@optimystic/db-p2p 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +52 -0
- package/dist/index.min.js.map +7 -0
- package/dist/src/cluster/client.d.ts +12 -0
- package/dist/src/cluster/client.d.ts.map +1 -0
- package/dist/src/cluster/client.js +65 -0
- package/dist/src/cluster/client.js.map +1 -0
- package/dist/src/cluster/cluster-repo.d.ts +79 -0
- package/dist/src/cluster/cluster-repo.d.ts.map +1 -0
- package/dist/src/cluster/cluster-repo.js +613 -0
- package/dist/src/cluster/cluster-repo.js.map +1 -0
- package/dist/src/cluster/partition-detector.d.ts +59 -0
- package/dist/src/cluster/partition-detector.d.ts.map +1 -0
- package/dist/src/cluster/partition-detector.js +129 -0
- package/dist/src/cluster/partition-detector.js.map +1 -0
- package/dist/src/cluster/service.d.ts +49 -0
- package/dist/src/cluster/service.d.ts.map +1 -0
- package/dist/src/cluster/service.js +107 -0
- package/dist/src/cluster/service.js.map +1 -0
- package/dist/src/index.d.ts +29 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +29 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/it-utility.d.ts +4 -0
- package/dist/src/it-utility.d.ts.map +1 -0
- package/dist/src/it-utility.js +32 -0
- package/dist/src/it-utility.js.map +1 -0
- package/dist/src/libp2p-key-network.d.ts +59 -0
- package/dist/src/libp2p-key-network.d.ts.map +1 -0
- package/dist/src/libp2p-key-network.js +278 -0
- package/dist/src/libp2p-key-network.js.map +1 -0
- package/dist/src/libp2p-node.d.ts +28 -0
- package/dist/src/libp2p-node.d.ts.map +1 -0
- package/dist/src/libp2p-node.js +270 -0
- package/dist/src/libp2p-node.js.map +1 -0
- package/dist/src/logger.d.ts +3 -0
- package/dist/src/logger.d.ts.map +1 -0
- package/dist/src/logger.js +6 -0
- package/dist/src/logger.js.map +1 -0
- package/dist/src/network/get-network-manager.d.ts +4 -0
- package/dist/src/network/get-network-manager.d.ts.map +1 -0
- package/dist/src/network/get-network-manager.js +17 -0
- package/dist/src/network/get-network-manager.js.map +1 -0
- package/dist/src/network/network-manager-service.d.ts +82 -0
- package/dist/src/network/network-manager-service.d.ts.map +1 -0
- package/dist/src/network/network-manager-service.js +283 -0
- package/dist/src/network/network-manager-service.js.map +1 -0
- package/dist/src/peer-utils.d.ts +2 -0
- package/dist/src/peer-utils.d.ts.map +1 -0
- package/dist/src/peer-utils.js +28 -0
- package/dist/src/peer-utils.js.map +1 -0
- package/dist/src/protocol-client.d.ts +12 -0
- package/dist/src/protocol-client.d.ts.map +1 -0
- package/dist/src/protocol-client.js +34 -0
- package/dist/src/protocol-client.js.map +1 -0
- package/dist/src/repo/client.d.ts +17 -0
- package/dist/src/repo/client.d.ts.map +1 -0
- package/dist/src/repo/client.js +82 -0
- package/dist/src/repo/client.js.map +1 -0
- package/dist/src/repo/cluster-coordinator.d.ts +59 -0
- package/dist/src/repo/cluster-coordinator.d.ts.map +1 -0
- package/dist/src/repo/cluster-coordinator.js +539 -0
- package/dist/src/repo/cluster-coordinator.js.map +1 -0
- package/dist/src/repo/coordinator-repo.d.ts +29 -0
- package/dist/src/repo/coordinator-repo.d.ts.map +1 -0
- package/dist/src/repo/coordinator-repo.js +102 -0
- package/dist/src/repo/coordinator-repo.js.map +1 -0
- package/dist/src/repo/redirect.d.ts +14 -0
- package/dist/src/repo/redirect.d.ts.map +1 -0
- package/dist/src/repo/redirect.js +9 -0
- package/dist/src/repo/redirect.js.map +1 -0
- package/dist/src/repo/service.d.ts +52 -0
- package/dist/src/repo/service.d.ts.map +1 -0
- package/dist/src/repo/service.js +181 -0
- package/dist/src/repo/service.js.map +1 -0
- package/dist/src/repo/types.d.ts +7 -0
- package/dist/src/repo/types.d.ts.map +1 -0
- package/dist/src/repo/types.js +2 -0
- package/dist/src/repo/types.js.map +1 -0
- package/dist/src/routing/libp2p-known-peers.d.ts +4 -0
- package/dist/src/routing/libp2p-known-peers.d.ts.map +1 -0
- package/dist/src/routing/libp2p-known-peers.js +19 -0
- package/dist/src/routing/libp2p-known-peers.js.map +1 -0
- package/dist/src/routing/responsibility.d.ts +14 -0
- package/dist/src/routing/responsibility.d.ts.map +1 -0
- package/dist/src/routing/responsibility.js +45 -0
- package/dist/src/routing/responsibility.js.map +1 -0
- package/dist/src/routing/simple-cluster-coordinator.d.ts +23 -0
- package/dist/src/routing/simple-cluster-coordinator.d.ts.map +1 -0
- package/dist/src/routing/simple-cluster-coordinator.js +59 -0
- package/dist/src/routing/simple-cluster-coordinator.js.map +1 -0
- package/dist/src/storage/arachnode-fret-adapter.d.ts +65 -0
- package/dist/src/storage/arachnode-fret-adapter.d.ts.map +1 -0
- package/dist/src/storage/arachnode-fret-adapter.js +93 -0
- package/dist/src/storage/arachnode-fret-adapter.js.map +1 -0
- package/dist/src/storage/block-storage.d.ts +31 -0
- package/dist/src/storage/block-storage.d.ts.map +1 -0
- package/dist/src/storage/block-storage.js +154 -0
- package/dist/src/storage/block-storage.js.map +1 -0
- package/dist/src/storage/file-storage.d.ts +30 -0
- package/dist/src/storage/file-storage.d.ts.map +1 -0
- package/dist/src/storage/file-storage.js +127 -0
- package/dist/src/storage/file-storage.js.map +1 -0
- package/dist/src/storage/helpers.d.ts +3 -0
- package/dist/src/storage/helpers.d.ts.map +1 -0
- package/dist/src/storage/helpers.js +28 -0
- package/dist/src/storage/helpers.js.map +1 -0
- package/dist/src/storage/i-block-storage.d.ts +32 -0
- package/dist/src/storage/i-block-storage.d.ts.map +1 -0
- package/dist/src/storage/i-block-storage.js +2 -0
- package/dist/src/storage/i-block-storage.js.map +1 -0
- package/dist/src/storage/i-raw-storage.d.ts +20 -0
- package/dist/src/storage/i-raw-storage.d.ts.map +1 -0
- package/dist/src/storage/i-raw-storage.js +2 -0
- package/dist/src/storage/i-raw-storage.js.map +1 -0
- package/dist/src/storage/memory-storage.d.ts +27 -0
- package/dist/src/storage/memory-storage.d.ts.map +1 -0
- package/dist/src/storage/memory-storage.js +87 -0
- package/dist/src/storage/memory-storage.js.map +1 -0
- package/dist/src/storage/restoration-coordinator-v2.d.ts +63 -0
- package/dist/src/storage/restoration-coordinator-v2.d.ts.map +1 -0
- package/dist/src/storage/restoration-coordinator-v2.js +157 -0
- package/dist/src/storage/restoration-coordinator-v2.js.map +1 -0
- package/dist/src/storage/ring-selector.d.ts +56 -0
- package/dist/src/storage/ring-selector.d.ts.map +1 -0
- package/dist/src/storage/ring-selector.js +118 -0
- package/dist/src/storage/ring-selector.js.map +1 -0
- package/dist/src/storage/storage-monitor.d.ts +23 -0
- package/dist/src/storage/storage-monitor.d.ts.map +1 -0
- package/dist/src/storage/storage-monitor.js +40 -0
- package/dist/src/storage/storage-monitor.js.map +1 -0
- package/dist/src/storage/storage-repo.d.ts +17 -0
- package/dist/src/storage/storage-repo.d.ts.map +1 -0
- package/dist/src/storage/storage-repo.js +267 -0
- package/dist/src/storage/storage-repo.js.map +1 -0
- package/dist/src/storage/struct.d.ts +29 -0
- package/dist/src/storage/struct.d.ts.map +1 -0
- package/dist/src/storage/struct.js +2 -0
- package/dist/src/storage/struct.js.map +1 -0
- package/dist/src/sync/client.d.ts +27 -0
- package/dist/src/sync/client.d.ts.map +1 -0
- package/dist/src/sync/client.js +32 -0
- package/dist/src/sync/client.js.map +1 -0
- package/dist/src/sync/protocol.d.ts +58 -0
- package/dist/src/sync/protocol.d.ts.map +1 -0
- package/dist/src/sync/protocol.js +12 -0
- package/dist/src/sync/protocol.js.map +1 -0
- package/dist/src/sync/service.d.ts +62 -0
- package/dist/src/sync/service.d.ts.map +1 -0
- package/dist/src/sync/service.js +168 -0
- package/dist/src/sync/service.js.map +1 -0
- package/package.json +73 -0
- package/readme.md +497 -0
- package/src/cluster/client.ts +63 -0
- package/src/cluster/cluster-repo.ts +711 -0
- package/src/cluster/partition-detector.ts +158 -0
- package/src/cluster/service.ts +156 -0
- package/src/index.ts +30 -0
- package/src/it-utility.ts +36 -0
- package/src/libp2p-key-network.ts +334 -0
- package/src/libp2p-node.ts +335 -0
- package/src/logger.ts +9 -0
- package/src/network/get-network-manager.ts +17 -0
- package/src/network/network-manager-service.ts +334 -0
- package/src/peer-utils.ts +24 -0
- package/src/protocol-client.ts +54 -0
- package/src/repo/client.ts +112 -0
- package/src/repo/cluster-coordinator.ts +592 -0
- package/src/repo/coordinator-repo.ts +137 -0
- package/src/repo/redirect.ts +17 -0
- package/src/repo/service.ts +219 -0
- package/src/repo/types.ts +7 -0
- package/src/routing/libp2p-known-peers.ts +26 -0
- package/src/routing/responsibility.ts +63 -0
- package/src/routing/simple-cluster-coordinator.ts +70 -0
- package/src/storage/arachnode-fret-adapter.ts +128 -0
- package/src/storage/block-storage.ts +182 -0
- package/src/storage/file-storage.ts +163 -0
- package/src/storage/helpers.ts +29 -0
- package/src/storage/i-block-storage.ts +40 -0
- package/src/storage/i-raw-storage.ts +30 -0
- package/src/storage/memory-storage.ts +108 -0
- package/src/storage/restoration-coordinator-v2.ts +191 -0
- package/src/storage/ring-selector.ts +155 -0
- package/src/storage/storage-monitor.ts +59 -0
- package/src/storage/storage-repo.ts +320 -0
- package/src/storage/struct.ts +34 -0
- package/src/sync/client.ts +42 -0
- package/src/sync/protocol.ts +71 -0
- package/src/sync/service.ts +229 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.OptimysticDbP2P = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
+
"use strict";var OptimysticDbP2P=(()=>{var aE=Object.create;var Xc=Object.defineProperty;var cE=Object.getOwnPropertyDescriptor;var lE=Object.getOwnPropertyNames;var uE=Object.getPrototypeOf,hE=Object.prototype.hasOwnProperty;var re=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var A=(r,e)=>()=>(r&&(e=r(r=0)),e);var He=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ve=(r,e)=>{for(var t in e)Xc(r,t,{get:e[t],enumerable:!0})},gg=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of lE(e))!hE.call(r,n)&&n!==t&&Xc(r,n,{get:()=>e[n],enumerable:!(s=cE(e,n))||s.enumerable});return r};var we=(r,e,t)=>(t=r!=null?aE(uE(r)):{},gg(e||!r||!r.__esModule?Xc(t,"default",{value:r,enumerable:!0}):t,r)),dE=r=>gg(Xc({},"__esModule",{value:!0}),r);function Bs(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}var ra=A(()=>{});function ie(r=0){return Bs(pd.Buffer.alloc(r))}function je(r=0){return Bs(pd.Buffer.allocUnsafe(r))}var pd,nt=A(()=>{pd=re("node:buffer");ra()});function Le(r){if(r<vE)return 1;if(r<EE)return 2;if(r<SE)return 3;if(r<md)return 4;if(r<gd)return 5;if(r<yd)return 6;if(r<bd)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ko(r,e,t=0){switch(Le(r)){case 8:e[t++]=r&255|pe,r/=128;case 7:e[t++]=r&255|pe,r/=128;case 6:e[t++]=r&255|pe,r/=128;case 5:e[t++]=r&255|pe,r/=128;case 4:e[t++]=r&255|pe,r>>>=7;case 3:e[t++]=r&255|pe,r>>>=7;case 2:e[t++]=r&255|pe,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function IE(r,e,t=0){switch(Le(r)){case 8:e.set(t++,r&255|pe),r/=128;case 7:e.set(t++,r&255|pe),r/=128;case 6:e.set(t++,r&255|pe),r/=128;case 5:e.set(t++,r&255|pe),r/=128;case 4:e.set(t++,r&255|pe),r>>>=7;case 3:e.set(t++,r&255|pe),r>>>=7;case 2:e.set(t++,r&255|pe),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function wd(r,e){let t=r[e],s=0;if(s+=t&bt,t<pe||(t=r[e+1],s+=(t&bt)<<7,t<pe)||(t=r[e+2],s+=(t&bt)<<14,t<pe)||(t=r[e+3],s+=(t&bt)<<21,t<pe)||(t=r[e+4],s+=(t&bt)*md,t<pe)||(t=r[e+5],s+=(t&bt)*gd,t<pe)||(t=r[e+6],s+=(t&bt)*yd,t<pe)||(t=r[e+7],s+=(t&bt)*bd,t<pe))return s;throw new RangeError("Could not decode varint")}function _E(r,e){let t=r.get(e),s=0;if(s+=t&bt,t<pe||(t=r.get(e+1),s+=(t&bt)<<7,t<pe)||(t=r.get(e+2),s+=(t&bt)<<14,t<pe)||(t=r.get(e+3),s+=(t&bt)<<21,t<pe)||(t=r.get(e+4),s+=(t&bt)*md,t<pe)||(t=r.get(e+5),s+=(t&bt)*gd,t<pe)||(t=r.get(e+6),s+=(t&bt)*yd,t<pe)||(t=r.get(e+7),s+=(t&bt)*bd,t<pe))return s;throw new RangeError("Could not decode varint")}function rr(r,e,t=0){return e==null&&(e=je(Le(r))),e instanceof Uint8Array?ko(r,e,t):IE(r,e,t)}function as(r,e=0){return r instanceof Uint8Array?wd(r,e):_E(r,e)}var vE,EE,SE,md,gd,yd,bd,pe,bt,wr=A(()=>{nt();vE=Math.pow(2,7),EE=Math.pow(2,14),SE=Math.pow(2,21),md=Math.pow(2,28),gd=Math.pow(2,35),yd=Math.pow(2,42),bd=Math.pow(2,49),pe=128,bt=127});function Ye(r,e){return Bs(wg.Buffer.concat(r,e))}var wg,Kr=A(()=>{wg=re("node:buffer");ra()});function ae(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Kt=A(()=>{});function xg(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let s of r){let n=t+s.byteLength;if(e<n)return{buf:s,index:e-t};t=n}throw new RangeError("index is out of bounds")}function el(r){return!!r?.[vg]}var vg,W,ot=A(()=>{nt();Kr();Kt();vg=Symbol.for("@achingbrain/uint8arraylist");W=class r{bufs;length;[vg]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let s of e)if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.push(s);else if(el(s))t+=s.byteLength,this.bufs.push(...s.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let s of e.reverse())if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.unshift(s);else if(el(s))t+=s.byteLength,this.bufs.unshift(...s.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=xg(this.bufs,e);return t.buf[t.index]}set(e,t){let s=xg(this.bufs,e);s.buf[s.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let s=0;s<e.length;s++)this.set(t+s,e[s]);else if(el(e))for(let s=0;s<e.length;s++)this.set(t+s,e.get(s));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:s,length:n}=this._subList(e,t);return Ye(s,n)}subarray(e,t){let{bufs:s,length:n}=this._subList(e,t);return s.length===1?s[0]:Ye(s,n)}sublist(e,t){let{bufs:s,length:n}=this._subList(e,t),o=new r;return o.length=n,o.bufs=[...s],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let s=[],n=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=n,c=a+i.byteLength;if(n=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){s.push(i);break}let h=e-a;s.push(i.subarray(h,h+(t-e)));break}if(l){if(e===0){s.push(i);continue}s.push(i.subarray(e-a));continue}if(u){if(t===c){s.push(i);break}s.push(i.subarray(0,t-a));break}s.push(i)}return{bufs:s,length:t-e}}indexOf(e,t=0){if(!el(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let s=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let n=s.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let h=0;h<o;h++)i[h]=-1;for(let h=0;h<n;h++)i[s[h]]=h;let a=i,c=this.byteLength-s.byteLength,l=s.byteLength-1,u;for(let h=t;h<=c;h+=u){u=0;for(let d=l;d>=0;d--){let f=this.get(h+d);if(s[d]!==f){u=Math.max(1,d-a[f]);break}}if(u===0)return h}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let s=je(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt8(0,t),this.write(s,e)}getInt16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt16(0,t)}setInt16(e,t,s){let n=ie(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,s),this.write(n,e)}getInt32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt32(0,t)}setInt32(e,t,s){let n=ie(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,s),this.write(n,e)}getBigInt64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigInt64(0,t)}setBigInt64(e,t,s){let n=ie(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,s),this.write(n,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let s=je(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint8(0,t),this.write(s,e)}getUint16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint16(0,t)}setUint16(e,t,s){let n=ie(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,s),this.write(n,e)}getUint32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint32(0,t)}setUint32(e,t,s){let n=ie(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,s),this.write(n,e)}getBigUint64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigUint64(0,t)}setBigUint64(e,t,s){let n=ie(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,s),this.write(n,e)}getFloat32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat32(0,t)}setFloat32(e,t,s){let n=ie(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,s),this.write(n,e)}getFloat64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat64(0,t)}setFloat64(e,t,s){let n=ie(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,s),this.write(n,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ae(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let s=new r;return s.bufs=e,t==null&&(t=e.reduce((n,o)=>n+o.byteLength,0)),s.length=t,s}}});var T9,Sg=A(()=>{T9=Symbol.for("@libp2p/connection")});var Ig=A(()=>{});var _g=A(()=>{});var Ag=A(()=>{});var k9,Cg=A(()=>{k9=Symbol.for("@libp2p/content-routing")});var Ge,Mo,oa,Oo,Tg=A(()=>{Ge=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Mo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},oa=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},Oo=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}});var Pg=A(()=>{});var kg=A(()=>{});var Dg=A(()=>{});var Mg=A(()=>{});var Og=A(()=>{});var R9,Lg=A(()=>{R9=Symbol.for("@libp2p/peer-discovery")});var B9,Rg=A(()=>{B9=Symbol.for("@libp2p/peer-id")});var Ng=A(()=>{});var U9,Bg=A(()=>{U9=Symbol.for("@libp2p/peer-routing")});var Fg=A(()=>{});var Ug=A(()=>{});var Kg=A(()=>{});var Hg=A(()=>{});var zg=A(()=>{});var qg=A(()=>{});var $g=A(()=>{});var q9,Gg,Vg=A(()=>{q9=Symbol.for("@libp2p/transport");(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Gg||(Gg={}))});var Wg,J,jg=A(()=>{Wg=re("node:events"),J=(r,...e)=>{try{(0,Wg.setMaxListeners)(r,...e)}catch{}}});var Xe,Ze=A(()=>{jg();Xe=class extends EventTarget{#e=new Map;constructor(){super(),J(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,s){super.addEventListener(e,t,s);let n=this.#e.get(e);n==null&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(s!==!0&&s!==!1&&s?.once)??!1})}removeEventListener(e,t,s){super.removeEventListener(e.toString(),t??null,s);let n=this.#e.get(e);n!=null&&(n=n.filter(({callback:o})=>o!==t),this.#e.set(e,n))}dispatchEvent(e){let t=super.dispatchEvent(e),s=this.#e.get(e.type);return s==null||(s=s.filter(({once:n})=>!n),this.#e.set(e.type,s)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}});var j9,Y9,Us=A(()=>{Sg();Ig();_g();Ag();Cg();Tg();Pg();kg();Dg();Mg();Og();Lg();Rg();Ng();Bg();Fg();Ug();Kg();Hg();zg();qg();$g();Vg();Ze();j9=Symbol.for("@libp2p/service-capabilities"),Y9=Symbol.for("@libp2p/service-dependencies")});function Yg(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function nr(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")}function Xg(r){return new TextEncoder().encode(r)}function Zg(r){return new TextDecoder().decode(r)}var vD,ls=A(()=>{vD=new Uint8Array(0)});function PE(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var n=0;n<r.length;n++){var o=r.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,w=p.length;y!==w&&p[y]===0;)y++,m++;for(var b=(w-y)*u+1>>>0,x=new Uint8Array(b);y!==w;){for(var E=p[y],P=0,T=b-1;(E!==0||P<g)&&T!==-1;T--,P++)E+=256*x[T]>>>0,x[T]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");g=P,y++}for(var D=b-g;D!==b&&x[D]===0;)D++;for(var v=c.repeat(m);D<b;++D)v+=r.charAt(x[D]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var w=(p.length-m)*l+1>>>0,b=new Uint8Array(w);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var E=0,P=w-1;(x!==0||E<y)&&P!==-1;P--,E++)x+=a*b[P]>>>0,b[P]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=E,m++}if(p[m]!==" "){for(var T=w-y;T!==w&&b[T]===0;)T++;for(var D=new Uint8Array(g+(w-T)),v=g;T!==w;)D[v++]=b[T++];return D}}}function f(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:f}}var kE,DE,Jg,e3=A(()=>{kE=PE,DE=kE,Jg=DE});function t3(r,e){return new Id({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function Lo({name:r,prefix:e,encode:t,decode:s}){return new _d(r,e,t,s)}function Ks({name:r,prefix:e,alphabet:t}){let{encode:s,decode:n}=Jg(t,r);return Lo({prefix:e,name:r,encode:s,decode:o=>nr(n(o))})}function ME(r,e,t,s){let n=r.length;for(;r[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),i=0,a=0,c=0;for(let l=0;l<n;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${s} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function OE(r,e,t){let s=e[e.length-1]==="=",n=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),s)for(;(o.length*t&7)!==0;)o+="=";return o}function LE(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Re({name:r,prefix:e,bitsPerChar:t,alphabet:s}){let n=LE(s);return Lo({prefix:e,name:r,encode(o){return OE(o,s,t)},decode(o){return ME(o,n,t,r)}})}var Ed,Sd,Id,_d,xr=A(()=>{ls();e3();Ed=class{name;prefix;baseEncode;constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Sd=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,s){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=s}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 t3(this,e)}},Id=class{decoders;constructor(e){this.decoders=e}or(e){return t3(this,e)}decode(e){let t=e[0],s=this.decoders[t];if(s!=null)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};_d=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new Ed(e,t,s),this.decoder=new Sd(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var Ad={};ve(Ad,{base58btc:()=>me,base58flickr:()=>RE});var me,RE,Vt=A(()=>{xr();me=Ks({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),RE=Ks({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var Cd={};ve(Cd,{base32:()=>or,base32hex:()=>UE,base32hexpad:()=>HE,base32hexpadupper:()=>zE,base32hexupper:()=>KE,base32pad:()=>BE,base32padupper:()=>FE,base32upper:()=>NE,base32z:()=>qE});var or,NE,BE,FE,UE,KE,HE,zE,qE,Ro=A(()=>{xr();or=Re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),NE=Re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),BE=Re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),FE=Re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),UE=Re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),KE=Re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),HE=Re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zE=Re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),qE=Re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Td={};ve(Td,{base36:()=>ia,base36upper:()=>$E});var ia,$E,Pd=A(()=>{xr();ia=Ks({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),$E=Ks({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});function n3(r,e,t){e=e||[],t=t||0;for(var s=t;r>=jE;)e[t++]=r&255|r3,r/=128;for(;r&WE;)e[t++]=r&255|r3,r>>>=7;return e[t]=r|0,n3.bytes=t-s+1,e}function kd(r,s){var t=0,s=s||0,n=0,o=s,i,a=r.length;do{if(o>=a)throw kd.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=n<28?(i&s3)<<n:(i&s3)*Math.pow(2,n),n+=7}while(i>=XE);return kd.bytes=o-s,t}var GE,r3,VE,WE,jE,YE,XE,s3,ZE,QE,JE,eS,tS,rS,sS,nS,oS,iS,aS,cS,aa,o3=A(()=>{GE=n3,r3=128,VE=127,WE=~VE,jE=Math.pow(2,31);YE=kd,XE=128,s3=127;ZE=Math.pow(2,7),QE=Math.pow(2,14),JE=Math.pow(2,21),eS=Math.pow(2,28),tS=Math.pow(2,35),rS=Math.pow(2,42),sS=Math.pow(2,49),nS=Math.pow(2,56),oS=Math.pow(2,63),iS=function(r){return r<ZE?1:r<QE?2:r<JE?3:r<eS?4:r<tS?5:r<rS?6:r<sS?7:r<nS?8:r<oS?9:10},aS={encode:GE,decode:YE,encodingLength:iS},cS=aS,aa=cS});function ca(r,e=0){return[aa.decode(r,e),aa.decode.bytes]}function No(r,e,t=0){return aa.encode(r,e,t),e}function Bo(r){return aa.encodingLength(r)}var al=A(()=>{o3()});function Hr(r,e){let t=e.byteLength,s=Bo(r),n=s+Bo(t),o=new Uint8Array(n+t);return No(r,o,0),No(t,o,s),o.set(e,n),new Fo(r,t,e,o)}function Ht(r){let e=nr(r),[t,s]=ca(e),[n,o]=ca(e.subarray(s)),i=e.subarray(s+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new Fo(t,n,i,e)}function i3(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Yg(r.bytes,t.bytes)}}var Fo,ir=A(()=>{ls();al();Fo=class{code;size;digest;bytes;constructor(e,t,s,n){this.code=e,this.size=t,this.digest=s,this.bytes=n}}});var Dd=A(()=>{});function a3(r,e){let{bytes:t,version:s}=r;switch(s){case 0:return uS(t,Md(r),e??me.encoder);default:return hS(t,Md(r),e??or.encoder)}}function Md(r){let e=c3.get(r);if(e==null){let t=new Map;return c3.set(r,t),t}return e}function lS(r,e){switch(r[0]){case"Q":{let t=e??me;return[me.prefix,t.decode(`${me.prefix}${r}`)]}case me.prefix:{let t=e??me;return[me.prefix,t.decode(r)]}case or.prefix:{let t=e??or;return[or.prefix,t.decode(r)]}case ia.prefix:{let t=e??ia;return[ia.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function uS(r,e,t){let{prefix:s}=t;if(s!==me.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(s);if(n==null){let o=t.encode(r).slice(1);return e.set(s,o),o}else return n}function hS(r,e,t){let{prefix:s}=t,n=e.get(s);if(n==null){let o=t.encode(r);return e.set(s,o),o}else return n}function l3(r,e,t){let s=Bo(r),n=s+Bo(e),o=new Uint8Array(n+t.byteLength);return No(r,o,0),No(e,o,s),o.set(t,n),o}var c3,De,la,dS,fS,zr=A(()=>{Ro();Pd();Vt();ls();ir();al();Dd();c3=new WeakMap;De=class r{code;version;multihash;bytes;"/";constructor(e,t,s,n){this.code=t,this.version=e,this.multihash=s,this.bytes=n,this["/"]=n}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==la)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==dS)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,s=Hr(e,t);return r.createV1(this.code,s)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let s=t;return s!=null&&e.code===s.code&&e.version===s.version&&i3(e.multihash,s.multihash)}toString(e){return a3(this,e)}toJSON(){return{"/":a3(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:s,code:n,multihash:o,bytes:i}=t;return new r(s,n,o,i??l3(s,n,o.bytes))}else if(t[fS]===!0){let{version:s,multihash:n,code:o}=t,i=Ht(n);return r.create(s,o,i)}else return null}static create(e,t,s){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(s.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==la)throw new Error(`Version 0 CID must use dag-pb (code: ${la}) block encoding`);return new r(e,t,s,s.bytes)}case 1:{let n=l3(e,t,s.bytes);return new r(e,t,s,n)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,la,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,s]=r.decodeFirst(e);if(s.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),s=t.size-t.multihashSize,n=nr(e.subarray(s,s+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new Fo(t.multihashCode,t.digestSize,o,n);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,s=()=>{let[h,d]=ca(e.subarray(t));return t+=d,h},n=s(),o=la;if(n===18?(n=0,t=0):o=s(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=s(),c=s(),l=t+c,u=l-i;return{version:n,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[s,n]=lS(e,t),o=r.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Md(o).set(s,e),o}};la=112,dS=18;fS=Symbol.for("@ipld/js-cid/CID")});var Od={};ve(Od,{identity:()=>Er});function mS(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Hr(u3,h3(r))}var u3,pS,h3,Er,pn=A(()=>{ls();ir();u3=0,pS="identity",h3=nr;Er={code:u3,name:pS,encode:h3,digest:mS}});var Ld={};ve(Ld,{base10:()=>gS});var gS,d3=A(()=>{xr();gS=Ks({prefix:"9",name:"base10",alphabet:"0123456789"})});var Rd={};ve(Rd,{base16:()=>yS,base16upper:()=>bS});var yS,bS,f3=A(()=>{xr();yS=Re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),bS=Re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var Nd={};ve(Nd,{base2:()=>wS});var wS,p3=A(()=>{xr();wS=Re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var Bd={};ve(Bd,{base256emoji:()=>IS});function ES(r){return r.reduce((e,t)=>(e+=xS[t],e),"")}function SS(r){let e=[];for(let t of r){let s=t.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${t}`);let n=vS[s];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var m3,xS,vS,IS,g3=A(()=>{xr();m3=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),xS=m3.reduce((r,e,t)=>(r[t]=e,r),[]),vS=m3.reduce((r,e,t)=>{let s=e.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${e}`);return r[s]=t,r},[]);IS=Lo({prefix:"\u{1F680}",name:"base256emoji",encode:ES,decode:SS})});var Kd={};ve(Kd,{base64:()=>Fd,base64pad:()=>_S,base64url:()=>Ud,base64urlpad:()=>AS});var Fd,_S,Ud,AS,cl=A(()=>{xr();Fd=Re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_S=Re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ud=Re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),AS=Re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var Hd={};ve(Hd,{base8:()=>CS});var CS,y3=A(()=>{xr();CS=Re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var zd={};ve(zd,{identity:()=>TS});var TS,b3=A(()=>{ls();xr();TS=Lo({prefix:"\0",name:"identity",encode:r=>Zg(r),decode:r=>Xg(r)})});var WD,jD,w3=A(()=>{WD=new TextEncoder,jD=new TextDecoder});var x3=A(()=>{ls()});function $d({name:r,code:e,encode:t,minDigestLength:s,maxDigestLength:n}){return new qd(r,e,t,s,n)}function v3(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Hr(e,r)}var DS,qd,Gd=A(()=>{ir();DS=20;qd=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,s,n,o){this.name=e,this.code=t,this.encode=s,this.minDigestLength=n??DS,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let s=this.encode(e);return s instanceof Uint8Array?v3(s,this.code,t?.truncate):s.then(n=>v3(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var Wd={};ve(Wd,{sha256:()=>Qe,sha512:()=>MS});var Vd,Qe,MS,us=A(()=>{Vd=we(re("crypto"),1);ls();Gd();Qe=$d({name:"sha2-256",code:18,encode:r=>nr(Vd.default.createHash("sha256").update(r).digest())}),MS=$d({name:"sha2-512",code:19,encode:r=>nr(Vd.default.createHash("sha512").update(r).digest())})});var S3=A(()=>{});var I3=A(()=>{});var _3=A(()=>{});var A3=A(()=>{});var C3=A(()=>{S3();I3();_3();Dd();A3()});var jd=A(()=>{ls();zr();ir();Gd();al();C3()});var ua,aM,Yd=A(()=>{d3();f3();p3();g3();Ro();Pd();Vt();cl();y3();b3();w3();x3();pn();us();jd();ua={...zd,...Nd,...Hd,...Ld,...Rd,...Cd,...Td,...Ad,...Kd,...Bd},aM={...Wd,...Od}});function P3(r,e,t,s){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:s}}}var T3,Xd,OS,ll,Zd=A(()=>{Yd();nt();T3=P3("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Xd=P3("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=je(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),OS={utf8:T3,"utf-8":T3,hex:ua.base16,latin1:Xd,ascii:Xd,binary:Xd,...ua},ll=OS});function L(r,e="utf8"){let t=ll[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?Bs(k3.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var k3,ge=A(()=>{k3=re("node:buffer");Zd();ra()});function K(r,e="utf8"){let t=ll[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return e==="utf8"||e==="utf-8"?D3.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var D3,Se=A(()=>{D3=re("node:buffer");Zd()});function hs(r,e={offset:0}){let t=r[e.offset]&LS;if(e.offset++,M3[t]!=null)return M3[t](r,e);throw new Error("No decoder for tag "+t)}function da(r,e){let t=0;if((r[e.offset]&Qd)===Qd){let s=r[e.offset]&RS,n="0x";e.offset++;for(let o=0;o<s;o++,e.offset++)n+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(n,16)}else t=r[e.offset],e.offset++;return t}function ha(r,e){da(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let s=hs(r,e);if(s===null)break;t.push(s)}return t}function NS(r,e){let t=da(r,e),s=e.offset,n=e.offset+t,o=[];for(let i=s;i<n;i++)i===s&&r[i]===0||o.push(r[i]);return e.offset+=t,Uint8Array.from(o)}function BS(r,e){let t=da(r,e),s=e.offset+t,n=r[e.offset];e.offset++;let o=0,i=0;n<40?(o=0,i=n):n<80?(o=1,i=n-40):(o=2,i=n-80);let a=`${o}.${i}`,c=[];for(;e.offset<s;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function FS(r,e){return e.offset++,null}function US(r,e){let t=da(r,e),s=r[e.offset];e.offset++;let n=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,s!==0)throw new Error("Unused bits in bit string is unimplemented");return n}function KS(r,e){let t=da(r,e),s=r.subarray(e.offset,e.offset+t);return e.offset+=t,s}function HS(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new W;for(let s=0;s<e.length;s+=2)t.append(Uint8Array.from([parseInt(`${e[s]}${e[s+1]}`,16)]));return t}function ul(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=HS(r.byteLength);return new W(Uint8Array.from([e.byteLength|Qd]),e)}function Dt(r){let e=new W,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new W(Uint8Array.from([2]),ul(e),e)}function fa(r){let e=Uint8Array.from([0]),t=new W(e,r);return new W(Uint8Array.from([3]),ul(t),t)}function O3(r){return new W(Uint8Array.from([4]),ul(r),r)}function Sr(r,e=48){let t=new W;for(let s of r)t.append(s);return new W(Uint8Array.from([e]),ul(t),t)}var LS,Qd,RS,M3,Jd=A(()=>{ot();LS=parseInt("11111",2),Qd=parseInt("10000000",2),RS=parseInt("01111111",2),M3={0:ha,1:ha,2:NS,3:US,4:KS,5:FS,6:BS,16:ha,22:ha,48:ha}});async function L3(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function R3(r,e,t){let s=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let n=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},s,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(n,0,n.byteLength)}async function N3(r,e,t,s){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);s?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,e,t.subarray());return s?.signal?.throwIfAborted(),o}var ef=A(()=>{});function nf(r){let e=hs(r);return B3(e)}function B3(r){let e=r[1][1][0],t=1,s,n;if(e.byteLength===tf*2+1)return s=K(e.subarray(t,t+tf),"base64url"),n=K(e.subarray(t+tf),"base64url"),new mn({...GS,key_ops:["verify"],x:s,y:n});if(e.byteLength===rf*2+1)return s=K(e.subarray(t,t+rf),"base64url"),n=K(e.subarray(t+rf),"base64url"),new mn({...VS,key_ops:["verify"],x:s,y:n});if(e.byteLength===sf*2+1)return s=K(e.subarray(t,t+sf),"base64url"),n=K(e.subarray(t+sf),"base64url"),new mn({...WS,key_ops:["verify"],x:s,y:n});throw new Ge(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function F3(r){return Sr([Dt(Uint8Array.from([1])),O3(L(r.d??"","base64url")),Sr([K3(r.crv)],160),Sr([fa(new W(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function U3(r){return Sr([Dt(Uint8Array.from([1])),Sr([K3(r.crv)],160),Sr([fa(new W(Uint8Array.from([4]),L(r.x??"","base64url"),L(r.y??"","base64url")))],161)]).subarray()}function K3(r){if(r==="P-256")return zS;if(r==="P-384")return qS;if(r==="P-521")return $S;throw new Ge(`Invalid curve ${r}`)}async function H3(r="P-256"){let e=await L3(r);return new hl(e.privateKey)}var zS,qS,$S,GS,VS,WS,tf,rf,sf,of=A(()=>{Us();ot();ge();Se();Jd();z3();ef();zS=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),qS=Uint8Array.from([6,5,43,129,4,0,34]),$S=Uint8Array.from([6,5,43,129,4,0,35]),GS={ext:!0,kty:"EC",crv:"P-256"},VS={ext:!0,kty:"EC",crv:"P-384"},WS={ext:!0,kty:"EC",crv:"P-521"},tf=32,rf=48,sf=66});var mn,hl,z3=A(()=>{Vt();zr();pn();Kt();ft();of();ef();mn=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=U3(this.jwk)),this._raw}toMultihash(){return Er.digest(Ve(this))}toCID(){return De.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}async verify(e,t,s){return N3(this.jwk,t,e,s)}},hl=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new mn({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=F3(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}async sign(e,t){return R3(this.jwk,e,t)}}});function ZS(r){let t=gn.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",x:"",d:K(r,"base64url"),kty:"OKP"}}).export({format:"jwk"});if(t.x==null||t.x==="")throw new Error("Could not export JWK public key");return L(t.x,"base64url")}function q3(){let r=jS("ed25519",{publicKeyEncoding:{type:"spki",format:"jwk"},privateKeyEncoding:{type:"pkcs8",format:"jwk"}}),e=L(r.privateKey.d,"base64url"),t=L(r.publicKey.x,"base64url");return{privateKey:Ye([e,t],e.byteLength+t.byteLength),publicKey:t}}function $3(r,e){if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');let t,s;if(r.byteLength===dl)t=r.subarray(0,32),s=r.subarray(32);else if(r.byteLength===YS)t=r.subarray(0,32),s=ZS(t);else throw new TypeError('"key" must be 64 or 32 bytes in length.');let n=gn.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",d:K(t,"base64url"),x:K(s,"base64url"),kty:"OKP"}});return gn.default.sign(null,e instanceof Uint8Array?e:e.subarray(),n)}function G3(r,e,t){if(r.byteLength!==pa)throw new TypeError('"key" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==XS)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let s=gn.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:K(r,"base64url"),kty:"OKP"}});return gn.default.verify(null,t instanceof Uint8Array?t:t.subarray(),s,e)}var gn,jS,pa,dl,YS,XS,af=A(()=>{gn=we(re("crypto"),1);Kr();ge();Se();jS=gn.default.generateKeyPairSync,pa=32,dl=64,YS=32,XS=64});function cf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var W3=A(()=>{Kr();ge()});var ma,fl,j3=A(()=>{Vt();zr();pn();Kt();W3();ft();lf();af();ma=class{type="Ed25519";raw;constructor(e){this.raw=pl(e,pa)}toMultihash(){return Er.digest(Ve(this))}toCID(){return De.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}verify(e,t,s){s?.signal?.throwIfAborted();let n=G3(this.raw,t,e);return cf(n)?n.then(o=>(s?.signal?.throwIfAborted(),o)):n}},fl=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=pl(e,dl),this.publicKey=new ma(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let s=$3(this.raw,e);return cf(s)?s.then(n=>(t?.signal?.throwIfAborted(),n)):(t?.signal?.throwIfAborted(),s)}}});function uf(r){return r=pl(r,pa),new ma(r)}async function Y3(){let{privateKey:r,publicKey:e}=q3();return new fl(r,e)}function pl(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Ge(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var lf=A(()=>{Us();j3();af()});function X3(r,e,t){hf[0]=r,e[t]=Hs[0],e[t+1]=Hs[1],e[t+2]=Hs[2],e[t+3]=Hs[3]}function Z3(r,e){return Hs[0]=r[e],Hs[1]=r[e+1],Hs[2]=r[e+2],Hs[3]=r[e+3],hf[0]}function Q3(r,e,t){df[0]=r,e[t]=wt[0],e[t+1]=wt[1],e[t+2]=wt[2],e[t+3]=wt[3],e[t+4]=wt[4],e[t+5]=wt[5],e[t+6]=wt[6],e[t+7]=wt[7]}function J3(r,e){return wt[0]=r[e],wt[1]=r[e+1],wt[2]=r[e+2],wt[3]=r[e+3],wt[4]=r[e+4],wt[5]=r[e+5],wt[6]=r[e+6],wt[7]=r[e+7],df[0]}var hf,Hs,df,wt,ff=A(()=>{hf=new Float32Array([-0]),Hs=new Uint8Array(hf.buffer);df=new Float64Array([-0]),wt=new Uint8Array(df.buffer)});var QS,JS,Wt,yn,e6,pf=A(()=>{QS=BigInt(Number.MAX_SAFE_INTEGER),JS=BigInt(Number.MIN_SAFE_INTEGER),Wt=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,s=~this.hi>>>0;return t===0&&(s=s+1>>>0),-(t+s*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,s=~this.hi>>>0;return t===0&&(s=s+1>>>0),-(BigInt(t)+(BigInt(s)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,s=this.hi>>>24;return s===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:s<128?9:10}static fromBigInt(e){if(e===0n)return yn;if(e<QS&&e>JS)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let s=e>>32n,n=e-(s<<32n);return t&&(s=~s|0n,n=~n|0n,++n>e6&&(n=0n,++s>e6&&(s=0n))),new r(Number(n),Number(s))}static fromNumber(e){if(e===0)return yn;let t=e<0;t&&(e=-e);let s=e>>>0,n=(e-s)/4294967296>>>0;return t&&(n=~n>>>0,s=~s>>>0,++s>4294967295&&(s=0,++n>4294967295&&(n=0))),new r(s,n)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):yn}},yn=new Wt(0,0);yn.toBigInt=function(){return 0n};yn.zzEncode=yn.zzDecode=function(){return this};yn.length=function(){return 1};e6=4294967296n});function t6(r){let e=0,t=0;for(let s=0;s<r.length;++s)t=r.charCodeAt(s),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(s+1)&64512)===56320?(++s,e+=4):e+=3;return e}function r6(r,e,t){if(t-e<1)return"";let n,o=[],i=0,a;for(;e<t;)a=r[e++],a<128?o[i++]=a:a>191&&a<224?o[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,o)),i=0);return n!=null?(i>0&&n.push(String.fromCharCode.apply(String,o.slice(0,i))),n.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function mf(r,e,t){let s=t,n,o;for(let i=0;i<r.length;++i)n=r.charCodeAt(i),n<128?e[t++]=n:n<2048?(e[t++]=n>>6|192,e[t++]=n&63|128):(n&64512)===55296&&((o=r.charCodeAt(i+1))&64512)===56320?(n=65536+((n&1023)<<10)+(o&1023),++i,e[t++]=n>>18|240,e[t++]=n>>12&63|128,e[t++]=n>>6&63|128,e[t++]=n&63|128):(e[t++]=n>>12|224,e[t++]=n>>6&63|128,e[t++]=n&63|128);return t-s}var gf=A(()=>{});function Ir(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function ml(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}function bf(r){return new yf(r instanceof Uint8Array?r:r.subarray())}var yf,wf=A(()=>{wr();ff();pf();gf();yf=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Ir(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Ir(this,4);return ml(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ir(this,4);return ml(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ir(this,4);let e=Z3(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ir(this,4);let e=J3(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,s=this.pos+e;if(s>this.len)throw Ir(this,e);return this.pos+=e,t===s?new Uint8Array(0):this.buf.subarray(t,s)}string(){let e=this.bytes();return r6(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ir(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ir(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new Wt(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Ir(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Ir(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Ir(this,8);let e=ml(this.buf,this.pos+=4),t=ml(this.buf,this.pos+=4);return new Wt(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=wd(this.buf,this.pos);return this.pos+=Le(e),e}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 le(r,e,t){let s=bf(r);return e.decode(s,void 0,t)}var n6=A(()=>{wf()});function xf(r){let e=r??8192,t=e>>>1,s,n=e;return function(i){if(i<1||i>t)return je(i);n+i>e&&(s=je(e),n=0);let a=s.subarray(n,n+=i);return(n&7)!==0&&(n=(n|7)+1),a}}var o6=A(()=>{nt()});function vf(){}function t8(r){return globalThis.Buffer!=null?je(r):e8(r)}function Ef(r,e,t){e[t]=r&255}function r8(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function gl(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function ga(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function s8(r,e,t){e.set(r,t)}function n8(r,e,t){e.set(r,t)}function o8(r,e,t){r.length<40?mf(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(L(r),t)}function _f(){return new ya}var bn,Sf,e8,ya,If,Af=A(()=>{wr();nt();ge();ff();pf();o6();gf();bn=class{fn;len;next;val;constructor(e,t,s){this.fn=e,this.len=t,this.next=void 0,this.val=s}};Sf=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},e8=xf();ya=class{len;head;tail;states;constructor(){this.len=0,this.head=new bn(vf,0,0),this.tail=this.head,this.states=null}_push(e,t,s){return this.tail=this.tail.next=new bn(e,t,s),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new If((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(gl,10,Wt.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Wt.fromBigInt(e);return this._push(gl,t.length(),t)}uint64Number(e){return this._push(ko,Le(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=Wt.fromBigInt(e).zzEncode();return this._push(gl,t.length(),t)}sint64Number(e){let t=Wt.fromNumber(e).zzEncode();return this._push(gl,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ef,1,e?1:0)}fixed32(e){return this._push(ga,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Wt.fromBigInt(e);return this._push(ga,4,t.lo)._push(ga,4,t.hi)}fixed64Number(e){let t=Wt.fromNumber(e);return this._push(ga,4,t.lo)._push(ga,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(X3,4,e)}double(e){return this._push(Q3,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Ef,1,0):this.uint32(t)._push(s8,t,e)}string(e){let t=t6(e);return t!==0?this.uint32(t)._push(mf,t,e):this._push(Ef,1,0)}fork(){return this.states=new Sf(this),this.head=this.tail=new bn(vf,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 bn(vf,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,s=this.len;return this.reset().uint32(s),s!==0&&(this.tail.next=e.next,this.tail=t,this.len+=s),this}finish(){let e=this.head.next,t=t8(this.len),s=0;for(;e!=null;)e.fn(e.val,t,s),s+=e.len,e=e.next;return t}};If=class extends bn{next;constructor(e,t){super(r8,e,t),this.next=void 0}};globalThis.Buffer!=null&&(ya.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(n8,e,r),this},ya.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(o8,e,r),this})});function ue(r,e){let t=_f();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var i6=A(()=>{Af()});function yl(r,e,t,s){return{name:r,type:e,encode:t,decode:s}}var Uo,Cf=A(()=>{(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Uo||(Uo={}))});function Tf(r){function e(n){if(r[n.toString()]==null)throw new Error("Invalid enum value");return r[n]}let t=function(o,i){let a=e(o);i.int32(a)},s=function(o){let i=o.int32();return e(i)};return yl("enum",Uo.VARINT,t,s)}var a6=A(()=>{Cf()});function he(r,e){return yl("message",Uo.LENGTH_DELIMITED,r,e)}var c6=A(()=>{Cf()});var Ie,ba,zs=A(()=>{n6();i6();a6();c6();wf();Af();Ie=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},ba=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}});var ze,Pf,qr,kf,Df=A(()=>{zs();(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ze||(ze={}));(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Pf||(Pf={}));(function(r){r.codec=()=>Tf(Pf)})(ze||(ze={}));(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.Type!=null&&(s.uint32(8),ze.codec().encode(t.Type,s)),t.Data!=null&&(s.uint32(18),s.bytes(t.Data)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={},i=s==null?t.len:t.pos+s;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=ze.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})(qr||(qr={}));(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.Type!=null&&(s.uint32(8),ze.codec().encode(t.Type,s)),t.Data!=null&&(s.uint32(18),s.bytes(t.Data)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={},i=s==null?t.len:t.pos+s;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=ze.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})(kf||(kf={}))});function wa(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function $r(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function Ee(r,e,t=""){let s=wa(r),n=r?.length,o=e!==void 0;if(!s||o&&n!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=s?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function bl(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");$r(r.outputLen),$r(r.blockLen)}function Ko(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function h6(r,e){Ee(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function wn(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function wl(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function _r(r,e){return r<<32-e|r>>>e}function xn(r){if(Ee(r),d6)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=i8[r[t]];return e}function u6(r){if(r>=ds._0&&r<=ds._9)return r-ds._0;if(r>=ds.A&&r<=ds.F)return r-(ds.A-10);if(r>=ds.a&&r<=ds.f)return r-(ds.a-10)}function vn(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(d6)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let s=new Uint8Array(t);for(let n=0,o=0;n<t;n++,o+=2){let i=u6(r.charCodeAt(o)),a=u6(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}s[n]=i*16+a}return s}function Ar(...r){let e=0;for(let s=0;s<r.length;s++){let n=r[s];Ee(n),e+=n.length}let t=new Uint8Array(e);for(let s=0,n=0;s<r.length;s++){let o=r[s];t.set(o,n),n+=o.length}return t}function f6(r,e={}){let t=(n,o)=>r(o).update(n).digest(),s=r(void 0);return t.outputLen=s.outputLen,t.blockLen=s.blockLen,t.create=n=>r(n),Object.assign(t,e),Object.freeze(t)}function Ho(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var d6,i8,ds,p6,qs=A(()=>{d6=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",i8=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));ds={_0:48,_9:57,A:65,F:70,a:97,f:102};p6=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])})});function Gr(r){if(isNaN(r)||r<=0)throw new Ge("random bytes length must be a Number bigger than 0");return Ho(r)}var m6=A(()=>{Us();qs()});function g6(r,e,t){return r&e^~r&t}function y6(r,e,t){return r&e^r&t^e&t}var xl,fs,b6=A(()=>{qs();xl=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,s,n){this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=wl(this.buffer)}update(e){Ko(this),Ee(e);let{view:t,buffer:s,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(n-this.pos,o-i);if(a===n){let c=wl(e);for(;n<=o-i;i+=n)this.process(c,i);continue}s.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ko(this),h6(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,wn(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(s,0),i=0);for(let h=i;h<n;h++)t[h]=0;s.setBigUint64(n-8,BigInt(this.length*8),o),this.process(s,0);let a=wl(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:s,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%t&&e.buffer.set(s),e}clone(){return this._cloneInto()}},fs=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var a8,$s,Mf,Of,zo,Lf=A(()=>{b6();qs();a8=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),$s=new Uint32Array(64),Mf=class extends xl{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:s,D:n,E:o,F:i,G:a,H:c}=this;return[e,t,s,n,o,i,a,c]}set(e,t,s,n,o,i,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)$s[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let d=$s[h-15],f=$s[h-2],p=_r(d,7)^_r(d,18)^d>>>3,m=_r(f,17)^_r(f,19)^f>>>10;$s[h]=m+$s[h-7]+p+$s[h-16]|0}let{A:s,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){let d=_r(a,6)^_r(a,11)^_r(a,25),f=u+d+g6(a,c,l)+a8[h]+$s[h]|0,m=(_r(s,2)^_r(s,13)^_r(s,22))+y6(s,n,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=n,n=s,s=f+m|0}s=s+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(s,n,o,i,a,c,l,u)}roundClean(){wn($s)}destroy(){this.set(0,0,0,0,0,0,0,0),wn(this.buffer)}},Of=class extends Mf{A=fs[0]|0;B=fs[1]|0;C=fs[2]|0;D=fs[3]|0;E=fs[4]|0;F=fs[5]|0;G=fs[6]|0;H=fs[7]|0;constructor(){super(32)}},zo=f6(()=>new Of,p6(1))});var qo,xa,w6=A(()=>{Vt();zr();Kt();Rf();qo=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=va.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return De.createV1(114,this._multihash)}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}verify(e,t,s){return v6(this.jwk,t,e,s)}},xa=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=va.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}sign(e,t){return x6(this.jwk,e,t)}}});var va={};ve(va,{MAX_RSA_KEY_SIZE:()=>Nf,generateRSAKeyPair:()=>Gf,jwkToJWKKeyPair:()=>S6,jwkToPkcs1:()=>h8,jwkToPkix:()=>Kf,jwkToRSAPrivateKey:()=>$f,pkcs1MessageToJwk:()=>Ff,pkcs1MessageToRSAPrivateKey:()=>Hf,pkcs1ToJwk:()=>u8,pkcs1ToRSAPrivateKey:()=>E6,pkixMessageToJwk:()=>Uf,pkixMessageToRSAPublicKey:()=>qf,pkixToJwk:()=>d8,pkixToRSAPublicKey:()=>zf});function u8(r){let e=hs(r);return Ff(e)}function Ff(r){return{n:K(r[1],"base64url"),e:K(r[2],"base64url"),d:K(r[3],"base64url"),p:K(r[4],"base64url"),q:K(r[5],"base64url"),dp:K(r[6],"base64url"),dq:K(r[7],"base64url"),qi:K(r[8],"base64url"),kty:"RSA"}}function h8(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new Ge("JWK was missing components");return Sr([Dt(Uint8Array.from([0])),Dt(L(r.n,"base64url")),Dt(L(r.e,"base64url")),Dt(L(r.d,"base64url")),Dt(L(r.p,"base64url")),Dt(L(r.q,"base64url")),Dt(L(r.dp,"base64url")),Dt(L(r.dq,"base64url")),Dt(L(r.qi,"base64url"))]).subarray()}function d8(r){let e=hs(r,{offset:0});return Uf(e)}function Uf(r){let e=hs(r[1],{offset:0});return{kty:"RSA",n:K(e[0],"base64url"),e:K(e[1],"base64url")}}function Kf(r){if(r.n==null||r.e==null)throw new Ge("JWK was missing components");return Sr([l8,fa(Sr([Dt(L(r.n,"base64url")),Dt(L(r.e,"base64url"))]))]).subarray()}function E6(r){let e=hs(r);return Hf(e)}function Hf(r){let e=Ff(r);return $f(e)}function zf(r,e){if(r.byteLength>=c8)throw new Mo("Key size is too large");let t=hs(r,{offset:0});return qf(t,r,e)}function qf(r,e,t){let s=Uf(r);if(t==null){let n=zo(qr.encode({Type:ze.RSA,Data:e}));t=Hr(Bf,n)}return new qo(s,t)}function $f(r){if(_6(r)>Nf)throw new Ge("Key size is too large");let e=S6(r),t=zo(qr.encode({Type:ze.RSA,Data:Kf(e.publicKey)})),s=Hr(Bf,t);return new xa(e.privateKey,new qo(e.publicKey,s))}async function Gf(r){if(r>Nf)throw new Ge("Key size is too large");let e=await I6(r),t=zo(qr.encode({Type:ze.RSA,Data:Kf(e.publicKey)})),s=Hr(Bf,t);return new xa(e.privateKey,new qo(e.publicKey,s))}function S6(r){if(r==null)throw new Ge("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Nf,Bf,c8,l8,Vf=A(()=>{Us();Lf();ir();ge();Se();Df();Jd();w6();Rf();Nf=8192,Bf=18,c8=1062,l8=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0])});async function I6(r,e){let t=await f8("rsa",{modulusLength:r,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return e?.signal?.throwIfAborted(),{privateKey:t.privateKey,publicKey:t.publicKey}}function x6(r,e,t){t?.signal?.throwIfAborted();let s=vl.default.createSign("RSA-SHA256");if(e instanceof Uint8Array)s.update(e);else for(let n of e)s.update(n);return s.sign({format:"jwk",key:r})}function v6(r,e,t,s){s?.signal?.throwIfAborted();let n=vl.default.createVerify("RSA-SHA256");if(t instanceof Uint8Array)n.update(t);else for(let o of t)n.update(o);return n.verify({format:"jwk",key:r},e)}function _6(r){if(r.kty!=="RSA")throw new Ge("Invalid key type");if(r.n==null)throw new Ge("Invalid key modulus");return L(r.n,"base64url").length*8}var vl,A6,f8,Rf=A(()=>{vl=we(re("node:crypto"),1),A6=re("node:util");Us();ge();Vf();f8=(0,A6.promisify)(vl.default.generateKeyPair)});function Ea(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function C6(r){if(typeof r=="bigint"){if(!El(r))throw new Error("positive bigint expected, got "+r)}else $r(r);return r}function Sa(r){let e=C6(r).toString(16);return e.length&1?"0"+e:e}function T6(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?jf:BigInt("0x"+r)}function $o(r){return T6(xn(r))}function Yf(r){return T6(xn(p8(Ee(r)).reverse()))}function Sl(r,e){$r(e),r=C6(r);let t=vn(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Xf(r,e){return Sl(r,e).reverse()}function p8(r){return Uint8Array.from(r)}function m8(r,e,t){return El(r)&&El(e)&&El(t)&&e<=r&&r<t}function P6(r,e,t,s){if(!m8(e,t,s))throw new Error("expected valid "+r+": "+t+" <= n < "+s+", got "+e)}function Zf(r){let e;for(e=0;r>jf;r>>=Wf,e+=1);return e}function k6(r,e,t){if($r(r,"hashLen"),$r(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let s=g=>new Uint8Array(g),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=s(r),l=s(r),u=0,h=()=>{c.fill(1),l.fill(0),u=0},d=(...g)=>t(l,Ar(c,...g)),f=(g=n)=>{l=d(o,g),c=d(),g.length!==0&&(l=d(i,g),c=d())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,y=[];for(;g<e;){c=d();let w=c.slice();y.push(w),g+=c.length}return Ar(...y)};return(g,y)=>{h(),f(g);let w;for(;!(w=y(p()));)f();return h(),w}}function _a(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function s(o,i,a){let c=r[o];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}let n=(o,i)=>Object.entries(o).forEach(([a,c])=>s(a,c,i));n(e,!1),n(t,!0)}function Qf(r){let e=new WeakMap;return(t,...s)=>{let n=e.get(t);if(n!==void 0)return n;let o=r(t,...s);return e.set(t,o),o}}var jf,Wf,El,Ia,Il=A(()=>{qs();qs();jf=BigInt(0),Wf=BigInt(1);El=r=>typeof r=="bigint"&&jf<=r;Ia=r=>(Wf<<BigInt(r))-Wf});function Cr(r,e){let t=r%e;return t>=Mt?t:e+t}function jt(r,e,t){let s=r;for(;e-- >Mt;)s*=s,s%=t;return s}function D6(r,e){if(r===Mt)throw new Error("invert: expected non-zero number");if(e<=Mt)throw new Error("invert: expected positive modulus, got "+e);let t=Cr(r,e),s=e,n=Mt,o=xt,i=xt,a=Mt;for(;t!==Mt;){let l=s/t,u=s%t,h=n-i*l,d=o-a*l;s=t,t=u,n=i,o=a,i=h,a=d}if(s!==xt)throw new Error("invert: does not exist");return Cr(n,e)}function ep(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function F6(r,e){let t=(r.ORDER+xt)/L6,s=r.pow(e,t);return ep(r,s,e),s}function b8(r,e){let t=(r.ORDER-R6)/N6,s=r.mul(e,En),n=r.pow(s,t),o=r.mul(e,n),i=r.mul(r.mul(o,En),n),a=r.mul(o,r.sub(i,r.ONE));return ep(r,a,e),a}function w8(r){let e=Go(r),t=U6(r),s=t(e,e.neg(e.ONE)),n=t(e,s),o=t(e,e.neg(s)),i=(r+g8)/B6;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,s),h=a.mul(l,n),d=a.mul(l,o),f=a.eql(a.sqr(u),c),p=a.eql(a.sqr(h),c);l=a.cmov(l,u,f),u=a.cmov(d,h,p);let m=a.eql(a.sqr(u),c),g=a.cmov(l,u,m);return ep(a,g,c),g}}function U6(r){if(r<O6)throw new Error("sqrt is not defined for small field");let e=r-xt,t=0;for(;e%En===Mt;)e/=En,t++;let s=En,n=Go(r);for(;M6(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return F6;let o=n.pow(s,e),i=(e+xt)/En;return function(c,l){if(c.is0(l))return l;if(M6(c,l)!==1)throw new Error("Cannot find square root");let u=t,h=c.mul(c.ONE,o),d=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,m=c.sqr(d);for(;!c.eql(m,c.ONE);)if(p++,m=c.sqr(m),p===u)throw new Error("Cannot find square root");let g=xt<<BigInt(u-p-1),y=c.pow(h,g);u=p,h=c.sqr(y),d=c.mul(d,h),f=c.mul(f,y)}return f}}function x8(r){return r%L6===O6?F6:r%N6===R6?b8:r%B6===y8?w8(r):U6(r)}function tp(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=v8.reduce((s,n)=>(s[n]="function",s),e);return _a(r,t),r}function E8(r,e,t){if(t<Mt)throw new Error("invalid exponent, negatives unsupported");if(t===Mt)return r.ONE;if(t===xt)return e;let s=r.ONE,n=e;for(;t>Mt;)t&xt&&(s=r.mul(s,n)),n=r.sqr(n),t>>=xt;return s}function _l(r,e,t=!1){let s=new Array(e.length).fill(t?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(s[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(s[c]=r.mul(i,s[c]),r.mul(i,a)),o),s}function M6(r,e){let t=(r.ORDER-xt)/En,s=r.pow(e,t),n=r.eql(s,r.ONE),o=r.eql(s,r.ZERO),i=r.eql(s,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function S8(r,e){e!==void 0&&$r(e);let t=e!==void 0?e:r.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function Go(r,e={}){return new Jf(r,e)}function K6(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function rp(r){let e=K6(r);return e+Math.ceil(e/2)}function sp(r,e,t=!1){Ee(r);let s=r.length,n=K6(e),o=rp(e);if(s<16||s<o||s>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+s);let i=t?Yf(r):$o(r),a=Cr(i,e-xt)+xt;return t?Xf(a,n):Sl(a,n)}var Mt,xt,En,O6,L6,R6,g8,N6,y8,B6,v8,Jf,Al=A(()=>{Il();Mt=BigInt(0),xt=BigInt(1),En=BigInt(2),O6=BigInt(3),L6=BigInt(4),R6=BigInt(5),g8=BigInt(7),N6=BigInt(8),y8=BigInt(9),B6=BigInt(16);v8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];Jf=class{ORDER;BITS;BYTES;isLE;ZERO=Mt;ONE=xt;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Mt)throw new Error("invalid field: expected ORDER > 0, got "+e);let s;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(s=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:n,nByteLength:o}=S8(e,s);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Cr(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Mt<=e&&e<this.ORDER}is0(e){return e===Mt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&xt)===xt}neg(e){return Cr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Cr(e*e,this.ORDER)}add(e,t){return Cr(e+t,this.ORDER)}sub(e,t){return Cr(e-t,this.ORDER)}mul(e,t){return Cr(e*t,this.ORDER)}pow(e,t){return E8(this,e,t)}div(e,t){return Cr(e*D6(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return D6(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=x8(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Xf(e,this.BYTES):Sl(e,this.BYTES)}fromBytes(e,t=!1){Ee(e);let{_lengths:s,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(s){if(!s.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let l=new Uint8Array(n);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?Yf(e):$o(e);if(a&&(c=Cr(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return _l(this,e)}cmov(e,t,s){return s?t:e}}});function Aa(r,e){let t=e.negate();return r?t:e}function ap(r,e){let t=_l(r.Fp,e.map(s=>s.Z));return e.map((s,n)=>r.fromAffine(s.toAffine(t[n])))}function $6(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function np(r,e){$6(r,e);let t=Math.ceil(e/r)+1,s=2**(r-1),n=2**r,o=Ia(r),i=BigInt(r);return{windows:t,windowSize:s,mask:o,maxNumber:n,shiftBy:i}}function H6(r,e,t){let{windowSize:s,mask:n,maxNumber:o,shiftBy:i}=t,a=Number(r&n),c=r>>i;a>s&&(a-=o,c+=Sn);let l=e*s,u=l+Math.abs(a)-1,h=a===0,d=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:d,isNegF:f,offsetF:l}}function ip(r){return G6.get(r)||1}function z6(r){if(r!==Vo)throw new Error("invalid wNAF")}function V6(r,e,t,s){let n=e,o=r.ZERO,i=r.ZERO;for(;t>Vo||s>Vo;)t&Sn&&(o=o.add(n)),s&Sn&&(i=i.add(n)),n=n.double(),t>>=Sn,s>>=Sn;return{p1:o,p2:i}}function q6(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return tp(e),e}else return Go(r,{isLE:t})}function W6(r,e,t={},s){if(s===void 0&&(s=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Vo))throw new Error(`CURVE.${c} must be positive bigint`)}let n=q6(e.p,t.Fp,s),o=q6(e.n,t.Fn,s),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:o}}function j6(r,e){return function(s){let n=r(s);return{secretKey:n,publicKey:e(n)}}}var Vo,Sn,op,G6,Cl,Y6=A(()=>{Il();Al();Vo=BigInt(0),Sn=BigInt(1);op=new WeakMap,G6=new WeakMap;Cl=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,s=this.ZERO){let n=e;for(;t>Vo;)t&Sn&&(s=s.add(n)),n=n.double(),t>>=Sn;return s}precomputeWindow(e,t){let{windows:s,windowSize:n}=np(t,this.bits),o=[],i=e,a=i;for(let c=0;c<s;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE,i=np(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:d,offsetF:f}=H6(s,a,i);s=c,u?o=o.add(Aa(d,t[f])):n=n.add(Aa(h,t[l]))}return z6(s),{p:n,f:o}}wNAFUnsafe(e,t,s,n=this.ZERO){let o=np(e,this.bits);for(let i=0;i<o.windows&&s!==Vo;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=H6(s,i,o);if(s=a,!l){let h=t[c];n=n.add(u?h.negate():h)}}return z6(s),n}getPrecomputes(e,t,s){let n=op.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof s=="function"&&(n=s(n)),op.set(t,n))),n}cached(e,t,s){let n=ip(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)}unsafe(e,t,s,n){let o=ip(e);return o===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,s),t,n)}createCache(e,t){$6(t,this.bits),G6.set(e,t),op.delete(e)}hasCache(e){return ip(e)!==1}}});var Tl,cp,X6=A(()=>{qs();Tl=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(bl(e),Ee(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,n=new Uint8Array(s);n.set(t.length>s?e.create().update(t).digest():t);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),wn(n)}update(e){return Ko(this),this.iHash.update(e),this}digestInto(e){Ko(this),Ee(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:s,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},cp=(r,e,t)=>new Tl(r,e).update(t).digest();cp.create=(r,e)=>new Tl(r,e)});function I8(r,e,t){let[[s,n],[o,i]]=e,a=Z6(i*r,t),c=Z6(-n*r,t),l=r-a*s-c*o,u=-a*n-c*i,h=l<ps,d=u<ps;h&&(l=-l),d&&(u=-u);let f=Ia(Math.ceil(Zf(t)/2))+Wo;if(l<ps||l>=f||u<ps||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:d,k2:u}}function up(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function lp(r,e){let t={};for(let s of Object.keys(e))t[s]=r[s]===void 0?e[s]:r[s];return Ea(t.lowS,"lowS"),Ea(t.prehash,"prehash"),t.format!==void 0&&up(t.format),t}function J6(r,e={}){let t=W6("weierstrass",r,e),{Fp:s,Fn:n}=t,o=t.CURVE,{h:i,n:a}=o;_a(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!s.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=ty(s,n);function u(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(B,I,S){let{x:_,y:k}=I.toAffine(),O=s.toBytes(_);if(Ea(S,"isCompressed"),S){u();let N=!s.isOdd(k);return Ar(ey(N),O)}else return Ar(Uint8Array.of(4),O,s.toBytes(k))}function d(B){Ee(B,void 0,"Point");let{publicKey:I,publicKeyUncompressed:S}=l,_=B.length,k=B[0],O=B.subarray(1);if(_===I&&(k===2||k===3)){let N=s.fromBytes(O);if(!s.isValid(N))throw new Error("bad point: is not on curve, wrong x");let C=m(N),R;try{R=s.sqrt(C)}catch(ee){let te=ee instanceof Error?": "+ee.message:"";throw new Error("bad point: is not on curve, sqrt error"+te)}u();let U=s.isOdd(R);return(k&1)===1!==U&&(R=s.neg(R)),{x:N,y:R}}else if(_===S&&k===4){let N=s.BYTES,C=s.fromBytes(O.subarray(0,N)),R=s.fromBytes(O.subarray(N,N*2));if(!g(C,R))throw new Error("bad point: is not on curve");return{x:C,y:R}}else throw new Error(`bad point: got length ${_}, expected compressed=${I} or uncompressed=${S}`)}let f=e.toBytes||h,p=e.fromBytes||d;function m(B){let I=s.sqr(B),S=s.mul(I,B);return s.add(s.add(S,s.mul(B,o.a)),o.b)}function g(B,I){let S=s.sqr(I),_=m(B);return s.eql(S,_)}if(!g(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let y=s.mul(s.pow(o.a,Pl),_8),w=s.mul(s.sqr(o.b),BigInt(27));if(s.is0(s.add(y,w)))throw new Error("bad curve params: a or b");function b(B,I,S=!1){if(!s.isValid(I)||S&&s.is0(I))throw new Error(`bad point coordinate ${B}`);return I}function x(B){if(!(B instanceof v))throw new Error("Weierstrass Point expected")}function E(B){if(!c||!c.basises)throw new Error("no endo");return I8(B,c.basises,n.ORDER)}let P=Qf((B,I)=>{let{X:S,Y:_,Z:k}=B;if(s.eql(k,s.ONE))return{x:S,y:_};let O=B.is0();I==null&&(I=O?s.ONE:s.inv(k));let N=s.mul(S,I),C=s.mul(_,I),R=s.mul(k,I);if(O)return{x:s.ZERO,y:s.ZERO};if(!s.eql(R,s.ONE))throw new Error("invZ was invalid");return{x:N,y:C}}),T=Qf(B=>{if(B.is0()){if(e.allowInfinityPoint&&!s.is0(B.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:S}=B.toAffine();if(!s.isValid(I)||!s.isValid(S))throw new Error("bad point: x or y not field elements");if(!g(I,S))throw new Error("bad point: equation left != right");if(!B.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function D(B,I,S,_,k){return S=new v(s.mul(S.X,B),S.Y,S.Z),I=Aa(_,I),S=Aa(k,S),I.add(S)}class v{static BASE=new v(o.Gx,o.Gy,s.ONE);static ZERO=new v(s.ZERO,s.ONE,s.ZERO);static Fp=s;static Fn=n;X;Y;Z;constructor(I,S,_){this.X=b("x",I),this.Y=b("y",S,!0),this.Z=b("z",_),Object.freeze(this)}static CURVE(){return o}static fromAffine(I){let{x:S,y:_}=I||{};if(!I||!s.isValid(S)||!s.isValid(_))throw new Error("invalid affine point");if(I instanceof v)throw new Error("projective point not allowed");return s.is0(S)&&s.is0(_)?v.ZERO:new v(S,_,s.ONE)}static fromBytes(I){let S=v.fromAffine(p(Ee(I,void 0,"point")));return S.assertValidity(),S}static fromHex(I){return v.fromBytes(vn(I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,S=!0){return F.createCache(this,I),S||this.multiply(Pl),this}assertValidity(){T(this)}hasEvenY(){let{y:I}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(I)}equals(I){x(I);let{X:S,Y:_,Z:k}=this,{X:O,Y:N,Z:C}=I,R=s.eql(s.mul(S,C),s.mul(O,k)),U=s.eql(s.mul(_,C),s.mul(N,k));return R&&U}negate(){return new v(this.X,s.neg(this.Y),this.Z)}double(){let{a:I,b:S}=o,_=s.mul(S,Pl),{X:k,Y:O,Z:N}=this,C=s.ZERO,R=s.ZERO,U=s.ZERO,z=s.mul(k,k),ee=s.mul(O,O),te=s.mul(N,N),Z=s.mul(k,O);return Z=s.add(Z,Z),U=s.mul(k,N),U=s.add(U,U),C=s.mul(I,U),R=s.mul(_,te),R=s.add(C,R),C=s.sub(ee,R),R=s.add(ee,R),R=s.mul(C,R),C=s.mul(Z,C),U=s.mul(_,U),te=s.mul(I,te),Z=s.sub(z,te),Z=s.mul(I,Z),Z=s.add(Z,U),U=s.add(z,z),z=s.add(U,z),z=s.add(z,te),z=s.mul(z,Z),R=s.add(R,z),te=s.mul(O,N),te=s.add(te,te),z=s.mul(te,Z),C=s.sub(C,z),U=s.mul(te,ee),U=s.add(U,U),U=s.add(U,U),new v(C,R,U)}add(I){x(I);let{X:S,Y:_,Z:k}=this,{X:O,Y:N,Z:C}=I,R=s.ZERO,U=s.ZERO,z=s.ZERO,ee=o.a,te=s.mul(o.b,Pl),Z=s.mul(S,O),se=s.mul(_,N),xe=s.mul(k,C),$e=s.add(S,_),oe=s.add(O,N);$e=s.mul($e,oe),oe=s.add(Z,se),$e=s.sub($e,oe),oe=s.add(S,k);let rt=s.add(O,C);return oe=s.mul(oe,rt),rt=s.add(Z,xe),oe=s.sub(oe,rt),rt=s.add(_,k),R=s.add(N,C),rt=s.mul(rt,R),R=s.add(se,xe),rt=s.sub(rt,R),z=s.mul(ee,oe),R=s.mul(te,xe),z=s.add(R,z),R=s.sub(se,z),z=s.add(se,z),U=s.mul(R,z),se=s.add(Z,Z),se=s.add(se,Z),xe=s.mul(ee,xe),oe=s.mul(te,oe),se=s.add(se,xe),xe=s.sub(Z,xe),xe=s.mul(ee,xe),oe=s.add(oe,xe),Z=s.mul(se,oe),U=s.add(U,Z),Z=s.mul(rt,oe),R=s.mul($e,R),R=s.sub(R,Z),Z=s.mul($e,se),z=s.mul(rt,z),z=s.add(z,Z),new v(R,U,z)}subtract(I){return this.add(I.negate())}is0(){return this.equals(v.ZERO)}multiply(I){let{endo:S}=e;if(!n.isValidNot0(I))throw new Error("invalid scalar: out of range");let _,k,O=N=>F.cached(this,N,C=>ap(v,C));if(S){let{k1neg:N,k1:C,k2neg:R,k2:U}=E(I),{p:z,f:ee}=O(C),{p:te,f:Z}=O(U);k=ee.add(Z),_=D(S.beta,z,te,N,R)}else{let{p:N,f:C}=O(I);_=N,k=C}return ap(v,[_,k])[0]}multiplyUnsafe(I){let{endo:S}=e,_=this;if(!n.isValid(I))throw new Error("invalid scalar: out of range");if(I===ps||_.is0())return v.ZERO;if(I===Wo)return _;if(F.hasCache(this))return this.multiply(I);if(S){let{k1neg:k,k1:O,k2neg:N,k2:C}=E(I),{p1:R,p2:U}=V6(v,_,O,C);return D(S.beta,R,U,k,N)}else return F.unsafe(_,I)}toAffine(I){return P(this,I)}isTorsionFree(){let{isTorsionFree:I}=e;return i===Wo?!0:I?I(v,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:I}=e;return i===Wo?this:I?I(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(I=!0){return Ea(I,"isCompressed"),this.assertValidity(),f(v,this,I)}toHex(I=!0){return xn(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let M=n.BITS,F=new Cl(v,e.endo?Math.ceil(M/2):M);return v.BASE.precompute(8),v}function ey(r){return Uint8Array.of(r?2:3)}function ty(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function A8(r,e={}){let{Fn:t}=r,s=e.randomBytes||Ho,n=Object.assign(ty(r.Fp,t),{seed:rp(t.ORDER)});function o(f){try{let p=t.fromBytes(f);return t.isValidNot0(p)}catch{return!1}}function i(f,p){let{publicKey:m,publicKeyUncompressed:g}=n;try{let y=f.length;return p===!0&&y!==m||p===!1&&y!==g?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=s(n.seed)){return sp(Ee(f,n.seed,"seed"),t.ORDER)}function c(f,p=!0){return r.BASE.multiply(t.fromBytes(f)).toBytes(p)}function l(f){let{secretKey:p,publicKey:m,publicKeyUncompressed:g}=n;if(!wa(f)||"_lengths"in t&&t._lengths||p===m)return;let y=Ee(f,void 0,"key").length;return y===m||y===g}function u(f,p,m=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(f);return r.fromBytes(p).multiply(g).toBytes(m)}let h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},d=j6(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:h,lengths:n})}function ry(r,e,t={}){bl(e),_a(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let s=t.randomBytes||Ho,n=t.hmac||((S,_)=>cp(e,S,_)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:f}=A8(r,t),p={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*Q6<o.ORDER;function g(S){let _=a>>Wo;return S>_}function y(S,_){if(!i.isValidNot0(_))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return _}function w(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function b(S,_){up(_);let k=f.signature,O=_==="compact"?k:_==="recovered"?k+1:void 0;return Ee(S,O)}class x{r;s;recovery;constructor(_,k,O){if(this.r=y("r",_),this.s=y("s",k),O!=null){if(w(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(_,k=p.format){b(_,k);let O;if(k==="der"){let{r:U,s:z}=Gs.toSig(Ee(_));return new x(U,z)}k==="recovered"&&(O=_[0],k="compact",_=_.subarray(1));let N=f.signature/2,C=_.subarray(0,N),R=_.subarray(N,N*2);return new x(i.fromBytes(C),i.fromBytes(R),O)}static fromHex(_,k){return this.fromBytes(vn(_),k)}assertRecovery(){let{recovery:_}=this;if(_==null)throw new Error("invalid recovery id: must be present");return _}addRecoveryBit(_){return new x(this.r,this.s,_)}recoverPublicKey(_){let{r:k,s:O}=this,N=this.assertRecovery(),C=N===2||N===3?k+a:k;if(!o.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let R=o.toBytes(C),U=r.fromBytes(Ar(ey((N&1)===0),R)),z=i.inv(C),ee=P(Ee(_,void 0,"msgHash")),te=i.create(-ee*z),Z=i.create(O*z),se=r.BASE.multiplyUnsafe(te).add(U.multiplyUnsafe(Z));if(se.is0())throw new Error("invalid recovery: point at infinify");return se.assertValidity(),se}hasHighS(){return g(this.s)}toBytes(_=p.format){if(up(_),_==="der")return vn(Gs.hexFromSig(this));let{r:k,s:O}=this,N=i.toBytes(k),C=i.toBytes(O);return _==="recovered"?(w(),Ar(Uint8Array.of(this.assertRecovery()),N,C)):Ar(N,C)}toHex(_){return xn(this.toBytes(_))}}let E=t.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");let k=$o(_),O=_.length*8-c;return O>0?k>>BigInt(O):k},P=t.bits2int_modN||function(_){return i.create(E(_))},T=Ia(c);function D(S){return P6("num < 2^"+c,S,ps,T),i.toBytes(S)}function v(S,_){return Ee(S,void 0,"message"),_?Ee(e(S),void 0,"prehashed message"):S}function M(S,_,k){let{lowS:O,prehash:N,extraEntropy:C}=lp(k,p);S=v(S,N);let R=P(S),U=i.fromBytes(_);if(!i.isValidNot0(U))throw new Error("invalid private key");let z=[D(U),D(R)];if(C!=null&&C!==!1){let se=C===!0?s(f.secretKey):C;z.push(Ee(se,void 0,"extraEntropy"))}let ee=Ar(...z),te=R;function Z(se){let xe=E(se);if(!i.isValidNot0(xe))return;let $e=i.inv(xe),oe=r.BASE.multiply(xe).toAffine(),rt=i.create(oe.x);if(rt===ps)return;let To=i.create($e*i.create(te+rt*U));if(To===ps)return;let ea=(oe.x===rt?0:2)|Number(oe.y&Wo),ta=To;return O&&g(To)&&(ta=i.neg(To),ea^=1),new x(rt,ta,m?void 0:ea)}return{seed:ee,k2sig:Z}}function F(S,_,k={}){let{seed:O,k2sig:N}=M(S,_,k);return k6(e.outputLen,i.BYTES,n)(O,N).toBytes(k.format)}function B(S,_,k,O={}){let{lowS:N,prehash:C,format:R}=lp(O,p);if(k=Ee(k,void 0,"publicKey"),_=v(_,C),!wa(S)){let U=S instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}b(S,R);try{let U=x.fromBytes(S,R),z=r.fromBytes(k);if(N&&U.hasHighS())return!1;let{r:ee,s:te}=U,Z=P(_),se=i.inv(te),xe=i.create(Z*se),$e=i.create(ee*se),oe=r.BASE.multiplyUnsafe(xe).add(z.multiplyUnsafe($e));return oe.is0()?!1:i.create(oe.x)===ee}catch{return!1}}function I(S,_,k={}){let{prehash:O}=lp(k,p);return _=v(_,O),x.fromBytes(S,"recovered").recoverPublicKey(_).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:f,Point:r,sign:F,verify:B,recoverPublicKey:I,Signature:x,hash:e})}var Z6,hp,Gs,ps,Wo,Q6,Pl,_8,sy=A(()=>{X6();qs();Il();Y6();Al();Z6=(r,e)=>(r+(r>=0?e:-e)/Q6)/e;hp=class extends Error{constructor(e=""){super(e)}},Gs={Err:hp,_tlv:{encode:(r,e)=>{let{Err:t}=Gs;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let s=e.length/2,n=Sa(s);if(n.length/2&128)throw new t("tlv.encode: long form length too big");let o=s>127?Sa(n.length/2|128):"";return Sa(r)+o+n+e},decode(r,e){let{Err:t}=Gs,s=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[s++]!==r)throw new t("tlv.decode: wrong tlv");let n=e[s++],o=!!(n&128),i=0;if(!o)i=n;else{let c=n&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(s,s+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(s+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(s,s+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(s+i)}}},_int:{encode(r){let{Err:e}=Gs;if(r<ps)throw new e("integer: negative integers are not allowed");let t=Sa(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Gs;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return $o(r)}},toSig(r){let{Err:e,_int:t,_tlv:s}=Gs,n=Ee(r,void 0,"signature"),{v:o,l:i}=s.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=s.decode(2,o),{v:l,l:u}=s.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Gs,s=e.encode(2,t.encode(r.r)),n=e.encode(2,t.encode(r.s)),o=s+n;return e.encode(48,o)}},ps=BigInt(0),Wo=BigInt(1),Q6=BigInt(2),Pl=BigInt(3),_8=BigInt(4)});function T8(r){let e=fp.p,t=BigInt(3),s=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,h=jt(u,t,e)*u%e,d=jt(h,t,e)*u%e,f=jt(d,ny,e)*l%e,p=jt(f,n,e)*f%e,m=jt(p,o,e)*p%e,g=jt(m,a,e)*m%e,y=jt(g,c,e)*g%e,w=jt(y,a,e)*m%e,b=jt(w,t,e)*u%e,x=jt(b,i,e)*p%e,E=jt(x,s,e)*l%e,P=jt(E,ny,e);if(!dp.eql(dp.sqr(P),r))throw new Error("Cannot find square root");return P}var fp,C8,ny,dp,P8,ms,pp=A(()=>{Lf();Al();sy();fp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},C8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ny=BigInt(2);dp=Go(fp.p,{sqrt:T8}),P8=J6(fp,{Fp:dp,endo:C8}),ms=ry(P8,zo)});var kl,Dl,oy=A(()=>{kl=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Dl=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}});function iy(r,e,t){t?.signal?.throwIfAborted();let s=mp.default.createHash("sha256");if(e instanceof Uint8Array)s.update(e);else for(let o of e)s.update(o);let n=s.digest();try{return ms.sign(n,r,{prehash:!1,format:"der"})}catch(o){throw new kl(String(o))}}function ay(r,e,t,s){s?.signal?.throwIfAborted();let n=mp.default.createHash("sha256");if(t instanceof Uint8Array)n.update(t);else for(let i of t)n.update(i);let o=n.digest();try{return ms.verify(e,o,r,{prehash:!1,format:"der"})}catch(i){throw new Dl(String(i))}}var mp,cy=A(()=>{mp=we(re("node:crypto"),1);pp();oy()});var Ca,Ml,ly=A(()=>{Vt();zr();pn();Kt();ft();gp();cy();Ca=class{type="secp256k1";raw;_key;constructor(e){this._key=dy(e),this.raw=uy(this._key)}toMultihash(){return Er.digest(Ve(this))}toCID(){return De.createV1(114,this.toMultihash())}toString(){return me.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}verify(e,t,s){return ay(this._key,t,e,s)}},Ml=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=hy(e),this.publicKey=new Ca(t??fy(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ae(this.raw,e.raw)}sign(e,t){return iy(this.raw,e,t)}}});function yp(r){return new Ca(r)}async function py(){let r=k8();return new Ml(r)}function uy(r){return ms.Point.fromBytes(r).toBytes()}function hy(r){try{return ms.getPublicKey(r,!0),r}catch(e){throw new oa(String(e))}}function dy(r){try{return ms.Point.fromBytes(r),r}catch(e){throw new Mo(String(e))}}function fy(r){try{return ms.getPublicKey(r,!0)}catch(e){throw new oa(String(e))}}function k8(){return ms.utils.randomSecretKey()}var gp=A(()=>{Us();pp();ly()});async function my(r,e){if(r==="Ed25519")return Y3();if(r==="secp256k1")return py();if(r==="RSA")return Gf(D8(e));if(r==="ECDSA")return H3(M8(e));throw new Oo}function Je(r,e){let{Type:t,Data:s}=qr.decode(r),n=s??new Uint8Array;switch(t){case ze.RSA:return zf(n,e);case ze.Ed25519:return uf(n);case ze.secp256k1:return yp(n);case ze.ECDSA:return nf(n);default:throw new Oo}}function gy(r){let{Type:e,Data:t}=qr.decode(r.digest),s=t??new Uint8Array;switch(e){case ze.Ed25519:return uf(s);case ze.secp256k1:return yp(s);case ze.ECDSA:return nf(s);default:throw new Oo}}function Ve(r){return qr.encode({Type:ze[r.type],Data:r.raw})}function D8(r){return r==null?2048:parseInt(r,10)}function M8(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new Ge("Unsupported curve, should be P-256, P-384 or P-521")}var ft=A(()=>{Us();of();lf();Df();Vf();gp()});var yy,by=A(()=>{yy=Symbol.for("@libp2p/connection")});var wy=A(()=>{});var xy=A(()=>{});var bp,vy=A(()=>{bp=Symbol.for("@libp2p/content-routing")});var Ey=A(()=>{});var Sy=A(()=>{});var Ta,Iy=A(()=>{Ta=Symbol.for("@libp2p/peer-discovery")});function Vs(r){return!!r?.[Ol]}var Ol,_y=A(()=>{Ol=Symbol.for("@libp2p/peer-id")});var Ay=A(()=>{});var wp,Cy=A(()=>{wp=Symbol.for("@libp2p/peer-routing")});var xp,Ty=A(()=>{xp="keep-alive"});var In,jo,Ot,aR,Py=A(()=>{In="StrictSign",jo="StrictNoSign";(function(r){r.Accept="accept",r.Ignore="ignore",r.Reject="reject"})(Ot||(Ot={}));aR=Symbol.for("@libp2p/pubsub")});var ky=A(()=>{});var Dy=A(()=>{});var My=A(()=>{});var Oy=A(()=>{});var Ly,_n,Ry=A(()=>{Ly=Symbol.for("@libp2p/transport");(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(_n||(_n={}))});var Lt,Ll,Rl,V,Nl,Yo,Ws,Bl,Fl,An,Xo,js,Ul,Kl,Cn,Yt,Hl,Vr,Tr,zl,Zo,Pa,ql,Qo,$l,Ny=A(()=>{Lt=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},Ll=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Rl=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},V=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Nl=class extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}},Yo=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},Ws=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},Bl=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},Fl=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},An=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},Xo=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},js=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Ul=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Kl=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Cn=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Yt=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},Hl=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Vr=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Tr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},zl=class extends Error{static name="AlreadyStartedError";constructor(e="Already started"){super(e),this.name="AlreadyStartedError"}},Zo=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},Pa=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},ql=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Qo=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},$l=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}});function Gl(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function By(...r){let e=[];for(let t of r)Gl(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Fy(...r){let e=[];for(let t of r)Gl(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Uy=A(()=>{});var et,ka,X=A(()=>{by();wy();xy();vy();Ey();Sy();Iy();_y();Ay();Cy();Ty();Py();ky();Dy();My();Oy();Ry();Ny();Ze();Uy();et=Symbol.for("@libp2p/service-capabilities"),ka=Symbol.for("@libp2p/service-dependencies")});var Ky,O8,Da,Ma,Oa,La,L8,Ra,Hy=A(()=>{X();Vt();zr();pn();Kt();ge();Se();Ky=Symbol.for("nodejs.util.inspect.custom"),O8=114,Da=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ol]=!0;toString(){return this.string==null&&(this.string=me.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return De.createV1(O8,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ae(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ae(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ky](){return`PeerId(${this.toString()})`}},Ma=class extends Da{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Oa=class extends Da{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},La=class extends Da{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},L8=2336,Ra=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Er.digest(L(this.url))}[Ky](){return`PeerId(${this.url})`}[Ol]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return De.createV1(L8,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=K(e)),e.toString()===this.toString())}}});var Ep={};ve(Ep,{peerIdFromCID:()=>Wr,peerIdFromMultihash:()=>Pr,peerIdFromPrivateKey:()=>vp,peerIdFromPublicKey:()=>gs,peerIdFromString:()=>$});function $(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ht(me.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Wr(De.parse(r));if(e==null)throw new V('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ht(e.decode(r))}return Pr(t)}function gs(r){if(r.type==="Ed25519")return new Oa({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new La({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Ma({multihash:r.toCID().multihash,publicKey:r});throw new $l}function vp(r){return gs(r.publicKey)}function Pr(r){if(B8(r))return new Ma({multihash:r});if(N8(r))try{let e=gy(r);if(e.type==="Ed25519")return new Oa({multihash:r,publicKey:e});if(e.type==="secp256k1")return new La({multihash:r,publicKey:e})}catch{let t=K(r.digest);return new Ra(new URL(t))}throw new Kl("Supplied PeerID Multihash is invalid")}function Wr(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==R8&&r.code!==zy)throw new Ul("Supplied PeerID CID is invalid");if(r.code===zy){let e=K(r.multihash.digest);return new Ra(new URL(e))}return Pr(r.multihash)}function N8(r){return r.code===Er.code}function B8(r){return r.code===Qe.code}var R8,zy,ce=A(()=>{ft();X();Vt();zr();ir();pn();us();Se();Hy();R8=114,zy=2336});var Zp=A(()=>{"use strict"});var b5=He((SK,y5)=>{var oi=1e3,ii=oi*60,ai=ii*60,Mn=ai*24,p_=Mn*7,m_=Mn*365.25;y5.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return g_(r);if(t==="number"&&isFinite(r))return e.long?b_(r):y_(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function g_(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),s=(e[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return t*m_;case"weeks":case"week":case"w":return t*p_;case"days":case"day":case"d":return t*Mn;case"hours":case"hour":case"hrs":case"hr":case"h":return t*ai;case"minutes":case"minute":case"mins":case"min":case"m":return t*ii;case"seconds":case"second":case"secs":case"sec":case"s":return t*oi;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function y_(r){var e=Math.abs(r);return e>=Mn?Math.round(r/Mn)+"d":e>=ai?Math.round(r/ai)+"h":e>=ii?Math.round(r/ii)+"m":e>=oi?Math.round(r/oi)+"s":r+"ms"}function b_(r){var e=Math.abs(r);return e>=Mn?Xl(r,e,Mn,"day"):e>=ai?Xl(r,e,ai,"hour"):e>=ii?Xl(r,e,ii,"minute"):e>=oi?Xl(r,e,oi,"second"):r+" ms"}function Xl(r,e,t,s){var n=e>=t*1.5;return Math.round(r/t)+" "+s+(n?"s":"")}});var Jp=He((IK,w5)=>{function w_(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=n,t.enabled=a,t.humanize=b5(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let h=0;for(let d=0;d<u.length;d++)h=(h<<5)-h+u.charCodeAt(d),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(u){let h,d=null,f,p;function m(...g){if(!m.enabled)return;let y=m,w=Number(new Date),b=w-(h||w);y.diff=b,y.prev=h,y.curr=w,h=w,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(P,T)=>{if(P==="%%")return"%";x++;let D=t.formatters[T];if(typeof D=="function"){let v=g[x];P=D.call(y,v),g.splice(x,1),x--}return P}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=s,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(u)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function s(u,h){let d=t(this.namespace+(typeof h>"u"?":":h)+u);return d.log=this.log,d}function n(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let h=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let d of h)d[0]==="-"?t.skips.push(d.slice(1)):t.names.push(d)}function o(u,h){let d=0,f=0,p=-1,m=0;for(;d<u.length;)if(f<h.length&&(h[f]===u[d]||h[f]==="*"))h[f]==="*"?(p=f,m=d,f++):(d++,f++);else if(p!==-1)f=p+1,m++,d=m;else return!1;for(;f<h.length&&h[f]==="*";)f++;return f===h.length}function i(){let u=[...t.names,...t.skips.map(h=>"-"+h)].join(",");return t.enable(""),u}function a(u){for(let h of t.skips)if(o(u,h))return!1;for(let h of t.names)if(o(u,h))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}w5.exports=w_});var x5=He((qt,Zl)=>{qt.formatArgs=v_;qt.save=E_;qt.load=S_;qt.useColors=x_;qt.storage=I_();qt.destroy=(()=>{let r=!1;return()=>{r||(r=!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`."))}})();qt.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 x_(){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 r;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&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function v_(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Zl.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,s=0;r[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(t++,n==="%c"&&(s=t))}),r.splice(s,0,e)}qt.log=console.debug||console.log||(()=>{});function E_(r){try{r?qt.storage.setItem("debug",r):qt.storage.removeItem("debug")}catch{}}function S_(){let r;try{r=qt.storage.getItem("debug")||qt.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function I_(){try{return localStorage}catch{}}Zl.exports=Jp()(qt);var{formatters:__}=Zl.exports;__.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var E5=He((_K,v5)=>{"use strict";v5.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",s=e.indexOf(t+r),n=e.indexOf("--");return s!==-1&&(n===-1||s<n)}});var _5=He((AK,I5)=>{"use strict";var A_=re("os"),S5=re("tty"),cr=E5(),{env:it}=process,Xs;cr("no-color")||cr("no-colors")||cr("color=false")||cr("color=never")?Xs=0:(cr("color")||cr("colors")||cr("color=true")||cr("color=always"))&&(Xs=1);"FORCE_COLOR"in it&&(it.FORCE_COLOR==="true"?Xs=1:it.FORCE_COLOR==="false"?Xs=0:Xs=it.FORCE_COLOR.length===0?1:Math.min(parseInt(it.FORCE_COLOR,10),3));function e0(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function t0(r,e){if(Xs===0)return 0;if(cr("color=16m")||cr("color=full")||cr("color=truecolor"))return 3;if(cr("color=256"))return 2;if(r&&!e&&Xs===void 0)return 0;let t=Xs||0;if(it.TERM==="dumb")return t;if(process.platform==="win32"){let s=A_.release().split(".");return Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in it)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(s=>s in it)||it.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in it)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(it.TEAMCITY_VERSION)?1:0;if(it.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in it){let s=parseInt((it.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(it.TERM_PROGRAM){case"iTerm.app":return s>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(it.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(it.TERM)||"COLORTERM"in it?1:t}function C_(r){let e=t0(r,r&&r.isTTY);return e0(e)}I5.exports={supportsColor:C_,stdout:e0(t0(!0,S5.isatty(1))),stderr:e0(t0(!0,S5.isatty(2)))}});var C5=He((at,Jl)=>{var T_=re("tty"),Ql=re("util");at.init=R_;at.log=M_;at.formatArgs=k_;at.save=O_;at.load=L_;at.useColors=P_;at.destroy=Ql.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");at.colors=[6,2,3,4,5,1];try{let r=_5();r&&(r.stderr||r).level>=2&&(at.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}at.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,o)=>o.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),r[t]=s,r},{});function P_(){return"colors"in at.inspectOpts?!!at.inspectOpts.colors:T_.isatty(process.stderr.fd)}function k_(r){let{namespace:e,useColors:t}=this;if(t){let s=this.color,n="\x1B[3"+(s<8?s:"8;5;"+s),o=` ${n};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
|
|
3
|
+
`).join(`
|
|
4
|
+
`+o),r.push(n+"m+"+Jl.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=D_()+e+" "+r[0]}function D_(){return at.inspectOpts.hideDate?"":new Date().toISOString()+" "}function M_(...r){return process.stderr.write(Ql.formatWithOptions(at.inspectOpts,...r)+`
|
|
5
|
+
`)}function O_(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function L_(){return process.env.DEBUG}function R_(r){r.inspectOpts={};let e=Object.keys(at.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=at.inspectOpts[e[t]]}Jl.exports=Jp()(at);var{formatters:A5}=Jl.exports;A5.o=function(r){return this.inspectOpts.colors=this.useColors,Ql.inspect(r,this.inspectOpts).split(`
|
|
6
|
+
`).map(e=>e.trim()).join(" ")};A5.O=function(r){return this.inspectOpts.colors=this.useColors,Ql.inspect(r,this.inspectOpts)}});var s0=He((CK,r0)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?r0.exports=x5():r0.exports=C5()});var T4=He((R$,C4)=>{C4.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),s=Object.create(null);function n(o,i){t[o]=i,e++,e>=r&&(e=0,s=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||s[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),s[o]!==void 0&&(s[o]=void 0)},get:function(o){var i=t[o];if(i!==void 0)return i;if((i=s[o])!==void 0)return n(o,i),i},set:function(o,i){t[o]!==void 0?t[o]=i:n(o,i)},clear:function(){t=Object.create(null),s=Object.create(null)}}}});var ub=He(wc=>{(function(){var r,e,t,s,n,o,i,a;a=function(c){var l,u,h,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,h=(c&65280)>>>8,d=c&255,[l,u,h,d].join(".")},i=function(c){var l,u,h,d,f,p;for(l=[],h=d=0;d<=3&&c.length!==0;h=++d){if(h>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),f=p[0],u=p[1],c=c.substring(u),l.push(f)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},s=t("0"),o=t("a"),n=t("A"),e=function(c){var l,u,h,d,f;for(d=0,l=10,u="9",h=0,c.length>1&&c[h]==="0"&&(c[h+1]==="x"||c[h+1]==="X"?(h+=2,l=16):"0"<=c[h+1]&&c[h+1]<="9"&&(h++,l=8,u="7")),f=h;h<c.length;){if("0"<=c[h]&&c[h]<=u)d=d*l+(t(c[h])-s)>>>0;else if(l===16)if("a"<=c[h]&&c[h]<="f")d=d*l+(10+t(c[h])-o)>>>0;else if("A"<=c[h]&&c[h]<="F")d=d*l+(10+t(c[h])-n)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");h++}if(h===f)throw new Error("empty octet");return[d,h]},r=(function(){function c(l,u){var h,d,f,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(p=l.split("/",2),l=p[0],u=p[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(m){throw h=m,new Error("Invalid mask: "+u)}for(d=f=32;f>=0;d=--f)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw h=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,h,d;for(d=i(this.first),h=i(this.last),u=0;d<=h;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),wc.ip2long=i,wc.long2ip=a,wc.Netmask=r}).call(wc)});var Fb=He((rZ,Bb)=>{function mr(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.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))}Bb.exports=mr;mr.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};mr.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};mr.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var s=this;return this._timer=setTimeout(function(){s._attempts++,s._operationTimeoutCb&&(s._timeout=setTimeout(function(){s._operationTimeoutCb(s._attempts)},s._operationTimeout),s._options.unref&&s._timeout.unref()),s._fn(s._attempts)},t),this._options.unref&&this._timer.unref(),!0};mr.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};mr.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};mr.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};mr.prototype.start=mr.prototype.try;mr.prototype.errors=function(){return this._errors};mr.prototype.attempts=function(){return this._attempts};mr.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,s=0;s<this._errors.length;s++){var n=this._errors[s],o=n.message,i=(r[o]||0)+1;r[o]=i,i>=t&&(e=n,t=i)}return e}});var Ub=He(uo=>{var p7=Fb();uo.operation=function(r){var e=uo.timeouts(r);return new p7(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};uo.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var s=[],n=0;n<e.retries;n++)s.push(this.createTimeout(n,e));return r&&r.forever&&!s.length&&s.push(this.createTimeout(n,e)),s.sort(function(o,i){return o-i}),s};uo.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,s=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return s=Math.min(s,e.maxTimeout),s};uo.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var s in r)typeof r[s]=="function"&&t.push(s)}for(var n=0;n<t.length;n++){var o=t[n],i=r[o];r[o]=function(c){var l=uo.operation(e),u=Array.prototype.slice.call(arguments,1),h=u.pop();u.push(function(d){l.retry(d)||(d&&(arguments[0]=l.mainError()),h.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,i),r[o].options=e}}});var Hb=He((nZ,Kb)=>{Kb.exports=Ub()});var sm=He(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.TAG_LENGTH=es.DATA_CHUNK_LENGTH=es.NONCE_LENGTH=es.KEY_LENGTH=void 0;es.KEY_LENGTH=32;es.NONCE_LENGTH=12;es.DATA_CHUNK_LENGTH=65536;es.TAG_LENGTH=16});var pw=He(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});th.ChaCha20Poly1305=void 0;var Ue=sm(),nm=class{constructor(e){this.ctx=e;let t=e.cpKey.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,Ue.KEY_LENGTH);let s=e.cpNonce.value;this.wasmNonceArr=new Uint8Array(e.memory.buffer,s,Ue.NONCE_LENGTH);let n=e.cpAssociatedData.value;this.wasmAdArr=new Uint8Array(e.memory.buffer,n,Ue.KEY_LENGTH);let o=e.cpInput.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,o,Ue.DATA_CHUNK_LENGTH);let i=e.chacha20Output.value;this.wasmChacha20OutputArr=new Uint8Array(e.memory.buffer,i,Ue.DATA_CHUNK_LENGTH);let a=e.poly1305Output.value;this.wasmPoly1305OutputArr=new Uint8Array(e.memory.buffer,a,Ue.TAG_LENGTH);let c=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,c,64)}seal(e,t,s,n,o){this.init(e,t,n);let i=s.length+Ue.TAG_LENGTH,a;if(o){if(o.length!==i)throw new Error("ChaCha20Poly1305: incorrect destination length");a=o}else a=new Uint8Array(i);let c=n?.length??0;return this.sealUpdate(s,c,a),a.set(this.wasmPoly1305OutputArr,s.length),a}open(e,t,s,n,o){this.init(e,t,n);let i=s.subarray(0,s.length-Ue.TAG_LENGTH),a;if(o){if(o.length!==i.length)throw new Error("ChaCha20Poly1305: incorrect destination length");a=o}else a=new Uint8Array(i.length);let c=n?.length??0;this.openUpdate(i,c,a);let l=s.subarray(s.length-Ue.TAG_LENGTH,s.length);return this.isSameTag(l)?a:null}init(e,t,s=new Uint8Array(0)){if(e.length!=Ue.KEY_LENGTH)throw Error(`Invalid chacha20poly1305 key length ${e.length}, expect ${Ue.KEY_LENGTH}`);if(s.length>Ue.KEY_LENGTH)throw Error(`Invalid ad length ${s.length}, expect <= ${Ue.KEY_LENGTH}`);if(t.length!==Ue.NONCE_LENGTH)throw Error(`Invalid nonce length ${t.length}, expect ${Ue.NONCE_LENGTH}`);this.wasmKeyArr.set(e),this.wasmNonceArr.set(t),this.wasmAdArr.set(s)}openUpdate(e,t,s){this.commonUpdate(e,this.ctx.openUpdate,t,s)}sealUpdate(e,t,s){this.commonUpdate(e,this.ctx.sealUpdate,t,s)}commonUpdate(e,t,s,n){let o=e.length;if(e.length<=Ue.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),t(!0,!0,o,o,s),n.set(o===Ue.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,o));return}for(let i=0;i<o;i+=Ue.DATA_CHUNK_LENGTH){let a=Math.min(o,i+Ue.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(i,a));let c=i===0,l=i+Ue.DATA_CHUNK_LENGTH>=o;t(c,l,a-i,o,s),n.set(a-i===Ue.DATA_CHUNK_LENGTH?this.wasmChacha20OutputArr:this.wasmChacha20OutputArr.subarray(0,a-i),i)}}isSameTag(e){let t=!0;for(let s=0;s<Ue.TAG_LENGTH;s++)if(this.wasmPoly1305OutputArr[s]!==e[s]){t=!1;break}return t}};th.ChaCha20Poly1305=nm});var mw=He(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});rh.Poly1305=void 0;var _s=sm(),om=class{constructor(e){this.ctx=e;let t=e.poly1305Key.value;this.wasmKeyArr=new Uint8Array(e.memory.buffer,t,_s.KEY_LENGTH);let s=e.poly1305Input.value;this.wasmInputArr=new Uint8Array(e.memory.buffer,s,_s.DATA_CHUNK_LENGTH);let n=e.poly1305Output.value;this.wasmOutputArr=new Uint8Array(e.memory.buffer,n,_s.TAG_LENGTH);let o=e.debug.value;this.wasmDebugArr=new Uint32Array(e.memory.buffer,o,64)}init(e){if(e.length!=_s.KEY_LENGTH)throw Error(`Invalid poly1305 key length ${e.length}, expect ${_s.KEY_LENGTH}`);this.wasmKeyArr.set(e),this.ctx.poly1305Init()}update(e){if(e.length<=_s.DATA_CHUNK_LENGTH){this.wasmInputArr.set(e),this.ctx.poly1305Update(e.length);return}for(let t=0;t<e.length;t+=_s.DATA_CHUNK_LENGTH){let s=Math.min(e.length,t+_s.DATA_CHUNK_LENGTH);this.wasmInputArr.set(e.subarray(t,s)),this.ctx.poly1305Update(s-t)}}digest(){this.ctx.poly1305Digest();let e=new Uint8Array(_s.TAG_LENGTH);return e.set(this.wasmOutputArr),e}};rh.Poly1305=om});var gw=He(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});sh.wasmCode=void 0;sh.wasmCode=Uint8Array.from([0,97,115,109,1,0,0,0,1,58,10,96,0,0,96,2,127,127,0,96,1,127,0,96,3,127,127,127,0,96,1,127,1,127,96,4,127,127,127,127,0,96,5,127,127,127,127,127,0,96,0,1,127,96,2,127,127,1,127,96,5,127,127,127,127,127,1,127,2,13,1,3,101,110,118,5,97,98,111,114,116,0,5,3,34,33,2,8,1,4,0,4,7,0,0,3,3,2,1,9,4,2,0,3,1,2,2,1,0,0,0,5,1,1,1,6,1,6,0,5,3,1,0,1,6,238,1,47,127,0,65,32,11,127,0,65,16,11,127,0,65,128,128,4,11,127,0,65,16,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,7,226,2,23,6,109,101,109,111,114,121,2,0,21,67,72,65,67,72,65,50,48,95,73,78,80,85,84,95,76,69,78,71,84,72,3,2,23,67,72,65,67,72,65,50,48,95,67,79,85,78,84,69,82,95,76,69,78,71,84,72,3,3,13,99,104,97,99,104,97,50,48,73,110,112,117,116,3,6,11,99,104,97,99,104,97,50,48,75,101,121,3,8,15,99,104,97,99,104,97,50,48,67,111,117,110,116,101,114,3,10,14,99,104,97,99,104,97,50,48,79,117,116,112,117,116,3,12,23,99,104,97,99,104,97,50,48,83,116,114,101,97,109,88,79,82,85,112,100,97,116,101,0,15,10,75,69,89,95,76,69,78,71,84,72,3,0,10,84,65,71,95,76,69,78,71,84,72,3,1,12,112,111,108,121,49,51,48,53,73,110,105,116,0,17,14,112,111,108,121,49,51,48,53,85,112,100,97,116,101,0,20,14,112,111,108,121,49,51,48,53,68,105,103,101,115,116,0,24,13,112,111,108,121,49,51,48,53,73,110,112,117,116,3,19,11,112,111,108,121,49,51,48,53,75,101,121,3,18,14,112,111,108,121,49,51,48,53,79,117,116,112,117,116,3,20,10,111,112,101,110,85,112,100,97,116,101,0,30,10,115,101,97,108,85,112,100,97,116,101,0,32,5,99,112,75,101,121,3,37,7,99,112,78,111,110,99,101,3,39,7,99,112,73,110,112,117,116,3,43,16,99,112,65,115,115,111,99,105,97,116,101,100,68,97,116,97,3,41,5,100,101,98,117,103,3,46,8,1,33,10,195,47,33,70,1,2,127,32,0,63,0,34,2,65,16,116,34,1,75,4,64,32,2,32,0,32,1,107,65,255,255,3,106,65,128,128,124,113,65,16,118,34,1,32,2,32,1,74,27,64,0,65,0,72,4,64,32,1,64,0,65,0,72,4,64,0,11,11,11,32,0,36,5,11,82,1,3,127,32,0,65,240,255,255,255,3,75,4,64,0,11,35,5,65,16,106,34,3,32,0,65,15,106,65,112,113,34,2,65,16,32,2,65,16,75,27,34,4,106,16,1,32,3,65,16,107,34,2,32,4,54,2,0,32,2,65,1,54,2,4,32,2,32,1,54,2,8,32,2,32,0,54,2,12,32,3,11,37,1,1,127,3,64,32,1,4,64,32,0,34,2,65,1,106,33,0,32,2,65,0,58,0,0,32,1,65,1,107,33,1,12,1,11,11,11,42,1,1,127,32,0,65,240,255,255,255,3,75,4,64,65,32,65,208,0,65,54,65,42,16,0,0,11,32,0,65,0,16,2,34,1,32,0,16,3,32,1,11,67,0,65,128,3,36,4,65,128,3,36,5,65,128,128,4,16,4,36,6,35,6,36,7,65,32,16,4,36,8,35,8,36,9,65,16,16,4,36,10,35,10,36,11,65,128,128,4,16,4,36,12,35,12,36,13,65,192,0,16,4,36,14,35,14,36,15,11,83,1,1,127,65,128,2,65,0,16,2,34,1,65,128,2,16,3,32,0,69,4,64,65,12,65,2,16,2,33,0,11,32,0,65,0,54,2,0,32,0,65,0,54,2,4,32,0,65,0,54,2,8,32,0,40,2,0,26,32,0,32,1,54,2,0,32,0,32,1,54,2,4,32,0,65,128,2,54,2,8,32,0,11,10,0,65,12,65,3,16,2,16,6,11,95,0,16,7,36,16,35,16,40,2,0,36,17,65,32,16,4,36,18,65,128,128,4,16,4,36,19,65,16,16,4,36,20,35,18,36,21,35,19,36,22,35,20,36,23,65,16,16,4,36,24,35,24,36,25,65,20,16,4,36,26,35,26,36,27,65,20,16,4,36,28,35,28,36,29,65,16,16,4,36,30,35,30,36,31,65,20,16,4,36,35,35,35,36,36,11,55,0,65,32,16,4,36,37,35,37,36,38,65,12,16,4,36,39,35,39,36,40,65,32,16,4,36,41,35,41,36,42,65,128,128,4,16,4,36,43,35,43,36,44,16,7,36,45,35,45,40,2,0,36,46,11,22,0,32,1,32,2,65,255,1,113,65,4,110,65,2,116,106,32,0,54,2,0,11,188,6,1,31,127,65,229,240,193,139,6,33,5,65,238,200,129,153,3,33,6,65,178,218,136,203,7,33,14,65,244,202,129,217,6,33,7,32,2,40,2,0,34,19,33,4,32,2,65,4,106,40,2,0,34,20,33,8,32,2,65,8,106,40,2,0,34,21,33,3,32,2,65,12,106,40,2,0,34,22,33,13,32,2,65,16,106,40,2,0,34,23,33,15,32,2,65,20,106,40,2,0,34,24,33,9,32,2,65,24,106,40,2,0,34,25,33,10,32,2,65,28,106,40,2,0,34,26,33,2,32,1,40,2,0,34,27,33,11,32,1,65,4,106,40,2,0,34,28,33,16,32,1,65,8,106,40,2,0,34,29,33,12,32,1,65,12,106,40,2,0,34,30,33,1,3,64,32,18,65,20,72,4,64,32,3,32,10,32,12,32,3,32,14,106,34,3,115,65,16,119,34,14,106,34,10,115,65,12,119,34,12,32,10,32,14,32,3,32,12,106,34,3,115,65,8,119,34,14,106,34,10,115,33,12,32,13,32,2,32,1,32,7,32,13,106,34,1,115,65,16,119,34,2,106,34,13,115,65,12,119,34,7,32,13,32,2,32,1,32,7,106,34,13,115,65,8,119,34,1,106,34,2,115,33,7,32,4,32,15,32,11,32,4,32,5,106,34,4,115,65,16,119,34,5,106,34,15,115,65,12,119,34,11,32,15,32,5,32,4,32,11,106,34,4,115,65,8,119,34,5,106,34,15,115,33,11,32,10,32,1,32,8,32,9,32,16,32,6,32,8,106,34,1,115,65,16,119,34,8,106,34,6,115,65,12,119,34,9,32,6,32,8,32,1,32,9,106,34,1,115,65,8,119,34,6,106,34,9,115,65,7,119,34,10,32,4,106,34,17,115,65,16,119,34,31,106,33,8,32,2,32,5,32,12,65,7,119,34,5,32,1,106,34,32,115,65,16,119,34,33,106,33,1,32,9,32,14,32,13,32,11,65,7,119,34,9,106,34,11,115,65,16,119,34,12,106,33,4,32,15,32,6,32,3,32,7,65,7,119,34,3,106,34,6,115,65,16,119,34,7,106,34,2,32,6,32,2,32,3,115,65,12,119,34,3,106,34,14,32,7,115,65,8,119,34,16,106,34,15,32,3,115,65,7,119,33,13,32,11,32,4,32,9,115,65,12,119,34,2,106,34,7,32,12,115,65,8,119,34,12,32,4,106,34,9,32,2,115,65,7,119,33,4,32,32,32,1,32,5,115,65,12,119,34,3,106,34,6,32,33,115,65,8,119,34,11,32,1,106,34,2,32,3,115,65,7,119,33,3,32,17,32,8,32,10,115,65,12,119,34,17,106,34,5,32,31,115,65,8,119,34,1,32,8,106,34,10,32,17,115,65,7,119,33,8,32,18,65,2,106,33,18,12,1,11,11,32,5,65,229,240,193,139,6,106,32,0,65,0,16,10,32,6,65,238,200,129,153,3,106,32,0,65,4,16,10,32,14,65,178,218,136,203,7,106,32,0,65,8,16,10,32,7,65,244,202,129,217,6,106,32,0,65,12,16,10,32,4,32,19,106,32,0,65,16,16,10,32,8,32,20,106,32,0,65,20,16,10,32,3,32,21,106,32,0,65,24,16,10,32,13,32,22,106,32,0,65,28,16,10,32,15,32,23,106,32,0,65,32,16,10,32,9,32,24,106,32,0,65,36,16,10,32,10,32,25,106,32,0,65,40,16,10,32,2,32,26,106,32,0,65,44,16,10,32,11,32,27,106,32,0,65,48,16,10,32,16,32,28,106,32,0,65,52,16,10,32,12,32,29,106,32,0,65,56,16,10,32,1,32,30,106,32,0,65,60,16,10,11,97,1,4,127,65,4,33,3,65,1,33,1,3,64,32,3,34,2,65,1,107,33,3,32,2,65,255,1,113,4,64,32,1,32,0,32,4,65,255,1,113,106,34,2,45,0,0,106,33,1,32,2,32,1,58,0,0,32,1,65,8,118,33,1,32,4,65,1,106,33,4,12,1,11,11,32,1,65,0,74,4,64,65,144,1,65,208,1,65,135,2,65,4,16,0,0,11,11,8,0,32,0,32,1,16,3,11,108,1,2,127,3,64,32,6,32,1,73,4,64,35,15,32,3,32,2,16,11,32,6,33,5,3,64,32,5,32,1,73,65,0,32,5,32,6,65,64,107,73,27,4,64,32,4,32,5,106,32,0,32,5,106,45,0,0,35,15,32,5,32,6,107,106,45,0,0,115,58,0,0,32,5,65,1,106,33,5,12,1,11,11,32,3,16,12,32,6,65,64,107,33,6,12,1,11,11,35,15,65,192,0,16,13,32,1,11,14,0,35,7,32,0,35,9,35,11,35,13,16,14,11,204,4,1,1,127,35,27,32,0,45,0,0,32,0,65,1,106,45,0,0,65,8,116,114,34,1,65,255,63,113,59,1,0,35,27,65,2,106,32,1,65,13,118,32,0,65,2,106,45,0,0,32,0,65,3,106,45,0,0,65,8,116,114,34,1,65,3,116,114,65,255,63,113,59,1,0,35,27,65,4,106,32,1,65,10,118,32,0,65,4,106,45,0,0,32,0,65,5,106,45,0,0,65,8,116,114,34,1,65,6,116,114,65,131,62,113,59,1,0,35,27,65,6,106,32,1,65,7,118,32,0,65,6,106,45,0,0,32,0,65,7,106,45,0,0,65,8,116,114,34,1,65,9,116,114,65,255,63,113,59,1,0,35,27,65,8,106,32,1,65,4,118,32,0,65,8,106,45,0,0,32,0,65,9,106,45,0,0,65,8,116,114,34,1,65,12,116,114,65,255,1,113,59,1,0,35,27,65,10,106,32,1,65,1,118,65,254,63,113,59,1,0,35,27,65,12,106,32,1,65,14,118,32,0,65,10,106,45,0,0,32,0,65,11,106,45,0,0,65,8,116,114,34,1,65,2,116,114,65,255,63,113,59,1,0,35,27,65,14,106,32,1,65,11,118,32,0,65,12,106,45,0,0,32,0,65,13,106,45,0,0,65,8,116,114,34,1,65,5,116,114,65,129,63,113,59,1,0,35,27,65,16,106,32,1,65,8,118,32,0,65,14,106,45,0,0,32,0,65,15,106,45,0,0,65,8,116,114,34,1,65,8,116,114,65,255,63,113,59,1,0,35,27,65,18,106,32,1,65,5,118,65,255,0,113,59,1,0,35,31,32,0,65,16,106,45,0,0,32,0,65,17,106,45,0,0,65,8,116,114,59,1,0,35,31,65,2,106,32,0,65,18,106,45,0,0,32,0,65,19,106,45,0,0,65,8,116,114,59,1,0,35,31,65,4,106,32,0,65,20,106,45,0,0,32,0,65,21,106,45,0,0,65,8,116,114,59,1,0,35,31,65,6,106,32,0,65,22,106,45,0,0,32,0,65,23,106,45,0,0,65,8,116,114,59,1,0,35,31,65,8,106,32,0,65,24,106,45,0,0,32,0,65,25,106,45,0,0,65,8,116,114,59,1,0,35,31,65,10,106,32,0,65,26,106,45,0,0,32,0,65,27,106,45,0,0,65,8,116,114,59,1,0,35,31,65,12,106,32,0,65,28,106,45,0,0,32,0,65,29,106,45,0,0,65,8,116,114,59,1,0,35,31,65,14,106,32,0,65,30,106,45,0,0,32,0,65,31,106,45,0,0,65,8,116,114,59,1,0,11,6,0,35,21,16,16,11,166,13,1,32,127,65,0,65,128,16,35,33,27,33,34,35,29,47,1,0,33,3,35,29,65,2,106,47,1,0,33,4,35,29,65,4,106,47,1,0,33,8,35,29,65,6,106,47,1,0,33,9,35,29,65,8,106,47,1,0,33,10,35,29,65,10,106,47,1,0,33,11,35,29,65,12,106,47,1,0,33,12,35,29,65,14,106,47,1,0,33,13,35,29,65,16,106,47,1,0,33,14,35,29,65,18,106,47,1,0,33,6,35,27,47,1,0,33,17,35,27,65,2,106,47,1,0,33,18,35,27,65,4,106,47,1,0,33,20,35,27,65,6,106,47,1,0,33,22,35,27,65,8,106,47,1,0,33,24,35,27,65,10,106,47,1,0,33,26,35,27,65,12,106,47,1,0,33,29,35,27,65,14,106,47,1,0,33,30,35,27,65,16,106,47,1,0,33,31,35,27,65,18,106,47,1,0,33,33,3,64,32,2,65,16,79,4,64,32,3,32,0,32,1,106,45,0,0,32,0,32,1,65,1,106,106,45,0,0,65,8,116,114,34,15,65,255,63,113,106,34,3,32,17,108,32,4,32,0,32,1,65,2,106,106,45,0,0,32,0,32,1,65,3,106,106,45,0,0,65,8,116,114,34,16,65,3,116,32,15,65,255,255,3,113,65,13,118,114,65,255,63,113,106,34,4,32,33,65,5,108,34,15,108,106,32,8,32,0,32,1,65,4,106,106,45,0,0,32,0,32,1,65,5,106,106,45,0,0,65,8,116,114,34,19,65,6,116,32,16,65,255,255,3,113,65,10,118,114,65,255,63,113,106,34,8,32,31,65,5,108,34,16,108,106,32,9,32,0,32,1,65,6,106,106,45,0,0,32,0,32,1,65,7,106,106,45,0,0,65,8,116,114,34,21,65,9,116,32,19,65,255,255,3,113,65,7,118,114,65,255,63,113,106,34,9,32,30,65,5,108,34,19,108,106,32,10,32,0,32,1,65,8,106,106,45,0,0,32,0,32,1,65,9,106,106,45,0,0,65,8,116,114,34,23,65,12,116,32,21,65,255,255,3,113,65,4,118,114,65,255,63,113,106,34,10,32,29,65,5,108,34,21,108,106,34,32,65,255,63,113,32,11,32,23,65,255,255,3,113,65,1,118,65,255,63,113,106,34,11,32,26,65,5,108,34,27,108,106,32,12,32,0,32,1,65,10,106,106,45,0,0,32,0,32,1,65,11,106,106,45,0,0,65,8,116,114,34,28,65,2,116,32,23,65,255,255,3,113,65,14,118,114,65,255,63,113,106,34,12,32,24,65,5,108,34,23,108,106,32,13,32,0,32,1,65,12,106,106,45,0,0,32,0,32,1,65,13,106,106,45,0,0,65,8,116,114,34,25,65,5,116,32,28,65,255,255,3,113,65,11,118,114,65,255,63,113,106,34,13,32,22,65,5,108,34,28,108,106,32,14,32,25,65,255,255,3,113,65,8,118,32,0,32,1,65,14,106,106,45,0,0,32,0,32,1,65,15,106,106,45,0,0,65,8,116,114,34,25,65,8,116,114,65,255,63,113,106,34,14,32,20,65,5,108,34,7,108,106,33,5,32,11,32,21,108,32,32,65,13,118,32,5,32,6,32,34,32,25,65,255,255,3,113,65,5,118,114,65,255,255,3,113,106,34,6,32,18,65,5,108,108,106,34,32,65,13,118,106,32,3,32,18,108,106,32,4,32,17,108,106,32,8,32,15,108,106,32,9,32,16,108,106,32,10,32,19,108,106,34,25,65,255,63,113,106,32,12,32,27,108,106,32,13,32,23,108,106,32,14,32,28,108,106,33,5,32,11,32,19,108,32,25,65,13,118,32,5,32,6,32,7,108,106,34,25,65,13,118,106,32,3,32,20,108,106,32,4,32,18,108,106,32,8,32,17,108,106,32,9,32,15,108,106,32,10,32,16,108,106,34,7,65,255,63,113,106,32,12,32,21,108,106,32,13,32,27,108,106,32,14,32,23,108,106,33,5,32,11,32,16,108,32,7,65,13,118,32,5,32,6,32,28,108,106,34,28,65,13,118,106,32,3,32,22,108,106,32,4,32,20,108,106,32,8,32,18,108,106,32,9,32,17,108,106,32,10,32,15,108,106,34,7,65,255,63,113,106,32,12,32,19,108,106,32,13,32,21,108,106,32,14,32,27,108,106,33,5,32,11,32,15,108,32,7,65,13,118,32,5,32,6,32,23,108,106,34,23,65,13,118,106,32,3,32,24,108,106,32,4,32,22,108,106,32,8,32,20,108,106,32,9,32,18,108,106,32,10,32,17,108,106,34,7,65,255,63,113,106,32,12,32,16,108,106,32,13,32,19,108,106,32,14,32,21,108,106,33,5,32,11,32,17,108,32,7,65,13,118,32,5,32,6,32,27,108,106,34,27,65,13,118,106,32,3,32,26,108,106,32,4,32,24,108,106,32,8,32,22,108,106,32,9,32,20,108,106,32,10,32,18,108,106,34,7,65,255,63,113,106,32,12,32,15,108,106,32,13,32,16,108,106,32,14,32,19,108,106,33,5,32,11,32,18,108,32,7,65,13,118,32,5,32,6,32,21,108,106,34,21,65,13,118,106,32,3,32,29,108,106,32,4,32,26,108,106,32,8,32,24,108,106,32,9,32,22,108,106,32,10,32,20,108,106,34,7,65,255,63,113,106,32,12,32,17,108,106,32,13,32,15,108,106,32,14,32,16,108,106,33,5,32,11,32,20,108,32,7,65,13,118,32,5,32,6,32,19,108,106,34,19,65,13,118,106,32,3,32,30,108,106,32,4,32,29,108,106,32,8,32,26,108,106,32,9,32,24,108,106,32,10,32,22,108,106,34,7,65,255,63,113,106,32,12,32,18,108,106,32,13,32,17,108,106,32,14,32,15,108,106,33,5,32,11,32,22,108,32,7,65,13,118,32,5,32,6,32,16,108,106,34,16,65,13,118,106,32,3,32,31,108,106,32,4,32,30,108,106,32,8,32,29,108,106,32,9,32,26,108,106,32,10,32,24,108,106,34,7,65,255,63,113,106,32,12,32,20,108,106,32,13,32,18,108,106,32,14,32,17,108,106,33,5,32,11,32,24,108,32,7,65,13,118,32,5,32,6,32,15,108,106,34,15,65,13,118,106,32,3,32,33,108,106,32,4,32,31,108,106,32,8,32,30,108,106,32,9,32,29,108,106,32,10,32,26,108,106,34,3,65,255,63,113,106,32,12,32,22,108,106,32,13,32,20,108,106,32,14,32,18,108,106,33,4,32,3,65,13,118,32,4,32,6,32,17,108,106,34,6,65,13,118,106,34,3,32,3,65,2,116,106,32,32,65,255,63,113,106,34,3,65,13,118,33,4,32,3,65,255,63,113,33,3,32,25,65,255,63,113,32,4,106,33,4,32,28,65,255,63,113,33,8,32,23,65,255,63,113,33,9,32,27,65,255,63,113,33,10,32,21,65,255,63,113,33,11,32,19,65,255,63,113,33,12,32,16,65,255,63,113,33,13,32,15,65,255,63,113,33,14,32,6,65,255,63,113,33,6,32,1,65,16,106,33,1,32,2,65,16,107,33,2,12,1,11,11,35,29,32,3,59,1,0,35,29,65,2,106,32,4,59,1,0,35,29,65,4,106,32,8,59,1,0,35,29,65,6,106,32,9,59,1,0,35,29,65,8,106,32,10,59,1,0,35,29,65,10,106,32,11,59,1,0,35,29,65,12,106,32,12,59,1,0,35,29,65,14,106,32,13,59,1,0,35,29,65,16,106,32,14,59,1,0,35,29,65,18,106,32,6,59,1,0,11,203,1,1,3,127,35,32,4,64,65,16,35,32,107,34,3,32,1,75,4,64,32,1,33,3,11,3,64,32,2,32,3,73,4,64,35,25,32,2,35,32,106,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,32,3,107,33,1,32,3,33,4,32,3,35,32,106,36,32,35,32,65,16,73,4,64,15,11,35,25,65,0,65,16,16,18,65,0,36,32,11,2,127,32,1,65,16,79,4,64,32,0,32,4,32,1,32,1,65,15,113,107,34,3,16,18,32,3,32,4,106,33,4,32,1,32,3,107,33,1,11,32,1,11,4,64,65,0,33,2,3,64,32,2,32,1,73,4,64,35,25,32,2,35,32,106,106,32,0,32,2,32,4,106,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,35,32,106,36,32,11,11,8,0,35,22,32,0,16,19,11,149,9,1,3,127,35,32,4,64,35,32,34,1,35,25,106,65,1,58,0,0,32,1,65,1,106,33,1,3,64,32,1,65,16,73,4,64,32,1,35,25,106,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,65,1,36,33,35,25,65,0,65,16,16,18,11,35,29,65,2,106,47,1,0,65,13,118,33,2,35,29,65,2,106,35,29,65,2,106,47,1,0,65,255,63,113,59,1,0,65,2,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,29,106,32,2,32,3,35,29,106,47,1,0,106,59,1,0,32,3,35,29,106,47,1,0,65,13,118,33,2,32,3,35,29,106,32,3,35,29,106,47,1,0,65,255,63,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,29,47,1,0,32,2,65,5,108,106,59,1,0,35,29,47,1,0,33,1,35,29,35,29,47,1,0,65,255,63,113,59,1,0,35,29,65,2,106,35,29,65,2,106,47,1,0,32,1,65,255,255,3,113,65,13,118,106,59,1,0,35,29,65,2,106,47,1,0,33,1,35,29,65,2,106,35,29,65,2,106,47,1,0,65,255,63,113,59,1,0,35,29,65,4,106,35,29,65,4,106,47,1,0,32,1,65,255,255,3,113,65,13,118,106,59,1,0,35,36,35,29,47,1,0,65,5,106,59,1,0,35,36,47,1,0,65,13,118,33,2,35,36,35,36,47,1,0,65,255,63,113,59,1,0,65,1,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,36,106,32,2,32,3,35,29,106,47,1,0,106,59,1,0,32,3,35,36,106,47,1,0,65,13,118,33,2,32,3,35,36,106,32,3,35,36,106,47,1,0,65,255,63,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,36,65,18,106,35,36,65,18,106,47,1,0,65,128,64,106,59,1,0,32,2,65,1,115,65,1,107,33,2,65,0,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,3,35,36,106,32,2,32,3,35,36,106,47,1,0,113,59,1,0,32,1,65,1,106,33,1,12,1,11,11,32,2,65,127,115,33,3,65,0,33,1,3,64,32,1,65,10,73,4,64,32,1,65,1,116,34,2,35,29,106,32,2,35,36,106,47,1,0,32,3,32,2,35,29,106,47,1,0,113,114,59,1,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,29,47,1,0,35,29,65,2,106,47,1,0,65,13,116,114,59,1,0,35,29,65,2,106,35,29,65,4,106,47,1,0,65,10,116,35,29,65,2,106,47,1,0,65,3,118,114,59,1,0,35,29,65,4,106,35,29,65,6,106,47,1,0,65,7,116,35,29,65,4,106,47,1,0,65,6,118,114,59,1,0,35,29,65,6,106,35,29,65,8,106,47,1,0,65,4,116,35,29,65,6,106,47,1,0,65,9,118,114,59,1,0,35,29,65,8,106,35,29,65,10,106,47,1,0,65,1,116,35,29,65,8,106,47,1,0,65,12,118,114,35,29,65,12,106,47,1,0,65,14,116,114,59,1,0,35,29,65,10,106,35,29,65,14,106,47,1,0,65,11,116,35,29,65,12,106,47,1,0,65,2,118,114,59,1,0,35,29,65,12,106,35,29,65,16,106,47,1,0,65,8,116,35,29,65,14,106,47,1,0,65,5,118,114,59,1,0,35,29,65,14,106,35,29,65,18,106,47,1,0,65,5,116,35,29,65,16,106,47,1,0,65,8,118,114,59,1,0,35,29,35,29,47,1,0,35,31,47,1,0,106,34,2,59,1,0,65,1,33,1,3,64,32,1,65,8,73,4,64,32,1,65,1,116,34,3,35,29,106,47,1,0,32,3,35,31,106,47,1,0,106,32,2,65,16,118,106,33,2,35,29,32,3,106,32,2,59,1,0,32,1,65,1,106,33,1,12,1,11,11,32,0,35,29,47,1,0,58,0,0,32,0,65,1,106,35,29,47,1,0,65,8,118,58,0,0,32,0,65,2,106,35,29,65,2,106,47,1,0,58,0,0,32,0,65,3,106,35,29,65,2,106,47,1,0,65,8,118,58,0,0,32,0,65,4,106,35,29,65,4,106,47,1,0,58,0,0,32,0,65,5,106,35,29,65,4,106,47,1,0,65,8,118,58,0,0,32,0,65,6,106,35,29,65,6,106,47,1,0,58,0,0,32,0,65,7,106,35,29,65,6,106,47,1,0,65,8,118,58,0,0,32,0,65,8,106,35,29,65,8,106,47,1,0,58,0,0,32,0,65,9,106,35,29,65,8,106,47,1,0,65,8,118,58,0,0,32,0,65,10,106,35,29,65,10,106,47,1,0,58,0,0,32,0,65,11,106,35,29,65,10,106,47,1,0,65,8,118,58,0,0,32,0,65,12,106,35,29,65,12,106,47,1,0,58,0,0,32,0,65,13,106,35,29,65,12,106,47,1,0,65,8,118,58,0,0,32,0,65,14,106,35,29,65,14,106,47,1,0,58,0,0,32,0,65,15,106,35,29,65,14,106,47,1,0,65,8,118,58,0,0,65,1,36,34,11,11,0,32,0,32,1,65,1,116,16,3,11,38,0,35,25,65,16,16,13,35,27,65,10,16,22,35,29,65,10,16,22,35,31,65,8,16,22,65,0,36,32,65,0,36,33,65,0,36,34,11,33,1,1,127,35,23,33,0,35,34,4,64,65,144,2,65,208,2,65,226,3,65,4,16,0,0,11,32,0,16,21,16,23,11,39,1,1,127,3,64,32,0,65,32,73,4,64,32,0,35,7,106,65,0,58,0,0,32,0,65,1,106,33,0,12,1,11,11,65,32,16,15,26,11,152,2,1,1,127,3,64,32,4,65,32,72,4,64,32,4,35,9,106,32,0,32,4,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,65,0,33,4,3,64,32,4,65,4,72,4,64,32,4,35,11,106,65,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,65,4,33,4,3,64,32,4,65,16,72,4,64,32,4,35,11,106,32,1,32,4,65,4,107,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,16,25,65,0,33,4,3,64,32,4,65,32,72,4,64,32,4,35,21,106,32,4,35,13,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,35,21,16,16,32,3,65,0,75,4,64,65,0,33,4,3,64,32,4,32,3,73,4,64,32,4,35,22,106,32,2,32,4,106,45,0,0,58,0,0,32,4,65,1,106,33,4,12,1,11,11,32,3,16,20,32,3,65,15,113,65,0,75,4,64,65,16,32,3,65,15,113,107,34,1,65,0,74,4,64,65,0,33,0,3,64,32,0,32,1,72,4,64,32,0,35,22,106,65,0,58,0,0,32,0,65,1,106,33,0,12,1,11,11,32,1,16,20,11,11,11,11,65,1,1,127,3,64,32,2,32,1,73,4,64,35,22,32,2,106,32,0,32,2,106,45,0,0,58,0,0,35,7,32,2,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,20,32,1,16,15,26,11,27,0,32,0,32,1,65,0,16,10,32,0,173,66,128,128,128,128,16,127,167,32,1,65,4,16,10,11,87,1,2,127,32,0,65,15,113,65,0,75,4,64,65,16,32,0,65,15,113,107,34,3,65,0,74,4,64,3,64,32,2,32,3,72,4,64,32,2,35,22,106,65,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,3,16,20,11,11,32,1,35,22,16,28,65,8,16,20,32,0,35,22,16,28,65,8,16,20,16,24,11,34,0,32,0,4,64,35,38,35,40,35,42,32,4,16,26,11,35,44,32,2,16,27,32,1,4,64,32,3,32,4,16,29,11,11,89,1,1,127,3,64,32,2,32,1,73,4,64,35,7,32,2,106,32,0,32,2,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,15,26,65,0,33,2,3,64,32,2,32,1,73,4,64,35,22,32,2,106,32,2,35,13,106,45,0,0,58,0,0,32,2,65,1,106,33,2,12,1,11,11,32,1,16,20,11,34,0,32,0,4,64,35,38,35,40,35,42,32,4,16,26,11,35,44,32,2,16,31,32,1,4,64,32,3,32,4,16,29,11,11,8,0,16,5,16,8,16,9,11,11,234,2,6,0,65,16,11,43,28,0,0,0,1,0,0,0,1,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,192,0,11,53,38,0,0,0,1,0,0,0,1,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,128,1,11,63,48,0,0,0,1,0,0,0,1,0,0,0,48,0,0,0,67,0,104,0,97,0,67,0,104,0,97,0,58,0,32,0,99,0,111,0,117,0,110,0,116,0,101,0,114,0,32,0,111,0,118,0,101,0,114,0,102,0,108,0,111,0,119,0,65,192,1,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,99,0,104,0,97,0,99,0,104,0,97,0,50,0,48,0,46,0,116,0,115,0,65,128,2,11,57,42,0,0,0,1,0,0,0,1,0,0,0,42,0,0,0,80,0,111,0,108,0,121,0,49,0,51,0,48,0,53,0,32,0,119,0,97,0,115,0,32,0,102,0,105,0,110,0,105,0,115,0,104,0,101,0,100,0,65,192,2,11,55,40,0,0,0,1,0,0,0,1,0,0,0,40,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,112,0,111,0,108,0,121,0,49,0,51,0,48,0,53,0,46,0,116,0,115])});var im=He(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});nh.newInstance=void 0;var G7=gw(),V7=new WebAssembly.Module(G7.wasmCode),W7={env:{abort:function(r,e,t,s){throw Error(`abort: ${r}:${e}:${t}:${s}`)}}};function j7(){return new WebAssembly.Instance(V7,W7).exports}nh.newInstance=j7});var ww=He(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});oh.chacha20StreamXOR=void 0;var Y7=im(),ts=Y7.newInstance(),X7=ts.chacha20Input.value,Z7=ts.chacha20Output.value,Q7=ts.chacha20Key.value,J7=ts.chacha20Counter.value,{CHACHA20_INPUT_LENGTH:Mi,KEY_LENGTH:am,CHACHA20_COUNTER_LENGTH:bw}=ts,eT=new Uint8Array(ts.memory.buffer,X7,Mi),yw=new Uint8Array(ts.memory.buffer,Z7,Mi),tT=new Uint8Array(ts.memory.buffer,Q7,am),rT=new Uint8Array(ts.memory.buffer,J7,bw);function sT(r,e,t){if(r.length!=am)throw new Error("ChaCha: key size must be 32 bytes, expected "+am+" got "+r.length);if(e.length!=bw)throw new Error("ChaCha nonce with counter must be 16 bytes");tT.set(r),rT.set(e);let s=new Uint8Array(t.length),n=Math.floor(t.length/Mi);for(let o=0;o<=n;o++){let i=o*Mi,a=Math.min((o+1)*Mi,t.length);eT.set(n===0?t:t.subarray(i,a));let c=a-i,l=ts.chacha20StreamXORUpdate(c);s.set(l===Mi?yw:yw.subarray(0,l),i)}return s}oh.chacha20StreamXOR=sT});var xw=He(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.newInstance=rs.chacha20StreamXOR=rs.Poly1305=rs.ChaCha20Poly1305=void 0;var nT=pw();Object.defineProperty(rs,"ChaCha20Poly1305",{enumerable:!0,get:function(){return nT.ChaCha20Poly1305}});var oT=mw();Object.defineProperty(rs,"Poly1305",{enumerable:!0,get:function(){return oT.Poly1305}});var iT=ww();Object.defineProperty(rs,"chacha20StreamXOR",{enumerable:!0,get:function(){return iT.chacha20StreamXOR}});var aT=im();Object.defineProperty(rs,"newInstance",{enumerable:!0,get:function(){return aT.newInstance}})});var Cw=He((ite,Aw)=>{function bT(){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)}Aw.exports=bT});var Ov=He((joe,Mv)=>{"use strict";function Oe(r,t){var t=t||{};this._capacity=t.capacity,this._head=0,this._tail=0,Array.isArray(r)?this._fromArray(r):(this._capacityMask=3,this._list=new Array(4))}Oe.prototype.peekAt=function(e){var t=e;if(t===(t|0)){var s=this.size();if(!(t>=s||t<-s))return t<0&&(t+=s),t=this._head+t&this._capacityMask,this._list[t]}};Oe.prototype.get=function(e){return this.peekAt(e)};Oe.prototype.peek=function(){if(this._head!==this._tail)return this._list[this._head]};Oe.prototype.peekFront=function(){return this.peek()};Oe.prototype.peekBack=function(){return this.peekAt(-1)};Object.defineProperty(Oe.prototype,"length",{get:function(){return this.size()}});Oe.prototype.size=function(){return this._head===this._tail?0:this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Oe.prototype.unshift=function(e){if(arguments.length===0)return this.size();var t=this._list.length;return this._head=this._head-1+t&this._capacityMask,this._list[this._head]=e,this._tail===this._head&&this._growArray(),this._capacity&&this.size()>this._capacity&&this.pop(),this._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Oe.prototype.shift=function(){var e=this._head;if(e!==this._tail){var t=this._list[e];return this._list[e]=void 0,this._head=e+1&this._capacityMask,e<2&&this._tail>1e4&&this._tail<=this._list.length>>>2&&this._shrinkArray(),t}};Oe.prototype.push=function(e){if(arguments.length===0)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._head<this._tail?this._tail-this._head:this._capacityMask+1-(this._head-this._tail)};Oe.prototype.pop=function(){var e=this._tail;if(e!==this._head){var t=this._list.length;this._tail=e-1+t&this._capacityMask;var s=this._list[this._tail];return this._list[this._tail]=void 0,this._head<2&&e>1e4&&e<=t>>>2&&this._shrinkArray(),s}};Oe.prototype.removeOne=function(e){var t=e;if(t===(t|0)&&this._head!==this._tail){var s=this.size(),n=this._list.length;if(!(t>=s||t<-s)){t<0&&(t+=s),t=this._head+t&this._capacityMask;var o=this._list[t],i;if(e<s/2){for(i=e;i>0;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=s-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}}};Oe.prototype.remove=function(e,t){var s=e,n,o=t;if(s===(s|0)&&this._head!==this._tail){var i=this.size(),a=this._list.length;if(!(s>=i||s<-i||t<1)){if(s<0&&(s+=i),t===1||!t)return n=new Array(1),n[0]=this.removeOne(s),n;if(s===0&&s+t>=i)return n=this.toArray(),this.clear(),n;s+t>i&&(t=i-s);var c;for(n=new Array(t),c=0;c<t;c++)n[c]=this._list[this._head+s+c&this._capacityMask];if(s=this._head+s&this._capacityMask,e+t===i){for(this._tail=this._tail-t+a&this._capacityMask,c=t;c>0;c--)this._list[s=s+1+a&this._capacityMask]=void 0;return n}if(e===0){for(this._head=this._head+t+a&this._capacityMask,c=t-1;c>0;c--)this._list[s=s+1+a&this._capacityMask]=void 0;return n}if(s<i/2){for(this._head=this._head+e+t+a&this._capacityMask,c=e;c>0;c--)this.unshift(this._list[s=s-1+a&this._capacityMask]);for(s=this._head-1+a&this._capacityMask;o>0;)this._list[s=s-1+a&this._capacityMask]=void 0,o--;e<0&&(this._tail=s)}else{for(this._tail=s,s=s+t+a&this._capacityMask,c=i-(t+e);c>0;c--)this.push(this._list[s++]);for(s=this._tail;o>0;)this._list[s=s+1+a&this._capacityMask]=void 0,o--}return this._head<2&&this._tail>1e4&&this._tail<=a>>>2&&this._shrinkArray(),n}}};Oe.prototype.splice=function(e,t){var s=e;if(s===(s|0)){var n=this.size();if(s<0&&(s+=n),!(s>n))if(arguments.length>2){var o,i,a,c=arguments.length,l=this._list.length,u=2;if(!n||s<n/2){for(i=new Array(s),o=0;o<s;o++)i[o]=this._list[this._head+o&this._capacityMask];for(t===0?(a=[],s>0&&(this._head=this._head+s+l&this._capacityMask)):(a=this.remove(s,t),this._head=this._head+s+l&this._capacityMask);c>u;)this.unshift(arguments[--c]);for(o=s;o>0;o--)this.unshift(i[o-1])}else{i=new Array(n-(s+t));var h=i.length;for(o=0;o<h;o++)i[o]=this._list[this._head+s+t+o&this._capacityMask];for(t===0?(a=[],s!=n&&(this._tail=this._head+s+l&this._capacityMask)):(a=this.remove(s,t),this._tail=this._tail-h+l&this._capacityMask);u<c;)this.push(arguments[u++]);for(o=0;o<h;o++)this.push(i[o])}return a}else return this.remove(s,t)}};Oe.prototype.clear=function(){this._list=new Array(this._list.length),this._head=0,this._tail=0};Oe.prototype.isEmpty=function(){return this._head===this._tail};Oe.prototype.toArray=function(){return this._copyArray(!1)};Oe.prototype._fromArray=function(e){var t=e.length,s=this._nextPowerOf2(t);this._list=new Array(s),this._capacityMask=s-1,this._tail=t;for(var n=0;n<t;n++)this._list[n]=e[n]};Oe.prototype._copyArray=function(e,t){var s=this._list,n=s.length,o=this.length;if(t=t|o,t==o&&this._head<this._tail)return this._list.slice(this._head,this._tail);var i=new Array(t),a=0,c;if(e||this._head>this._tail){for(c=this._head;c<n;c++)i[a++]=s[c];for(c=0;c<this._tail;c++)i[a++]=s[c]}else for(c=this._head;c<this._tail;c++)i[a++]=s[c];return i};Oe.prototype._growArray=function(){if(this._head!=0){var e=this._copyArray(!0,this._list.length<<1);this._tail=this._list.length,this._head=0,this._list=e}else this._tail=this._list.length,this._list.length<<=1;this._capacityMask=this._capacityMask<<1|1};Oe.prototype._shrinkArray=function(){this._list.length>>>=1,this._capacityMask>>>=1};Oe.prototype._nextPowerOf2=function(e){var t=Math.log(e)/Math.log(2),s=1<<t+1;return Math.max(s,4)};Mv.exports=Oe});var Ok={};ve(Ok,{ArachnodeFretAdapter:()=>oc,BlockStorage:()=>ci,ClusterClient:()=>Tn,ClusterCoordinator:()=>za,ClusterMember:()=>eu,ClusterService:()=>tu,CoordinatorRepo:()=>ru,FileRawStorage:()=>qa,Libp2pKeyPeerNetwork:()=>ic,MemoryRawStorage:()=>$a,NetworkManagerService:()=>ld,ProtocolClient:()=>cs,RepoClient:()=>i0,RepoService:()=>nu,RestorationCoordinator:()=>rc,RingSelector:()=>sc,SYNC_PROTOCOL_PREFIX:()=>w4,SYNC_PROTOCOL_VERSION:()=>x4,StorageMonitor:()=>nc,StorageRepo:()=>Ga,SyncClient:()=>tc,SyncService:()=>vu,asyncIteratorToArray:()=>na,buildKnownPeers:()=>kk,buildSyncProtocol:()=>ec,clusterMember:()=>n0,clusterService:()=>o0,computeResponsibility:()=>Pk,coordinatorRepo:()=>a0,createLibp2pNode:()=>Tk,first:()=>vd,getNetworkManager:()=>Mk,lessThanLex:()=>oE,networkManagerService:()=>fg,reduce:()=>TE,repoService:()=>c0,sortPeersByDistance:()=>iE,syncService:()=>$0,xorDistanceBytes:()=>nE});function fe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Zc=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Po=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Zc(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Zc(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var hd=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function dt(r={}){return fE(t=>{let s=t.shift();if(s==null)return{done:!0};if(s.error!=null)throw s.error;return{done:s.done===!0,value:s.value}},r)}function fE(r,e){e=e??{};let t=e.onEnd,s=new Po,n,o,i,a=fe(),c=async()=>{try{return s.isEmpty()?i?{done:!0}:await new Promise((g,y)=>{o=w=>{o=null,s.push(w);try{g(r(s))}catch(b){y(b)}return n}}):r(s)}finally{s.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=fe()})}},l=g=>o!=null?o(g):(s.push(g),n),u=g=>(s=new Po,o!=null?o({error:g}):(s.push({error:g}),n)),h=g=>{if(i)return n;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},d=g=>i?n:(i=!0,g!=null?u(g):l({done:!0})),f=()=>(s=new Po,d(),{done:!0}),p=g=>(d(g),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:f,throw:p,push:h,end:d,get readableLength(){return s.size},onEmpty:async g=>{let y=g?.signal;if(y?.throwIfAborted(),s.isEmpty())return;let w,b;y!=null&&(w=new Promise((x,E)=>{b=()=>{E(new hd)},y.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}finally{b!=null&&y!=null&&y?.removeEventListener("abort",b)}}},t==null)return n;let m=n;return n={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(g){return m.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(g){return m.end(g),t!=null&&(t(g),t=void 0),n},get readableLength(){return m.readableLength},onEmpty:g=>m.onEmpty(g)},n}var Qc=class extends Error{type;code;constructor(e,t,s){super(e??"The operation was aborted"),this.type="aborted",this.name=s??"AbortError",this.code=t??"ABORT_ERR"}};async function Ce(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Qc(t?.errorMessage,t?.errorCode,t?.errorName));let s,n=new Qc(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{s=()=>{i(n)},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var dd=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=fe(),this.haveNext=fe()}[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");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=fe(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=fe(),await Ce(this.readNext.promise,t?.signal,t)}};function Jc(){return new dd}function pE(r){return r[Symbol.asyncIterator]!=null}async function mE(r,e,t){try{await Promise.all(r.map(async s=>{for await(let n of s)await e.push(n,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(s){await e.end(s,{signal:t}).catch(()=>{})}}async function*gE(r){let e=new AbortController,t=Jc();mE(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*yE(r){for(let e of r)yield*e}function bE(...r){let e=[];for(let t of r)pE(t)||e.push(t);return e.length===r.length?yE(e):gE(r)}var dn=bE;function st(r,...e){if(r==null)throw new Error("Empty pipeline");if(fd(r)){let s=r;r=()=>s.source}else if(bg(r)||yg(r)){let s=r;r=()=>s}let t=[r,...e];if(t.length>1&&fd(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let s=1;s<t.length-1;s++)fd(t[s])&&(t[s]=xE(t[s]));return wE(...t)}var wE=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},yg=r=>r?.[Symbol.asyncIterator]!=null,bg=r=>r?.[Symbol.iterator]!=null,fd=r=>r==null?!1:r.sink!=null&&r.source!=null,xE=r=>e=>{let t=r.sink(e);if(t?.then!=null){let s=dt({objectMode:!0});t.then(()=>{s.end()},i=>{s.end(i)});let n,o=r.source;if(yg(o))n=async function*(){yield*o,s.end()};else if(bg(o))n=function*(){yield*o,s.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return dn(s,n())}return r.source};wr();ot();nt();var tl=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Do=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},rl=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},sa=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function sl(r){return r[Symbol.asyncIterator]!=null}function Eg(r,e){if(r.byteLength>e)throw new Do("Message length too long")}var ol=r=>{let e=Le(r),t=je(e);return rr(r,t),ol.bytes=e,t};ol.bytes=0;function sr(r,e){e=e??{};let t=e.lengthEncoder??ol,s=e?.maxDataLength??4194304;function*n(o){Eg(o,s);let i=t(o.byteLength);i instanceof Uint8Array?yield i:yield*i,o instanceof Uint8Array?yield o:yield*o}return sl(r)?(async function*(){for await(let o of r)yield*n(o)})():(function*(){for(let o of r)yield*n(o)})()}sr.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??ol,s=e?.maxDataLength??4194304;return Eg(r,s),new W(t(r.byteLength),r)};wr();ot();var fn;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(fn||(fn={}));var xd=r=>{let e=as(r);return xd.bytes=Le(e),e};xd.bytes=0;function Gt(r,e){let t=new W,s=fn.LENGTH,n=-1,o=e?.lengthDecoder??xd,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(s===fn.LENGTH)try{if(n=o(t),n<0)throw new tl("Invalid message length");if(n>a)throw new Do("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(n),s=fn.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new rl("Message length length too long");break}throw l}if(s===fn.DATA){if(t.byteLength<n)break;let l=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(l),yield l,s=fn.LENGTH}}}return sl(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new sa("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new sa("Unexpected end of input")})()}Gt.fromReader=(r,e)=>{let t=1,s=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return Gt(s,{...e??{},onLength:o=>{t=o}})};async function vd(r,e=()=>{throw new Error("No items found")},t){let s=new AbortController,n=typeof t=="number"?setTimeout(()=>s.abort(),t):void 0;try{for await(let o of r(s.signal))return o;return e()}finally{n!==void 0&&clearTimeout(n),s.abort()}}async function na(r){let e=[];for await(let t of r)e.push(t);return e}function TE(r,e,t){let s=t,n=0;for(let o of r)s=e(s,o,n),++n;return s}var cs=class{peerId;peerNetwork;constructor(e,t){this.peerId=e,this.peerNetwork=t}async processMessage(e,t,s){let n=await this.peerNetwork.connect(this.peerId,t,{signal:s?.signal});try{let o=st(n.source,Gt,async function*(a){for await(let c of a){let l=new TextDecoder().decode(c.subarray());yield JSON.parse(l)}}),i=dt();return st(i,sr,n.sink),i.push(new TextEncoder().encode(JSON.stringify(e))),i.end(),await vd(()=>o,()=>{throw new Error("No response received")})}finally{n.close()}}};ce();var Tn=class r extends cs{protocolPrefix;constructor(e,t,s){super(e,t),this.protocolPrefix=s}static create(e,t,s){return new r(e,t,s)}async update(e,t=0){let s={operation:"update",record:e},n=(this.protocolPrefix??"/db-p2p")+"/cluster/1.0.0",o;try{o=await this.processMessage(s,n)}catch(i){if(n!=="/db-p2p/cluster/1.0.0")o=await this.processMessage(s,"/db-p2p/cluster/1.0.0");else throw i}if(o?.redirect?.peers?.length){if(t>=2)throw new Error("Redirect loop detected in ClusterClient (max hops reached)");let i=this.peerId.toString(),a=o.redirect.peers.find(u=>u.id!==i)??o.redirect.peers[0],c=$(a.id);if(a.id===i)throw new Error("Redirect loop detected in ClusterClient (same peer)");return this.recordCoordinatorForRecordIfSupported(e,c),await r.create(c,this.peerNetwork,this.protocolPrefix).update(e,t+1)}return o}recordCoordinatorForRecordIfSupported(e,t){let s=e?.message,n;if(s?.commit?.tailId)n=s.commit.tailId;else if(s?.pend?.transforms){let o=Object.keys(s.pend.transforms);o.length>0&&(n=o[0])}if(n){let o=new TextEncoder().encode(n),i=this.peerNetwork;typeof i?.recordCoordinator=="function"&&i.recordCoordinator(o,t)}}};var Sp=new Map;function jr(r,e){if(Sp.has(r))throw new Error(`Block type ${r} (${e}) already registered (${Sp.get(r)})`);return Sp.set(r,e),r}function Vl(r,[e,t,s,n]){Array.isArray(n)?r[e].splice(t,s,...structuredClone(n)):r[e]=structuredClone(n)}function F8(r,e){for(let t of e)Vl(r,t)}function Pn(r){if(!r)return[];let e=Object.keys(r.inserts??{}),t=Object.keys(r.updates??{}),s=r.deletes??[];return[...new Set([...e,...t,...s])]}function Ip(){return{inserts:{},updates:{},deletes:[]}}function Wl(r,e){return{...e in r.inserts?{insert:r.inserts[e]}:{},...e in r.updates?{updates:r.updates[e]}:{},...e in r.deletes?{delete:!0}:{}}}function _p(r,e){return{inserts:r.insert?{[e]:r.insert}:{},updates:r.updates?{[e]:r.updates}:{},deletes:r.delete?[e]:[]}}function Na(r,e){if(e.insert&&(r=e.insert),r&&e.updates&&F8(r,e.updates),!e.delete)return r}function Ap(r,e,t){return{inserts:{...r.inserts,...t.insert?{[e]:t.insert}:{}},updates:{...r.updates,...t.updates?{[e]:t.updates}:{}},deletes:[...r.deletes,...t.delete?[e]:[]]}}function zt(r,e){return e??r}var U8=jr("TL","TreeLeaf"),K8=jr("TB","TreeBranch"),H8=zt("entries"),z8=zt("partitions"),q8=zt("nodes");var V8=zt("entries"),W8=zt("priorId"),j8=zt("nextId"),Y8=jr("CHD","ChainDataBlock"),X8=zt("headId"),Z8=zt("tailId"),Q8=jr("CHH","ChainHeaderBlock");var Dp={};ve(Dp,{base58btc:()=>Yr,base58flickr:()=>iI});var FN=new Uint8Array(0);function $y(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function ar(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")}function Gy(r){return new TextEncoder().encode(r)}function Vy(r){return new TextDecoder().decode(r)}function eI(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var n=0;n<r.length;n++){var o=r.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,g=0,y=0,w=p.length;y!==w&&p[y]===0;)y++,m++;for(var b=(w-y)*u+1>>>0,x=new Uint8Array(b);y!==w;){for(var E=p[y],P=0,T=b-1;(E!==0||P<g)&&T!==-1;T--,P++)E+=256*x[T]>>>0,x[T]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");g=P,y++}for(var D=b-g;D!==b&&x[D]===0;)D++;for(var v=c.repeat(m);D<b;++D)v+=r.charAt(x[D]);return v}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var g=0,y=0;p[m]===c;)g++,m++;for(var w=(p.length-m)*l+1>>>0,b=new Uint8Array(w);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var E=0,P=w-1;(x!==0||E<y)&&P!==-1;P--,E++)x+=a*b[P]>>>0,b[P]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");y=E,m++}if(p[m]!==" "){for(var T=w-y;T!==w&&b[T]===0;)T++;for(var D=new Uint8Array(g+(w-T)),v=g;T!==w;)D[v++]=b[T++];return D}}}function f(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:f}}var tI=eI,rI=tI,jy=rI;var Cp=class{name;prefix;baseEncode;constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Tp=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,s){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=s}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 Yy(this,e)}},Pp=class{decoders;constructor(e){this.decoders=e}or(e){return Yy(this,e)}decode(e){let t=e[0],s=this.decoders[t];if(s!=null)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Yy(r,e){return new Pp({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var kp=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new Cp(e,t,s),this.decoder=new Tp(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Jo({name:r,prefix:e,encode:t,decode:s}){return new kp(r,e,t,s)}function Ys({name:r,prefix:e,alphabet:t}){let{encode:s,decode:n}=jy(t,r);return Jo({prefix:e,name:r,encode:s,decode:o=>ar(n(o))})}function sI(r,e,t,s){let n=r.length;for(;r[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),i=0,a=0,c=0;for(let l=0;l<n;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${s} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function nI(r,e,t){let s=e[e.length-1]==="=",n=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),s)for(;(o.length*t&7)!==0;)o+="=";return o}function oI(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ne({name:r,prefix:e,bitsPerChar:t,alphabet:s}){let n=oI(s);return Jo({prefix:e,name:r,encode(o){return nI(o,s,t)},decode(o){return sI(o,n,t,r)}})}var Yr=Ys({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),iI=Ys({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Mp={};ve(Mp,{base32:()=>ei,base32hex:()=>uI,base32hexpad:()=>dI,base32hexpadupper:()=>fI,base32hexupper:()=>hI,base32pad:()=>cI,base32padupper:()=>lI,base32upper:()=>aI,base32z:()=>pI});var ei=Ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),aI=Ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cI=Ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lI=Ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),uI=Ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),hI=Ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dI=Ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),fI=Ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),pI=Ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Op={};ve(Op,{base36:()=>Ba,base36upper:()=>mI});var Ba=Ys({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),mI=Ys({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gI=Qy,Xy=128,yI=127,bI=~yI,wI=Math.pow(2,31);function Qy(r,e,t){e=e||[],t=t||0;for(var s=t;r>=wI;)e[t++]=r&255|Xy,r/=128;for(;r&bI;)e[t++]=r&255|Xy,r>>>=7;return e[t]=r|0,Qy.bytes=t-s+1,e}var xI=Lp,vI=128,Zy=127;function Lp(r,s){var t=0,s=s||0,n=0,o=s,i,a=r.length;do{if(o>=a)throw Lp.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=n<28?(i&Zy)<<n:(i&Zy)*Math.pow(2,n),n+=7}while(i>=vI);return Lp.bytes=o-s,t}var EI=Math.pow(2,7),SI=Math.pow(2,14),II=Math.pow(2,21),_I=Math.pow(2,28),AI=Math.pow(2,35),CI=Math.pow(2,42),TI=Math.pow(2,49),PI=Math.pow(2,56),kI=Math.pow(2,63),DI=function(r){return r<EI?1:r<SI?2:r<II?3:r<_I?4:r<AI?5:r<CI?6:r<TI?7:r<PI?8:r<kI?9:10},MI={encode:gI,decode:xI,encodingLength:DI},OI=MI,Fa=OI;function Ua(r,e=0){return[Fa.decode(r,e),Fa.decode.bytes]}function ti(r,e,t=0){return Fa.encode(r,e,t),e}function ri(r){return Fa.encodingLength(r)}function ni(r,e){let t=e.byteLength,s=ri(r),n=s+ri(t),o=new Uint8Array(n+t);return ti(r,o,0),ti(t,o,s),o.set(e,n),new si(r,t,e,o)}function Jy(r){let e=ar(r),[t,s]=Ua(e),[n,o]=Ua(e.subarray(s)),i=e.subarray(s+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new si(t,n,i,e)}function e5(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&$y(r.bytes,t.bytes)}}var si=class{code;size;digest;bytes;constructor(e,t,s,n){this.code=e,this.size=t,this.digest=s,this.bytes=n}};function t5(r,e){let{bytes:t,version:s}=r;switch(s){case 0:return RI(t,Rp(r),e??Yr.encoder);default:return NI(t,Rp(r),e??ei.encoder)}}var r5=new WeakMap;function Rp(r){let e=r5.get(r);if(e==null){let t=new Map;return r5.set(r,t),t}return e}var Yl=class r{code;version;multihash;bytes;"/";constructor(e,t,s,n){this.code=t,this.version=e,this.multihash=s,this.bytes=n,this["/"]=n}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ha)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==BI)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,s=ni(e,t);return r.createV1(this.code,s)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let s=t;return s!=null&&e.code===s.code&&e.version===s.version&&e5(e.multihash,s.multihash)}toString(e){return t5(this,e)}toJSON(){return{"/":t5(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:s,code:n,multihash:o,bytes:i}=t;return new r(s,n,o,i??s5(s,n,o.bytes))}else if(t[FI]===!0){let{version:s,multihash:n,code:o}=t,i=Jy(n);return r.create(s,o,i)}else return null}static create(e,t,s){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(s.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ha)throw new Error(`Version 0 CID must use dag-pb (code: ${Ha}) block encoding`);return new r(e,t,s,s.bytes)}case 1:{let n=s5(e,t,s.bytes);return new r(e,t,s,n)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ha,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,s]=r.decodeFirst(e);if(s.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),s=t.size-t.multihashSize,n=ar(e.subarray(s,s+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new si(t.multihashCode,t.digestSize,o,n);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,s=()=>{let[h,d]=Ua(e.subarray(t));return t+=d,h},n=s(),o=Ha;if(n===18?(n=0,t=0):o=s(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=s(),c=s(),l=t+c,u=l-i;return{version:n,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[s,n]=LI(e,t),o=r.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Rp(o).set(s,e),o}};function LI(r,e){switch(r[0]){case"Q":{let t=e??Yr;return[Yr.prefix,t.decode(`${Yr.prefix}${r}`)]}case Yr.prefix:{let t=e??Yr;return[Yr.prefix,t.decode(r)]}case ei.prefix:{let t=e??ei;return[ei.prefix,t.decode(r)]}case Ba.prefix:{let t=e??Ba;return[Ba.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function RI(r,e,t){let{prefix:s}=t;if(s!==Yr.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(s);if(n==null){let o=t.encode(r).slice(1);return e.set(s,o),o}else return n}function NI(r,e,t){let{prefix:s}=t,n=e.get(s);if(n==null){let o=t.encode(r);return e.set(s,o),o}else return n}var Ha=112,BI=18;function s5(r,e,t){let s=ri(r),n=s+ri(e),o=new Uint8Array(n+t.byteLength);return ti(r,o,0),ti(e,o,s),o.set(t,n),o}var FI=Symbol.for("@ipld/js-cid/CID");var Np={};ve(Np,{identity:()=>HI});var n5=0,UI="identity",o5=ar;function KI(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return ni(n5,o5(r))}var HI={code:n5,name:UI,encode:o5,digest:KI};var a5=re("node:buffer");function i5(r){return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function c5(r=0){return i5(a5.Buffer.allocUnsafe(r))}var Bp={};ve(Bp,{base10:()=>zI});var zI=Ys({prefix:"9",name:"base10",alphabet:"0123456789"});var Fp={};ve(Fp,{base16:()=>qI,base16upper:()=>$I});var qI=Ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$I=Ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Up={};ve(Up,{base2:()=>GI});var GI=Ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Kp={};ve(Kp,{base256emoji:()=>XI});var l5=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),VI=l5.reduce((r,e,t)=>(r[t]=e,r),[]),WI=l5.reduce((r,e,t)=>{let s=e.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${e}`);return r[s]=t,r},[]);function jI(r){return r.reduce((e,t)=>(e+=VI[t],e),"")}function YI(r){let e=[];for(let t of r){let s=t.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${t}`);let n=WI[s];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var XI=Jo({prefix:"\u{1F680}",name:"base256emoji",encode:jI,decode:YI});var Hp={};ve(Hp,{base64:()=>ZI,base64pad:()=>QI,base64url:()=>JI,base64urlpad:()=>e_});var ZI=Ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),QI=Ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),JI=Ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),e_=Ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var zp={};ve(zp,{base8:()=>t_});var t_=Ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var qp={};ve(qp,{identity:()=>r_});var r_=Jo({prefix:"\0",name:"identity",encode:r=>Vy(r),decode:r=>Gy(r)});var fB=new TextEncoder,pB=new TextDecoder;var jp={};ve(jp,{sha256:()=>Wp,sha512:()=>i_});var Vp=we(re("crypto"),1);var o_=20;function Gp({name:r,code:e,encode:t,minDigestLength:s,maxDigestLength:n}){return new $p(r,e,t,s,n)}var $p=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,s,n,o){this.name=e,this.code=t,this.encode=s,this.minDigestLength=n??o_,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let s=this.encode(e);return s instanceof Uint8Array?u5(s,this.code,t?.truncate):s.then(n=>u5(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function u5(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return ni(e,r)}var Wp=Gp({name:"sha2-256",code:18,encode:r=>ar(Vp.default.createHash("sha256").update(r).digest())}),i_=Gp({name:"sha2-512",code:19,encode:r=>ar(Vp.default.createHash("sha512").update(r).digest())});var Yp={...qp,...Up,...zp,...Bp,...Fp,...Mp,...Op,...Dp,...Hp,...Kp},CB={...jp,...Np};function f5(r,e,t,s){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:s}}}var d5=f5("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Xp=f5("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=c5(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),DB={utf8:d5,"utf-8":d5,hex:Yp.base16,latin1:Xp,ascii:Xp,binary:Xp,...Yp};var kn=class{static lockQueues=new Map;static async acquire(e){let t=this.lockQueues.get(e)??Promise.resolve(),s,n=new Promise(i=>{s=i});return this.lockQueues.set(e,n),await t,()=>{s(),this.lockQueues.get(e)===n&&this.lockQueues.delete(e)}}};var u_=jr("DIH","DiaryHeaderBlock");var h_=jr("TRE","TreeHeaderBlock"),d_=zt("rootId");var TF=zt("priorHash");Zp();Zp();var Dn=class{promise;response;error;t1=Date.now();duration;get isResponse(){return this.response!==void 0}get isError(){return this.error!==void 0}get isComplete(){return this.isResponse||this.isError}async result(){if(this.isResponse)return this.response;if(this.isError)throw this.error;return await this.promise}constructor(e){this.promise=e,e.then(t=>(this.duration=Date.now()-this.t1,this.response=t,t),t=>{this.duration=Date.now()-this.t1,this.error=t})}};function Qp(r,e){return r.reduce((t,s)=>{let n=e(s);return(t[n]??=[]).push(s),t},{})}ce();us();Se();var T5=we(s0(),1),N_="optimystic:db-p2p";function lr(r){return(0,T5.default)(`${N_}:${r}`)}var _e=lr("cluster-member"),vt;(function(r){r[r.Promising=0]="Promising",r[r.OurPromiseNeeded=1]="OurPromiseNeeded",r[r.OurCommitNeeded=2]="OurCommitNeeded",r[r.Consensus=3]="Consensus",r[r.Rejected=4]="Rejected",r[r.Propagating=5]="Propagating"})(vt||(vt={}));function n0(r){return new eu(r.storageRepo,r.peerNetwork,r.peerId,r.protocolPrefix,r.partitionDetector,r.fretService,r.validator)}var eu=class{storageRepo;peerNetwork;peerId;protocolPrefix;partitionDetector;fretService;validator;activeTransactions=new Map;cleanupQueue=[];pendingUpdates=new Map;constructor(e,t,s,n,o,i,a){this.storageRepo=e,this.peerNetwork=t,this.peerId=s,this.protocolPrefix=n,this.partitionDetector=o,this.fretService=i,this.validator=a,setInterval(()=>this.queueExpiredTransactions(),6e4),setInterval(()=>this.processCleanupQueue(),1e3)}async update(e){let t=this.pendingUpdates.get(e.messageHash);t&&(_e("cluster-member:concurrent-update-wait",{messageHash:e.messageHash}),await t);let s=this.processUpdate(e);this.pendingUpdates.set(e.messageHash,s);try{return await s}finally{setTimeout(()=>{this.pendingUpdates.delete(e.messageHash)},100)}}async processUpdate(e){let t=this.peerId.toString(),s=e.commits[t]?"commit":e.promises[t]?"promise":"initial";if(_e("cluster-member:incoming",{messageHash:e.messageHash,phase:s,peerCount:Object.keys(e.peers).length,promiseCount:Object.keys(e.promises).length,commitCount:Object.keys(e.commits).length,existingTransaction:this.activeTransactions.has(e.messageHash)}),this.fretService&&e.networkSizeHint&&e.networkSizeConfidence)try{this.fretService.reportNetworkSize(e.networkSizeHint,e.networkSizeConfidence,"cluster")}catch{}await this.validateRecord(e);let n=this.activeTransactions.get(e.messageHash),o=n?.record||e;n&&_e("cluster-member:merge-start",{messageHash:e.messageHash,existingPromises:Object.keys(n.record.promises??{}),existingCommits:Object.keys(n.record.commits??{}),incomingPromises:Object.keys(e.promises??{}),incomingCommits:Object.keys(e.commits??{})}),n&&(o=await this.mergeRecords(n.record,e),_e("cluster-member:merge-complete",{messageHash:e.messageHash,mergedPromises:Object.keys(o.promises??{}),mergedCommits:Object.keys(o.commits??{})}));let i=await this.getTransactionPhase(o);_e("cluster-member:phase",{messageHash:e.messageHash,phase:i,promises:Object.keys(o.promises??{}),commits:Object.keys(o.commits??{})});let a=!0;switch(i){case vt.OurPromiseNeeded:_e("cluster-member:action-promise",{messageHash:e.messageHash}),o=await this.handlePromiseNeeded(o),_e("cluster-member:action-promise-complete",{messageHash:e.messageHash,promises:Object.keys(o.promises??{})});break;case vt.OurCommitNeeded:_e("cluster-member:action-commit",{messageHash:e.messageHash}),o=await this.handleCommitNeeded(o),_e("cluster-member:action-commit-complete",{messageHash:e.messageHash,commits:Object.keys(o.commits??{})}),a=!1;break;case vt.Consensus:_e("cluster-member:action-consensus",{messageHash:e.messageHash}),await this.handleConsensus(o),a=!1;break;case vt.Rejected:_e("cluster-member:action-rejected",{messageHash:e.messageHash}),await this.handleRejection(o),a=!1;break;case vt.Propagating:_e("cluster-member:phase-propagating",{messageHash:e.messageHash}),a=!1;break;case vt.Promising:_e("cluster-member:phase-promising-blocked",{messageHash:e.messageHash});break}if(a){let c=this.setupTimeouts(o);this.activeTransactions.set(e.messageHash,{record:o,lastUpdate:Date.now(),promiseTimeout:c.promiseTimeout,resolutionTimeout:c.resolutionTimeout}),_e("cluster-member:state-persist",{messageHash:e.messageHash,storedPromises:Object.keys(o.promises??{}),storedCommits:Object.keys(o.commits??{})})}else _e("cluster-member:state-clear",{messageHash:e.messageHash}),this.clearTransaction(e.messageHash);return _e("cluster-member:update-complete",{messageHash:e.messageHash,promiseCount:Object.keys(o.promises).length,commitCount:Object.keys(o.commits).length}),o}async mergeRecords(e,t){if(_e("cluster-member:merge-records",{messageHash:e.messageHash,existingPromises:Object.keys(e.promises??{}),existingCommits:Object.keys(e.commits??{}),incomingPromises:Object.keys(t.promises??{}),incomingCommits:Object.keys(t.commits??{})}),e.messageHash!==t.messageHash)throw new Error("Message hash mismatch");if(JSON.stringify(e.message)!==JSON.stringify(t.message))throw new Error("Message content mismatch");if(JSON.stringify(e.peers)!==JSON.stringify(t.peers))throw new Error("Peers mismatch");return{...e,promises:{...e.promises,...t.promises},commits:{...e.commits,...t.commits}}}async validateRecord(e){if(await this.validateSignatures(e),e.message.expiration&&e.message.expiration<Date.now())throw new Error("Transaction expired")}async computeMessageHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)),s=await Qe.digest(t);return K(s.digest,"base64url")}async validateSignatures(e){let t=await this.computePromiseHash(e);for(let[n,o]of Object.entries(e.promises))if(!await this.verifySignature(n,t,o))throw new Error(`Invalid promise signature from ${n}`);let s=await this.computeCommitHash(e);for(let[n,o]of Object.entries(e.commits))if(!await this.verifySignature(n,s,o))throw new Error(`Invalid commit signature from ${n}`)}async computePromiseHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)),s=await Qe.digest(t);return K(s.digest,"base64url")}async computeCommitHash(e){let t=new TextEncoder().encode(e.messageHash+JSON.stringify(e.message)+JSON.stringify(e.promises)),s=await Qe.digest(t);return K(s.digest,"base64url")}async verifySignature(e,t,s){return!0}async getTransactionPhase(e){let t=Object.keys(e.peers).length,s=Object.keys(e.promises).length,n=Object.keys(e.commits).length,o=this.peerId.toString(),i=Object.values(e.promises).filter(l=>l.type==="reject"),a=Object.values(e.commits).filter(l=>l.type==="reject");if(i.length>0||this.hasMajority(a.length,t))return vt.Rejected;if(!e.promises[o]&&!this.hasConflict(e))return vt.OurPromiseNeeded;if(s<t)return vt.Promising;if(s===t&&!e.commits[o])return vt.OurCommitNeeded;let c=Object.values(e.commits).filter(l=>l.type==="approve");return this.hasMajority(c.length,t)?vt.Consensus:vt.Propagating}hasMajority(e,t){return e>t/2}async handlePromiseNeeded(e){let t=await this.validatePendOperations(e),s=t.valid?{type:"approve",signature:"approved"}:{type:"reject",signature:"rejected",rejectReason:t.reason};return t.valid||_e("cluster-member:validation-rejected",{messageHash:e.messageHash,reason:t.reason}),{...e,promises:{...e.promises,[this.peerId.toString()]:s}}}async validatePendOperations(e){if(!this.validator)return{valid:!0};for(let t of e.message.operations)if("pend"in t){let s=t.pend;if(s.transaction&&s.operationsHash){let n=await this.validator.validate(s.transaction,s.operationsHash);if(!n.valid)return{valid:!1,reason:n.reason}}}return{valid:!0}}async handleCommitNeeded(e){if(this.hasLocalCommit(e))return e;let t={type:"approve",signature:"committed"};return{...e,commits:{...e.commits,[this.peerId.toString()]:t}}}async handleConsensus(e){let t=this.activeTransactions.get(e.messageHash);if(!this.hasLocalCommit(t?.record??e))for(let s of e.message.operations)"get"in s?await this.storageRepo.get(s.get):"pend"in s?await this.storageRepo.pend(s.pend):"commit"in s?await this.storageRepo.commit(s.commit):"cancel"in s&&await this.storageRepo.cancel(s.cancel.actionRef)}async handleRejection(e){}setupTimeouts(e){return e.message.expiration?{promiseTimeout:setTimeout(()=>this.handleExpiration(e.messageHash),e.message.expiration-Date.now()),resolutionTimeout:setTimeout(()=>this.resolveWithPeers(e.messageHash),e.message.expiration+5e3-Date.now())}:{}}hasConflict(e){let t=Date.now(),s=2e3;for(let[n,o]of Array.from(this.activeTransactions.entries()))if(n!==e.messageHash){if(t-o.lastUpdate>s){_e("cluster-member:stale-cleanup",{messageHash:n,age:t-o.lastUpdate}),this.clearTransaction(n);continue}if(this.operationsConflict(o.record.message.operations,e.message.operations)){if(this.resolveRace(o.record,e)==="keep-existing")return _e("cluster-member:race-keep-existing",{existing:n,incoming:e.messageHash}),!0;_e("cluster-member:race-accept-incoming",{existing:n,incoming:e.messageHash}),this.clearTransaction(n);continue}}return!1}resolveRace(e,t){let s=Object.keys(e.promises).length,n=Object.keys(t.promises).length;return s>n?"keep-existing":n>s?"accept-incoming":e.messageHash>t.messageHash?"keep-existing":"accept-incoming"}operationsConflict(e,t){let s=this.getActionId(e),n=this.getActionId(t);if(s&&n&&s===n)return!1;let o=new Set(this.getAffectedBlockIds(e)),i=new Set(this.getAffectedBlockIds(t));for(let a of Array.from(o))if(i.has(a))return _e("cluster-member:conflict-detected",{blocks1:Array.from(o),blocks2:Array.from(i),conflictingBlock:a}),!0;return!1}getActionId(e){for(let t of e){if("pend"in t)return t.pend.actionId;if("commit"in t)return t.commit.actionId;if("cancel"in t)return t.cancel.actionRef.actionId}}getAffectedBlockIds(e){let t=new Set;for(let s of e)"get"in s?s.get.blockIds.forEach(n=>t.add(n)):"pend"in s?Pn(s.pend.transforms).forEach(n=>t.add(n)):"commit"in s?s.commit.blockIds.forEach(n=>t.add(n)):"cancel"in s&&s.cancel.actionRef.blockIds.forEach(n=>t.add(n));return Array.from(t)}async propagateIfNeeded(e){let t=[];for(let[s,n]of Object.entries(e.peers))if(s!==this.peerId.toString())try{let o=Tn.create($(s),this.peerNetwork,this.protocolPrefix);t.push(o.update(e))}catch(o){console.error(`Failed to propagate to peer ${s}:`,o)}await Promise.allSettled(t)}async handleExpiration(e){let t=this.activeTransactions.get(e);if(t&&!t.record.promises[this.peerId.toString()]){let s={type:"reject",signature:"rejected",rejectReason:"Transaction expired"},n={...t.record,promises:{...t.record.promises,[this.peerId.toString()]:s}};this.activeTransactions.set(e,{...t,record:n}),await this.propagateIfNeeded(n)}}async resolveWithPeers(e){_e("cluster-member:resolve-skipped",{messageHash:e,reason:"coordinator-handles-retry"})}queueExpiredTransactions(){let e=Date.now();for(let[t,s]of Array.from(this.activeTransactions.entries()))s.record.message.expiration&&s.record.message.expiration<e&&this.cleanupQueue.push(t)}async processCleanupQueue(){for(;this.cleanupQueue.length>0;){let e=this.cleanupQueue.shift();if(!e)continue;let t=this.activeTransactions.get(e);if(!t)continue;let s=await this.getTransactionPhase(t.record);s!==vt.Consensus&&s!==vt.Rejected&&this.activeTransactions.delete(e)}}hasLocalCommit(e){let t=this.peerId.toString();return!!e.commits[t]}clearTransaction(e){let t=this.activeTransactions.get(e);if(!t){_e("cluster-member:clear-miss",{messageHash:e});return}t.promiseTimeout&&clearTimeout(t.promiseTimeout),t.resolutionTimeout&&clearTimeout(t.resolutionTimeout),this.activeTransactions.delete(e),_e("cluster-member:clear-done",{messageHash:e,remaining:Array.from(this.activeTransactions.keys())})}};function o0(r={}){return e=>new tu(e,r)}var tu=class{protocol;maxInboundStreams;maxOutboundStreams;log;cluster;components;running;k;configuredClusterSize;allowDownsize;sizeTolerance;constructor(e,t={}){this.components=e,this.protocol=t.protocol??(t.protocolPrefix??"/db-p2p")+"/cluster/1.0.0",this.maxInboundStreams=t.maxInboundStreams??32,this.maxOutboundStreams=t.maxOutboundStreams??64,this.log=e.logger.forComponent(t.logPrefix??"db-p2p:cluster"),this.cluster=e.cluster,this.running=!1,this.k=t.kBucketSize??10,this.configuredClusterSize=t.configuredClusterSize??10,this.allowDownsize=t.allowClusterDownsize??!0,this.sizeTolerance=t.clusterSizeTolerance??.5}[Symbol.toStringTag]="@libp2p/cluster";async start(){this.running||(await this.components.registrar.handle(this.protocol,this.handleIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.running=!0)}async stop(){this.running&&(await this.components.registrar.unhandle(this.protocol),this.running=!1)}handleIncomingStream(e){let{stream:t,connection:s}=e,n=s.remotePeer,o=async function*(i){for await(let a of i){let c=new TextDecoder().decode(a.subarray()),l=JSON.parse(c),u;if(l.operation==="update"){let d=l.record?.message?.commit?.tailId??l.record?.message?.pend?Object.keys(l.record.message.pend.transforms)[0]:void 0;u=await this.cluster.update(l.record)}else throw new Error(`Unknown operation: ${l.operation}`);if(l.operation==="update"){let d=u;this.log("cluster-service:pre-serialize",{messageHash:d?.messageHash,responseType:typeof u,hasPromises:"promises"in(d??{}),hasCommits:"commits"in(d??{}),promiseKeys:Object.keys(d?.promises??{}),commitKeys:Object.keys(d?.commits??{}),promiseValues:d?.promises,commitValues:d?.commits})}let h=JSON.stringify(u);if(l.operation==="update"){let d=JSON.parse(h);this.log("cluster-service:post-serialize",{messageHash:d?.messageHash,promiseKeys:Object.keys(d?.promises??{}),commitKeys:Object.keys(d?.commits??{})})}yield new TextEncoder().encode(h)}};Promise.resolve().then(async()=>{await st(t,i=>Gt(i),o.bind(this),i=>sr(i),t)}).catch(i=>{this.log.error("error handling cluster protocol message from %p - %e",n,i)})}};ce();var i0=class r extends cs{protocolPrefix;constructor(e,t,s){super(e,t),this.protocolPrefix=s}static create(e,t,s){return new r(e,t,s)}async get(e,t){return this.processRepoMessage([{get:e}],t)}async pend(e,t){return this.processRepoMessage([{pend:e}],t)}async cancel(e,t){return this.processRepoMessage([{cancel:{actionRef:e}}],t)}async commit(e,t){return this.processRepoMessage([{commit:e}],t)}async processRepoMessage(e,t,s=0){let n={operations:e,expiration:t.expiration},o=t.expiration??Date.now()+3e4,i=Math.max(1,o-Date.now()),a=async u=>await Promise.race([u(),new Promise((h,d)=>setTimeout(()=>d(new Error("RepoClient timeout")),i))]),c,l=(this.protocolPrefix??"/db-p2p")+"/repo/1.0.0";if(c=await a(()=>super.processMessage(n,l,{signal:t?.signal})),c?.redirect?.peers?.length){if(s>=2)throw new Error("Redirect loop detected in RepoClient (max hops reached)");let u=this.peerId.toString(),h=c.redirect.peers.find(p=>p.id!==u)??c.redirect.peers[0],d=$(h.id);if(h.id===u)throw new Error("Redirect loop detected in RepoClient (same peer)");return this.recordCoordinatorForOpsIfSupported(e,d),await r.create(d,this.peerNetwork,this.protocolPrefix).processRepoMessage(e,t,s+1)}return c}extractKeyFromOperations(e){let t=e[0];if("get"in t){let s=t.get.blockIds[0];return s?new TextEncoder().encode(s):void 0}if("pend"in t){let s=Object.keys(t.pend.transforms)[0];return s?new TextEncoder().encode(s):void 0}if("commit"in t)return new TextEncoder().encode(t.commit.tailId)}recordCoordinatorForOpsIfSupported(e,t){let s=this.extractKeyFromOperations(e),n=this.peerNetwork;s!=null&&typeof n?.recordCoordinator=="function"&&n.recordCoordinator(s,t)}};ce();Vt();us();var Q=lr("cluster"),za=class{keyNetwork;createClusterClient;cfg;localCluster;fretService;transactions=new Map;retryInitialIntervalMs=2e3;retryBackoffFactor=2;retryMaxIntervalMs=3e4;retryMaxAttempts=5;constructor(e,t,s,n,o){this.keyNetwork=e,this.createClusterClient=t,this.cfg=s,this.localCluster=n,this.fretService=o}async createMessageHash(e){let t=new TextEncoder().encode(JSON.stringify(e)),s=await Qe.digest(t);return me.encode(s.digest)}async getClusterForBlock(e){let t=new TextEncoder().encode(e);try{let s=await this.keyNetwork.findCluster(t),n=Object.keys(s??{});return Q("cluster-tx:cluster-members",{blockId:e,peerIds:n}),s}catch(s){return Q("WARN findCluster failed for %s: %o",e,s),{}}}makeRecord(e,t,s){let n=Object.keys(e??{}).length,o={messageHash:t,peers:e,message:s,coordinatingBlockIds:s.coordinatingBlockIds,promises:{},commits:{},suggestedClusterSize:n||void 0,minRequiredSize:this.cfg.allowClusterDownsize?void 0:this.cfg.clusterSize};if(this.fretService)try{let i=this.fretService.getNetworkSizeEstimate();i.size_estimate>0&&(o.networkSizeHint=i.size_estimate,o.networkSizeConfidence=i.confidence)}catch{}return o}async executeClusterTransaction(e,t,s){let n=await this.getClusterForBlock(e),o=await this.createMessageHash(t),i=this.makeRecord(n,o,t);Q("cluster-tx:start",{messageHash:o,blockId:e,peerCount:Object.keys(n??{}).length,allowDownsize:this.cfg.allowClusterDownsize,configuredSize:this.cfg.clusterSize,suggestedSize:i.suggestedClusterSize,minRequiredSize:i.minRequiredSize});let a=this.executeTransaction(n,i),c=new Dn(a),l={messageHash:o,record:i,pending:c,lastUpdate:Date.now()};this.transactions.set(o,l),Q("cluster-tx:transaction-store",{messageHash:o,transactionKeys:Array.from(this.transactions.keys())});try{return await c.result()}finally{let u=this.transactions.get(o),h=u?.retry?{attempt:u.retry.attempt,pending:Array.from(u.retry.pendingPeers??[])}:void 0;Q("cluster-tx:complete",{messageHash:o,finalPromises:u?Object.keys(u.record.promises??{}):void 0,finalCommits:u?Object.keys(u.record.commits??{}):void 0,retry:h}),u?.retry||setTimeout(()=>{this.transactions.delete(o),Q("cluster-tx:transaction-remove",{messageHash:o,remaining:Array.from(this.transactions.keys())})},100)}}async executeTransaction(e,t){let s=Object.keys(e).length;if(s<this.cfg.minAbsoluteClusterSize){if(!await this.validateSmallCluster(s,e))throw Q("cluster-tx:reject-too-small",{peerCount:s,minRequired:this.cfg.minAbsoluteClusterSize}),new Error(`Cluster size ${s} below minimum ${this.cfg.minAbsoluteClusterSize} and not validated`);Q("cluster-tx:small-cluster-validated",{peerCount:s})}if(!this.cfg.allowClusterDownsize&&s<this.cfg.clusterSize)throw Q("cluster-tx:reject-downsize",{peerCount:s,required:this.cfg.clusterSize}),new Error(`Cluster size ${s} below configured minimum ${this.cfg.clusterSize}`);let n=await this.collectPromises(e,t),o=Math.ceil(s*this.cfg.superMajorityThreshold),i=n.record.promises,a=Object.values(i).filter(u=>u.type==="approve").length,c=Object.values(i).filter(u=>u.type==="reject").length,l=s-o;if(c>l){let u=Object.entries(i).filter(([h,d])=>d.type==="reject").map(([h,d])=>`${h}: ${d.rejectReason??"unknown"}`).join("; ");throw Q("cluster-tx:rejected-by-validators",{messageHash:t.messageHash,peerCount:s,rejections:c,maxAllowed:l,reasons:u}),this.updateTransactionRecord(n.record,"rejected-by-validators"),new Error(`Transaction rejected by validators (${c}/${s} rejected): ${u}`)}if(s>1&&a<o)throw Q("cluster-tx:supermajority-failed",{messageHash:t.messageHash,peerCount:s,approvals:a,rejections:c,superMajority:o,threshold:this.cfg.superMajorityThreshold}),this.updateTransactionRecord(n.record,"supermajority-failed"),new Error(`Failed to get super-majority: ${a}/${s} approvals (needed ${o}, ${c} rejections)`);return await this.commitTransaction(n.record)}async getClusterSize(e){let t=await this.getClusterForBlock(e);return Object.keys(t??{}).length}async validateSmallCluster(e,t){if(this.fretService)try{let s=this.fretService.getNetworkSizeEstimate();if(s.confidence>.5){let n=Math.floor(Math.log10(s.size_estimate+1)),o=Math.floor(Math.log10(e+1));if(Math.abs(n-o)<=1)return Q("cluster-tx:small-cluster-validated-by-fret",{localSize:e,fretEstimate:s.size_estimate,confidence:s.confidence,sources:s.sources}),!0}}catch{}return Q("cluster-tx:small-cluster-accepted-without-validation",{localSize:e,reason:"no-confident-network-size-estimate"}),!0}async collectPromises(e,t){let s=Object.keys(e),n=[],o=s.map(l=>{let u=this.localCluster&&l===this.localCluster.peerId.toString();Q("cluster-tx:promise-request",{messageHash:t.messageHash,peerId:l,isLocal:u});let h=u?this.localCluster.update(t):this.createClusterClient($(l)).update(t);return new Dn(h)}),i=await Promise.all(o.map((l,u)=>l.result().then(h=>{let d=s[u];return Q("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:d,success:!0,returnedPromises:Object.keys(h.promises??{}),returnedCommits:Object.keys(h.commits??{})}),n.push({peerId:d,success:!0}),h}).catch(h=>{let d=s[u];return Q("cluster-tx:promise-response",{messageHash:t.messageHash,peerId:d,success:!1,error:h}),n.push({peerId:d,success:!1,error:h instanceof Error?h.message:String(h)}),null}))),a=n.filter(l=>l.success).map(l=>l.peerId),c=n.filter(l=>!l.success);Q("cluster-tx:promise-summary",{messageHash:t.messageHash,successes:a,failures:c}),Q("cluster-tx:promise-merge-begin",{messageHash:t.messageHash,initialPromises:Object.keys(t.promises??{}),transactionsKeys:Array.from(this.transactions.keys()),hasTransaction:this.transactions.has(t.messageHash)});for(let l of i.filter(Boolean)){Q("cluster-tx:promise-merge-input",{messageHash:t.messageHash,resultFrom:Object.keys(l.promises??{}),recordBefore:Object.keys(t.promises??{})});let u=Object.keys(l.promises??{});if(Q("cluster-tx:promise-merge-result",{messageHash:t.messageHash,peerPromises:u}),typeof t.suggestedClusterSize=="number"&&typeof l.suggestedClusterSize=="number"){let h=l.suggestedClusterSize,d=Object.keys(e).length,f=Math.ceil(Math.max(1,h*this.cfg.clusterSizeTolerance));Math.abs(d-h)>f&&Q("cluster-tx:size-variance",{expected:h,actual:d,tolerance:this.cfg.clusterSizeTolerance})}t.promises={...t.promises,...l.promises},Q("cluster-tx:promise-merge-after",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})})}return Q("cluster-tx:promise-merge",{messageHash:t.messageHash,mergedPromises:Object.keys(t.promises??{})}),Q("cluster-tx:promise-merge-end",{messageHash:t.messageHash,finalPromises:Object.keys(t.promises??{}),transactionsEntry:this.transactions.get(t.messageHash)}),this.updateTransactionRecord(t,"after-promises"),{record:t}}async commitTransaction(e){let t=Object.keys(e.peers),s=[],n={...e},o=t.map(f=>{let p=this.localCluster&&f===this.localCluster.peerId.toString();Q("cluster-tx:commit-request",{messageHash:e.messageHash,peerId:f,isLocal:p});let m=p?this.localCluster.update(n):this.createClusterClient($(f)).update(n);return new Dn(m)}),i=await Promise.all(o.map((f,p)=>f.result().then(m=>{let g=t[p];return Q("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!0}),s.push({peerId:g,success:!0}),m}).catch(m=>{let g=t[p];return Q("cluster-tx:commit-response",{messageHash:e.messageHash,peerId:g,success:!1,error:m}),s.push({peerId:g,success:!1,error:m instanceof Error?m.message:String(m)}),null}))),a=s.filter(f=>f.success).map(f=>f.peerId),c=s.filter(f=>!f.success);Q("cluster-tx:commit-summary",{messageHash:e.messageHash,successes:a,failures:c}),Q("cluster-tx:commit-merge-begin",{messageHash:e.messageHash,initialCommits:Object.keys(e.commits??{}),transactionsEntry:this.transactions.get(e.messageHash)});for(let f of i.filter(Boolean))Q("cluster-tx:commit-merge-input",{messageHash:e.messageHash,resultFrom:Object.keys(f.commits??{}),recordBefore:Object.keys(e.commits??{})}),Q("cluster-tx:commit-merge-result",{messageHash:e.messageHash,peerCommits:Object.keys(f.commits??{})}),e.commits={...e.commits,...f.commits},Q("cluster-tx:commit-merge-after",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})});Q("cluster-tx:commit-merge",{messageHash:e.messageHash,mergedCommits:Object.keys(e.commits??{})}),Q("cluster-tx:commit-merge-end",{messageHash:e.messageHash,finalCommits:Object.keys(e.commits??{}),transactionsEntry:this.transactions.get(e.messageHash)}),this.updateTransactionRecord(e,"after-commit");let l=Object.keys(e.peers).length,u=Math.floor(l*this.cfg.simpleMajorityThreshold)+1,h=Object.keys(e.commits).length;h>=u&&Q("cluster-tx:commit-majority-reached",{messageHash:e.messageHash,commitCount:h,simpleMajority:u,peerCount:l,threshold:this.cfg.simpleMajorityThreshold});let d=c.map(f=>f.peerId);return d.length>0?this.scheduleCommitRetry(e.messageHash,e,d):this.clearRetry(e.messageHash),e}updateTransactionRecord(e,t){let s=this.transactions.get(e.messageHash);if(!s){Q("cluster-tx:transaction-update-miss",{messageHash:e.messageHash,stage:t});return}s.record={...e},s.lastUpdate=Date.now(),Q("cluster-tx:transaction-update",{messageHash:e.messageHash,stage:t,promises:Object.keys(e.promises??{}),commits:Object.keys(e.commits??{})})}scheduleCommitRetry(e,t,s){let n=this.transactions.get(e);if(!n)return;let o=n.retry,i=(o?.attempt??0)+1;if(i>this.retryMaxAttempts){Q("cluster-tx:retry-abort",{messageHash:e,missingPeers:s});return}if(s.length===0){this.clearRetry(e);return}let a=new Set(s),c=o?Math.min(o.intervalMs*this.retryBackoffFactor,this.retryMaxIntervalMs):this.retryInitialIntervalMs;o?.timer&&clearTimeout(o.timer);let l=setTimeout(()=>{this.retryCommits(e)},c);n.retry={pendingPeers:a,attempt:i,intervalMs:c,timer:l},Q("cluster-tx:retry-scheduled",{messageHash:e,attempt:i,missingPeers:s,delayMs:c})}async retryCommits(e){let t=this.transactions.get(e);if(!t?.retry)return;let{pendingPeers:s,attempt:n}=t.retry;if(s.size===0){this.clearRetry(e);return}let o=Array.from(s),i=t.record;Q("cluster-tx:retry-start",{messageHash:e,attempt:n,peerIds:o});let a=await Promise.all(o.map(async u=>{let h=this.localCluster&&u===this.localCluster.peerId.toString(),d={...i,commits:i.commits};try{let f=h?await this.localCluster.update(d):await this.createClusterClient($(u)).update(d);return t.record.commits={...t.record.commits,...f.commits},{peerId:u,success:!0}}catch(f){return{peerId:u,success:!1,error:f instanceof Error?f.message:String(f)}}})),c=a.filter(u=>u.success).map(u=>u.peerId),l=a.filter(u=>!u.success);for(let u of c)s.delete(u);if(Q("cluster-tx:retry-complete",{messageHash:e,attempt:n,successes:c,failures:l}),s.size===0){Q("cluster-tx:retry-finished",{messageHash:e}),this.clearRetry(e);return}this.transactions.has(e)&&this.scheduleCommitRetry(e,t.record,Array.from(s))}clearRetry(e){let t=this.transactions.get(e);t?.retry&&(t.retry.timer&&clearTimeout(t.retry.timer),t.retry=void 0,setTimeout(()=>{this.transactions.delete(e),Q("cluster-tx:transaction-remove",{messageHash:e,remaining:Array.from(this.transactions.keys())})},100))}};function a0(r,e,t,s){return n=>new ru(r,e,n.storageRepo,t,n.localCluster,n.localPeerId,s)}var ru=class{keyNetwork;createClusterClient;storageRepo;coordinator;DEFAULT_TIMEOUT=3e4;constructor(e,t,s,n,o,i,a){this.keyNetwork=e,this.createClusterClient=t,this.storageRepo=s;let c={clusterSize:n?.clusterSize??10,superMajorityThreshold:n?.superMajorityThreshold??.75,simpleMajorityThreshold:n?.simpleMajorityThreshold??.51,minAbsoluteClusterSize:n?.minAbsoluteClusterSize??3,allowClusterDownsize:n?.allowClusterDownsize??!0,clusterSizeTolerance:n?.clusterSizeTolerance??.5,partitionDetectionWindow:n?.partitionDetectionWindow??6e4},l=o&&i?{update:o.update.bind(o),peerId:i}:void 0;this.coordinator=new za(e,t,c,l,a)}async get(e,t){return await this.storageRepo.get(e,t)}async pend(e,t){let s=Object.keys(e.transforms),n=t?.coordinatingBlockIds??s;if(await this.coordinator.getClusterSize(n[0])<=1)return await this.storageRepo.pend(e,t);let i={operations:[{pend:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT,coordinatingBlockIds:n};try{return await this.coordinator.executeClusterTransaction(n[0],i,t),await this.storageRepo.pend(e,t)}catch(a){throw console.error("Failed to complete pend operation:",a),a}}async cancel(e,t){let s=e.blockIds,n={operations:[{cancel:{actionRef:e}}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{let o=s.map(i=>this.coordinator.executeClusterTransaction(i,n,t));await Promise.all(o),await this.storageRepo.cancel(e,t)}catch(o){throw console.error("Failed to complete cancel operation:",o),o}}async commit(e,t){let s=e.blockIds;if(await this.coordinator.getClusterSize(s[0])<=1)return await this.storageRepo.commit(e,t);let o={operations:[{commit:e}],expiration:t?.expiration??Date.now()+this.DEFAULT_TIMEOUT};try{return await this.coordinator.executeClusterTransaction(s[0],o,t),await this.storageRepo.commit(e,t)}catch(i){throw console.error("Failed to complete commit operation:",i),i}}};function P5(r){try{if(r==null)return null;if(typeof r?.toString=="function")return r.toString();let e=r.id;return e&&typeof e.toString=="function"?e.toString():typeof e=="string"?e:typeof r=="string"?r:null}catch{return null}}function On(r,e){let t=P5(r),s=P5(e);return t!=null&&s!=null&&t===s}us();function su(r){return{redirect:{peers:r,reason:"not_in_cluster"}}}function c0(r={}){return e=>new nu(e,r)}var nu=class{protocol;maxInboundStreams;maxOutboundStreams;log;repo;components;running;k;constructor(e,t={}){this.components=e;let s=t.protocol??(t.protocolPrefix??"/db-p2p")+"/repo/1.0.0";this.protocol=s,this.maxInboundStreams=t.maxInboundStreams??32,this.maxOutboundStreams=t.maxOutboundStreams??64,this.log=e.logger.forComponent(t.logPrefix??"db-p2p:repo-service"),this.repo=e.repo,this.running=!1,this.k=t.kBucketSize??10}[Symbol.toStringTag]="@libp2p/repo-service";async start(){this.running||(await this.components.registrar.handle(this.protocol,this.handleIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.running=!0)}async stop(){this.running&&(await this.components.registrar.unhandle(this.protocol),this.running=!1)}handleIncomingStream(e){let{stream:t,connection:s}=e,n=s.remotePeer,o=async function*(i){for await(let a of i){let c=new TextDecoder().decode(a.subarray()),l=JSON.parse(c),u=l.operations[0],h;if("get"in u){let f=(await Qe.digest(new TextEncoder().encode(u.get.blockIds[0]))).digest,p=this.components.libp2p?.services?.networkManager;if(p?.getCluster){let m=await p.getCluster(f);l.cluster=m.map(b=>b.toString?.()??String(b));let g=this.components.libp2p.peerId,y=m.some(b=>On(b,g));if(!(m.length<this.k)&&!y){let b=m.filter(x=>!On(x,g));console.debug("repo-service:redirect",{peerId:g.toString(),reason:"not-cluster-member",operation:"get",blockId:u.get.blockIds[0],cluster:m.map(x=>x.toString?.()??String(x))}),h=su(b.map(x=>({id:x.toString(),addrs:[]})))}else h=await this.repo.get(u.get,{expiration:l.expiration})}else h=await this.repo.get(u.get,{expiration:l.expiration})}else if("pend"in u){let d=Object.keys(u.pend.transforms)[0],p=(await Qe.digest(new TextEncoder().encode(d))).digest,m=this.components.libp2p?.services?.networkManager;if(m?.getCluster){let g=await m.getCluster(p);l.cluster=g.map(x=>x.toString?.()??String(x));let y=this.components.libp2p.peerId,w=g.some(x=>On(x,y));if(!(g.length<this.k)&&!w){let x=g.filter(E=>!On(E,y));console.debug("repo-service:redirect",{peerId:y.toString(),reason:"not-cluster-member",operation:"pend",blockId:d,cluster:g.map(E=>E.toString?.()??String(E))}),h=su(x.map(E=>({id:E.toString(),addrs:[]})))}else h=await this.repo.pend(u.pend,{expiration:l.expiration})}else h=await this.repo.pend(u.pend,{expiration:l.expiration})}else if("cancel"in u)h=await this.repo.cancel(u.cancel.actionRef,{expiration:l.expiration});else if("commit"in u){let f=(await Qe.digest(new TextEncoder().encode(u.commit.tailId))).digest,p=this.components.libp2p?.services?.networkManager;if(p?.getCluster){let m=await p.getCluster(f);l.cluster=m.map(b=>b.toString?.()??String(b));let g=this.components.libp2p.peerId,y=m.some(b=>On(b,g));if(!(m.length<this.k)&&!y){let b=m.filter(x=>!On(x,g));console.debug("repo-service:redirect",{peerId:g.toString(),reason:"not-cluster-member",operation:"commit",tailId:u.commit.tailId,cluster:m.map(x=>x.toString?.()??String(x))}),h=su(b.map(x=>({id:x.toString(),addrs:[]})))}else h=await this.repo.commit(u.commit,{expiration:l.expiration})}else h=await this.repo.commit(u.commit,{expiration:l.expiration})}yield new TextEncoder().encode(JSON.stringify(h))}};Promise.resolve().then(async()=>{await st(t,i=>Gt(i),o.bind(this),i=>sr(i),t)}).catch(i=>{this.log.error("error handling repo protocol message from %p - %e",n,i)})}};function k5(r){if(r.length<=1)return r;r.sort((t,s)=>t[0]-s[0]);let e=[r[0]];for(let t of r.slice(1)){let s=e[e.length-1];s[1]!==void 0&&(t[0]<=s[1]?t[1]===void 0?s[1]=void 0:s[1]=Math.max(s[1],t[1]):e.push(t))}return e}var ci=class{blockId;storage;restoreCallback;constructor(e,t,s){this.blockId=e,this.storage=t,this.restoreCallback=s}async getLatest(){return(await this.storage.getMetadata(this.blockId))?.latest}async getBlock(e){let t=await this.storage.getMetadata(this.blockId);if(!t)return;let s=e??t.latest?.rev;if(s===void 0)throw new Error(`No revision specified and no latest revision exists for block ${this.blockId}`);return await this.ensureRevision(t,s),await this.materializeBlock(t,s)}async getTransaction(e){return await this.storage.getTransaction(this.blockId,e)}async getPendingTransaction(e){return await this.storage.getPendingTransaction(this.blockId,e)}async*listPendingTransactions(){yield*this.storage.listPendingTransactions(this.blockId)}async savePendingTransaction(e,t){let s=await this.storage.getMetadata(this.blockId);s||(s={latest:void 0,ranges:[[0]]},await this.storage.saveMetadata(this.blockId,s)),await this.storage.savePendingTransaction(this.blockId,e,t)}async deletePendingTransaction(e){await this.storage.deletePendingTransaction(this.blockId,e)}async*listRevisions(e,t){yield*this.storage.listRevisions(this.blockId,e,t)}async saveMaterializedBlock(e,t){await this.storage.saveMaterializedBlock(this.blockId,e,t)}async saveRevision(e,t){await this.storage.saveRevision(this.blockId,e,t)}async promotePendingTransaction(e){await this.storage.promotePendingTransaction(this.blockId,e)}async setLatest(e){let t=await this.storage.getMetadata(this.blockId);if(!t)throw new Error(`Block ${this.blockId} not found`);t.latest=e,await this.storage.saveMetadata(this.blockId,t)}async ensureRevision(e,t){if(this.inRanges(t,e.ranges))return;let s=`BlockStorage.ensureRevision:${this.blockId}`,n=await kn.acquire(s);try{let o=await this.storage.getMetadata(this.blockId);if(!o)throw new Error(`Block ${this.blockId} metadata disappeared unexpectedly.`);if(this.inRanges(t,o.ranges))return;let i=await this.restoreBlock(t);if(!i)throw new Error(`Block ${this.blockId} revision ${t} not found during restore attempt.`);await this.saveRestored(i),o.ranges.unshift(i.range),o.ranges=k5(o.ranges),await this.storage.saveMetadata(this.blockId,o)}finally{n()}}async materializeBlock(e,t){let s,n,o=[];for await(let i of this.storage.listRevisions(this.blockId,t,1)){let a=await this.storage.getMaterializedBlock(this.blockId,i.actionId);if(a){s=a,n=i;break}else o.push(i)}if(!s||!n)throw new Error(`Failed to find materialized block ${this.blockId} for revision ${t}`);for(let i=o.length-1;i>=0;--i){let{actionId:a}=o[i],c=await this.storage.getTransaction(this.blockId,a);if(!c)throw new Error(`Missing action ${a} for block ${this.blockId}`);s=Na(s,c)}if(!s)throw new Error(`Block ${this.blockId} has been deleted`);return o.length?(await this.storage.saveMaterializedBlock(this.blockId,o[0].actionId,s),{block:s,actionRev:o[0]}):{block:s,actionRev:n}}async restoreBlock(e){if(this.restoreCallback)return await this.restoreCallback(this.blockId,e)}async saveRestored(e){let t=Object.entries(e.revisions).map(([s,n])=>({rev:Number(s),data:n}));for(let{rev:s,data:{action:n,block:o}}of t)await Promise.all([this.storage.saveRevision(this.blockId,s,n.actionId),this.storage.saveTransaction(this.blockId,n.actionId,n.transform),o?this.storage.saveMaterializedBlock(this.blockId,n.actionId,o):Promise.resolve()])}inRanges(e,t){return t.some(s=>e>=s[0]&&(s[1]===void 0||e<s[1]))}};var ys=re("fs"),kr=we(re("path"),1);var ou=lr("storage:file"),qa=class{basePath;constructor(e){this.basePath=e}async getMetadata(e){return this.readIfExists(this.getMetadataPath(e))}async saveMetadata(e,t){await this.ensureAndWriteFile(this.getMetadataPath(e),JSON.stringify(t))}async getRevision(e,t){return this.readIfExists(this.getRevisionPath(e,t))}async saveRevision(e,t,s){await this.ensureAndWriteFile(this.getRevisionPath(e,t),s)}async getPendingTransaction(e,t){return this.readIfExists(this.getPendingActionPath(e,t))}async savePendingTransaction(e,t,s){await this.ensureAndWriteFile(this.getPendingActionPath(e,t),JSON.stringify(s))}async deletePendingTransaction(e,t){let s=this.getPendingActionPath(e,t);await ys.promises.unlink(s).catch(n=>{n?.code!=="ENOENT"&&ou("deletePendingTransaction unlink failed for %s/%s - %o",e,t,n)})}async*listPendingTransactions(e){let t=kr.join(this.getBlockPath(e),"pend"),s=await ys.promises.readdir(t).catch(n=>(ou("listPendingTransactions readdir failed for %s - %o",e,n),[]));for(let n of s){if(!n.endsWith(".json"))continue;let o=n.slice(0,-5);/^[\w\d]+-[\w\d]+-[\w\d]+-[\w\d]+-[\w\d]+$/.test(o)&&(yield o)}}async getTransaction(e,t){return this.readIfExists(this.getActionPath(e,t))}async*listRevisions(e,t,s){for(let n=t;t<=s?n<=s:n>=s;t<=s?++n:--n){let o=await this.getRevision(e,n);o&&(yield{actionId:o,rev:n})}}async saveTransaction(e,t,s){await this.ensureAndWriteFile(this.getActionPath(e,t),JSON.stringify(s))}async getMaterializedBlock(e,t){return this.readIfExists(this.getMaterializedPath(e,t))}async saveMaterializedBlock(e,t,s){s?await this.ensureAndWriteFile(this.getMaterializedPath(e,t),JSON.stringify(s)):await ys.promises.unlink(this.getMaterializedPath(e,t)).catch(n=>{n?.code!=="ENOENT"&&ou("saveMaterializedBlock unlink failed for %s/%s - %o",e,t,n)})}async promotePendingTransaction(e,t){let s=this.getPendingActionPath(e,t),n=this.getActionPath(e,t);return await ys.promises.mkdir(kr.dirname(n),{recursive:!0}),ys.promises.rename(s,n).catch(o=>{throw o.code==="ENOENT"?new Error(`Pending action ${t} not found for block ${e}`):(ou("promotePendingTransaction rename failed for %s/%s - %o",e,t,o),o)})}getBlockPath(e){return kr.join(this.basePath,e)}getMetadataPath(e){return kr.join(this.getBlockPath(e),"meta.json")}getRevisionPath(e,t){return kr.join(this.getBlockPath(e),"revs",`${t}.json`)}getPendingActionPath(e,t){return kr.join(this.getBlockPath(e),"pend",`${t}.json`)}getActionPath(e,t){return kr.join(this.getBlockPath(e),"actions",`${t}.json`)}getMaterializedPath(e,t){return kr.join(this.getBlockPath(e),"blocks",`${t}.json`)}async readIfExists(e){return ys.promises.readFile(e,"utf-8").then(t=>JSON.parse(t)).catch(t=>{if(t.code!=="ENOENT")throw t})}async ensureAndWriteFile(e,t){await ys.promises.mkdir(kr.dirname(e),{recursive:!0}),await ys.promises.writeFile(e,t)}};var $a=class{metadata=new Map;revisions=new Map;pendingActions=new Map;actions=new Map;materializedBlocks=new Map;getRevisionKey(e,t){return`${e}:${t}`}getActionKey(e,t){return`${e}:${t}`}async getMetadata(e){return this.metadata.get(e)}async saveMetadata(e,t){this.metadata.set(e,t)}async getRevision(e,t){return this.revisions.get(this.getRevisionKey(e,t))}async saveRevision(e,t,s){this.revisions.set(this.getRevisionKey(e,t),s)}async*listRevisions(e,t,s){let n=t<=s,o=n?t:s,i=n?s:t,a=[];for(let c=o;c<=i;c++){let l=this.revisions.get(this.getRevisionKey(e,c));l&&a.push({rev:c,actionId:l})}n||a.reverse();for(let c of a)yield c}async getPendingTransaction(e,t){return this.pendingActions.get(this.getActionKey(e,t))}async savePendingTransaction(e,t,s){this.pendingActions.set(this.getActionKey(e,t),s)}async deletePendingTransaction(e,t){this.pendingActions.delete(this.getActionKey(e,t))}async*listPendingTransactions(e){let t=`${e}:`;for(let[s]of Array.from(this.pendingActions.entries()))s.startsWith(t)&&(yield s.substring(t.length))}async getTransaction(e,t){return this.actions.get(this.getActionKey(e,t))}async saveTransaction(e,t,s){this.actions.set(this.getActionKey(e,t),s)}async getMaterializedBlock(e,t){return this.materializedBlocks.get(this.getActionKey(e,t))}async saveMaterializedBlock(e,t,s){let n=this.getActionKey(e,t);s?this.materializedBlocks.set(n,s):this.materializedBlocks.delete(n)}async promotePendingTransaction(e,t){let s=this.getActionKey(e,t),n=this.pendingActions.get(s);n&&(this.actions.set(s,n),this.pendingActions.delete(s))}};var Ga=class{createBlockStorage;validatePend;constructor(e,t){this.createBlockStorage=e,this.validatePend=t?.validatePend}async get({blockIds:e,context:t},s){let n=Array.from(new Set(e)),o=await Promise.all(n.map(async i=>{let a=this.createBlockStorage(i);if(t){let u=await a.getLatest(),h=u?t.committed.filter(d=>d.rev>u.rev):t.committed;for(let{actionId:d,rev:f}of h.sort((p,m)=>p.rev-m.rev))await a.getPendingTransaction(d)&&await this.internalCommit(i,d,f,a)}let c=await a.getBlock(t?.rev);if(!c)return[i,{state:{}}];if(t?.actionId!==void 0){let u=await a.getPendingTransaction(t.actionId);if(!u)throw new Error(`Pending action ${t.actionId} not found`);let h=Na(c.block,u);return[i,{block:h,state:{latest:await a.getLatest(),pendings:[t.actionId]}}]}let l=await na(a.listPendingTransactions());return[i,{block:c.block,state:{latest:await a.getLatest(),pendings:l}}]}));return Object.fromEntries(o)}async pend(e,t){if(this.validatePend&&e.transaction&&e.operationsHash){let i=await this.validatePend(e.transaction,e.operationsHash);if(!i.valid)return{success:!1,reason:i.reason??"Transaction validation failed"}}let s=Pn(e.transforms),n=[],o=[];for(let i of s){let a=this.createBlockStorage(i),c=Wl(e.transforms,i),l=await na(a.listPendingTransactions());if(n.push(...l.map(u=>({blockId:i,actionId:u}))),e.rev!==void 0||c.insert){let u=await a.getLatest();if(u&&u.rev>=(e.rev??0)){let h=await na(a.listRevisions(e.rev??0,u.rev));for(let d of h){let f=await a.getTransaction(d.actionId);if(!f)throw new Error(`Missing action ${d.actionId} for block ${i}`);o.push({actionId:d.actionId,rev:d.rev,transforms:_p(f,i)})}}}}if(o.length)return{success:!1,missing:o};if(n.length>0){if(e.policy==="f")return{success:!1,pending:n};if(e.policy==="r")return{success:!1,pending:await Promise.all(n.map(async i=>{let a=this.createBlockStorage(i.blockId);return{blockId:i.blockId,actionId:i.actionId,transform:await a.getPendingTransaction(i.actionId)??await a.getTransaction(i.actionId)}}))}}return await Promise.all(s.map(i=>{let a=this.createBlockStorage(i),c=Wl(e.transforms,i);return a.savePendingTransaction(e.actionId,c)})),{success:!0,pending:n,blockIds:s}}async cancel(e,t){await Promise.all(e.blockIds.map(s=>this.createBlockStorage(s).deletePendingTransaction(e.actionId)))}async commit(e,t){let s=Array.from(new Set(e.blockIds)).sort(),n=[];try{for(let c of s){let l=`StorageRepo.commit:${c}`,u=await kn.acquire(l);n.push(u)}let o=e.blockIds.map(c=>({blockId:c,storage:this.createBlockStorage(c)})),i=[];for(let{blockId:c,storage:l}of o){let u=await l.getLatest();if(u&&u.rev>=e.rev){let h=[];for await(let d of l.listRevisions(e.rev,u.rev)){let f=await l.getTransaction(d.actionId);if(!f)throw new Error(`Missing action ${d.actionId} for block ${c}`);h.push({actionId:d.actionId,rev:d.rev,transform:f})}i.push({blockId:c,transforms:h})}}if(i.length)return{success:!1,missing:B_(i)};let a=[];for(let{blockId:c,storage:l}of o)await l.getPendingTransaction(e.actionId)||a.push({blockId:c,actionId:e.actionId});if(a.length)throw new Error(`Pending action ${e.actionId} not found for block(s): ${a.map(c=>c.blockId).join(", ")}`);for(let{blockId:c,storage:l}of o)try{await this.internalCommit(c,e.actionId,e.rev,l)}catch(u){return{success:!1,reason:u instanceof Error?u.message:"Unknown error during commit"}}}finally{n.reverse().forEach(o=>o())}return{success:!0}}async internalCommit(e,t,s,n){let o=await n.getPendingTransaction(t);if(!o)throw new Error(`Consistency Error: Pending action ${t} disappeared for block ${e} within critical section.`);let i=await n.getLatest(),a=i?(await n.getBlock(i.rev))?.block:void 0,c=Na(a,o);c&&await n.saveMaterializedBlock(t,c),await n.saveRevision(s,t),await n.promotePendingTransaction(t),await n.setLatest({actionId:t,rev:s})}};function B_(r){let e=r.flatMap(({blockId:s,transforms:n})=>n.map(o=>({blockId:s,transform:o}))),t=Qp(e,({transform:s})=>s.actionId);return Object.entries(t).map(([s,n])=>n.reduce((o,{blockId:i,transform:a})=>(Ap(o.transforms,i,a.transform),o),{actionId:s,rev:n[0].transform.rev,transforms:Ip()}))}var Xr=class{entries;constructor(e){this.entries=e}},Va=class{partitions;nodes;constructor(e,t){this.partitions=e,this.nodes=t}};var bs=class r{node;index;constructor(e,t){this.node=e,this.index=t}clone(){return new r(this.node,this.index)}},li=class r{branches;leafNode;leafIndex;on;version;constructor(e,t,s,n,o){this.branches=e,this.leafNode=t,this.leafIndex=s,this.on=n,this.version=o}isEqual(e){return this.leafNode===e.leafNode&&this.leafIndex===e.leafIndex&&this.on===e.on&&this.version===e.version}clone(){return new r(this.branches.map(e=>e.clone()),this.leafNode,this.leafIndex,this.on,this.version)}};var ur=64,iu=class{keyFromEntry;compare;_root;_version=0;constructor(e=s=>s,t=(s,n)=>s<n?-1:s>n?1:0){this.keyFromEntry=e,this.compare=t,this._root=new Xr([])}first(){return this.getFirst(this._root)}last(){return this.getLast(this._root)}find(e){return this.getPath(this._root,e)}get(e){return this.at(this.find(e))}at(e){return this.validatePath(e),e.on?e.leafNode.entries[e.leafIndex]:void 0}*range(e){let t=e.first?this.findFirst(e):e.isAscending?this.first():this.last(),s=e.last?this.findLast(e):e.isAscending?this.last():this.first(),n=this.keyFromEntry(s.leafNode.entries[s.leafIndex]),o=e.isAscending?this.internalAscending(t):this.internalDescending(t),i=e.isAscending?1:-1;for(let a of o){if(!a.on||!s.on||this.compareKeys(this.keyFromEntry(a.leafNode.entries[a.leafIndex]),n)*i>0)break;yield a}}isValid(e){return e.version===this._version}insert(e){Object.freeze(e);let t=this.internalInsert(e);return t.on&&(t.version=++this._version),t}updateAt(e,t){this.validatePath(e),e.on&&Object.freeze(t);let s=this.internalUpdate(e,t);return s[0].on&&(s[0].version=++this._version),s}upsert(e){let t=this.find(this.keyFromEntry(e));return Object.freeze(e),t.on?t.leafNode.entries[t.leafIndex]=e:this.internalInsertAt(t,e),t.version=++this._version,t}merge(e,t){let s=this.keyFromEntry(e),n=this.find(s);if(n.on){let o=this.updateAt(n,t(n.leafNode.entries[n.leafIndex]));return o[0].on&&(o[0].version=++this._version),o}else return this.internalInsertAt(n,Object.freeze(e)),n.on=!0,n.version=++this._version,[n,!1]}deleteAt(e){this.validatePath(e);let t=this.internalDelete(e);return t&&++this._version,t}ascending(e){return this.validatePath(e),this.internalAscending(e.clone())}descending(e){return this.validatePath(e),this.internalDescending(e.clone())}getCount(e){let t=0,s=e?e.path.clone():this.first();if(e?.ascending??!0)for(;s.on;)t+=s.leafNode.entries.length-s.leafIndex,s.leafIndex=s.leafNode.entries.length-1,this.internalNext(s);else for(;s.on;)t+=s.leafIndex+1,s.leafIndex=0,this.internalPrior(s);return t}next(e){let t=e.clone();return this.moveNext(t),t}moveNext(e){this.validatePath(e),this.internalNext(e)}prior(e){let t=e.clone();return this.movePrior(t),t}movePrior(e){this.validatePath(e),this.internalPrior(e)}compareKeys(e,t){let s=this.compare(e,t);if(s!==0&&s===this.compare(t,e))throw new Error("Inconsistent comparison function for given values");return s}*internalAscending(e){for(this.validatePath(e);e.on;)yield e,this.moveNext(e)}*internalDescending(e){for(this.validatePath(e);e.on;)yield e,this.movePrior(e)}findFirst(e){let t=this.find(e.first.key);return(!t.on||e.first&&!e.first.inclusive)&&(e.isAscending?this.internalNext(t):this.internalPrior(t)),t}findLast(e){let t=this.find(e.last.key);return(!t.on||e.last&&!e.last.inclusive)&&(e.isAscending?this.internalPrior(t):this.internalNext(t)),t}getPath(e,t){if(e instanceof Xr){let s=e,[n,o]=this.indexOfEntry(s.entries,t);return new li([],s,o,n,this._version)}else{let s=e,n=this.indexOfKey(s.partitions,t),o=this.getPath(s.nodes[n],t);return o.branches.unshift(new bs(s,n)),o}}indexOfEntry(e,t){let s=0,n=e.length-1,o=0,i=-1;for(;s<=n;){if(o=s+n>>>1,i=this.compareKeys(t,this.keyFromEntry(e[o])),i===0)return[!0,o];i<0?n=o-1:s=o+1}return[!1,s]}indexOfKey(e,t){let s=0,n=e.length-1,o=0,i=-1;for(;s<=n;){if(o=s+n>>>1,i=this.compareKeys(t,e[o]),i===0)return o+1;i<0?n=o-1:s=o+1}return s}internalNext(e){if(e.on)if(e.leafIndex>=e.leafNode.entries.length-1){let t=0,s=!1,n=e.branches.length-1;for(;t<=n&&!s;){let o=e.branches[n-t];o.index===o.node.partitions.length?++t:s=!0}if(!s)e.leafIndex=e.leafNode.entries.length,e.on=!1;else{e.branches.splice(-t,t);let o=e.branches.at(-1);++o.index,this.moveToFirst(o.node.nodes[o.index],e)}}else++e.leafIndex,e.on=!0;else if(e.on=e.branches.every(t=>t.index>=0&&t.index<t.node.nodes.length)&&e.leafIndex>=0&&e.leafIndex<e.leafNode.entries.length,e.on)return}internalPrior(e){if(this.validatePath(e),e.leafIndex<=0){let t=0,s=!1,n=e.branches.length-1;for(;t<=n&&!s;)e.branches[n-t].index===0?++t:s=!0;if(!s)e.leafIndex=0,e.on=!1;else{e.branches.splice(-t,t);let o=e.branches.at(-1);--o.index,this.moveToLast(o.node.nodes[o.index],e)}}else--e.leafIndex,e.on=!0}internalUpdate(e,t){if(e.on){let s=this.keyFromEntry(e.leafNode.entries[e.leafIndex]),n=this.keyFromEntry(t);if(this.compareKeys(s,n)!==0){let o=this.internalInsert(t);return o.on&&(this.internalDelete(this.find(s)),o=this.find(n)),[o,!1]}else e.leafNode.entries[e.leafIndex]=t}return[e,!0]}internalDelete(e){if(e.on){if(e.leafNode.entries.splice(e.leafIndex,1),e.branches.length>0){if(e.leafIndex===0){let s=e.branches.at(-1);this.updatePartition(s.index,e,e.branches.length-1,this.keyFromEntry(e.leafNode.entries[e.leafIndex]))}let t=this.rebalanceLeaf(e);t&&(this._root=t)}return e.on=!1,!0}else return!1}internalInsert(e){let t=this.find(this.keyFromEntry(e));return t.on?(t.on=!1,t):(this.internalInsertAt(t,e),t.on=!0,t)}internalInsertAt(e,t){let s=this.leafInsert(e,t),n=e.branches.length-1;for(;s&&n>=0;)s=this.branchInsert(e,n,s),--n;if(s){let o=new Va([s.key],[this._root,s.right]);this._root=o,e.branches.unshift(new bs(o,s.indexDelta))}}moveToFirst(e,t){if(e instanceof Xr){let s=e;t.leafNode=s,t.leafIndex=0,t.on=s.entries.length>0}else t.branches.push(new bs(e,0)),this.moveToFirst(e.nodes[0],t)}moveToLast(e,t){if(e instanceof Xr){let s=e,n=s.entries.length;t.leafNode=s,t.on=n>0,t.leafIndex=n>0?n-1:0}else{let s=e,n=new bs(s,s.partitions.length);t.branches.push(n),this.moveToLast(s.nodes[n.index],t)}}getFirst(e){if(e instanceof Xr){let t=e;return new li([],t,0,t.entries.length>0,this._version)}else{let t=e,s=this.getFirst(t.nodes[0]);return s.branches.unshift(new bs(t,0)),s}}getLast(e){if(e instanceof Xr){let t=e,s=t.entries.length;return new li([],t,s>0?s-1:0,s>0,this._version)}else{let t=e,s=t.nodes.length-1,n=this.getLast(t.nodes[s]);return n.branches.unshift(new bs(t,s)),n}}leafInsert(e,t){let{leafNode:s,leafIndex:n}=e;if(s.entries.length<ur){s.entries.splice(n,0,t);return}let o=s.entries.length+1>>>1,i=s.entries.splice(o),a=new Xr(i),c=n<o?0:1;return c?(e.leafNode=a,e.leafIndex-=s.entries.length,a.entries.splice(e.leafIndex,0,t)):s.entries.splice(n,0,t),new au(this.keyFromEntry(i[0]),a,c)}branchInsert(e,t,s){let n=e.branches[t],{index:o,node:i}=n;if(n.index+=s.indexDelta,i.partitions.splice(o,0,s.key),i.nodes.splice(o+1,0,s.right),i.nodes.length<=ur)return;let a=i.nodes.length>>>1,c=i.partitions.splice(a),l=i.partitions.pop(),u=i.nodes.splice(a),h=new Va(c,u),d=n.index<a?0:1;return d&&(n.index-=a,n.node=h),new au(l,h,d)}rebalanceLeaf(e){if(e.leafNode.entries.length>=ur>>>1)return;let t=e.leafNode,s=e.branches.at(-1),n=e.branches.length-1,o=s.index,i=s.node,a=i.nodes[o+1];if(a&&a.entries.length>ur>>>1){let l=a.entries.shift();t.entries.push(l),this.updatePartition(o+1,e,n,this.keyFromEntry(a.entries[0]));return}let c=i.nodes[o-1];if(c&&c.entries.length>ur>>>1){let l=c.entries.pop();t.entries.unshift(l),this.updatePartition(o,e,n,this.keyFromEntry(l)),e.leafIndex+=1;return}if(a&&a.entries.length+t.entries.length<=ur)return t.entries.push(...a.entries),i.partitions.splice(o,1),i.nodes.splice(o+1,1),o===0&&this.updatePartition(o,e,n,this.keyFromEntry(t.entries[0])),this.rebalanceBranch(e,n);if(c&&c.entries.length+t.entries.length<=ur)return e.leafNode=c,e.leafIndex+=c.entries.length,c.entries.push(...t.entries),i.partitions.splice(o-1,1),i.nodes.splice(o,1),this.rebalanceBranch(e,n)}rebalanceBranch(e,t){let s=e.branches[t],n=s.node;if(t===0&&n.partitions.length===0)return e.branches[t+1]?.node??e.leafNode;if(t===0||n.nodes.length>=ur<<1)return;let o=e.branches.at(t-1),i=o.index,a=o.node,c=a.nodes[i+1];if(c&&c.nodes.length>ur>>>1){n.partitions.push(a.partitions[i]);let u=c.nodes.shift();n.nodes.push(u);let h=c.partitions.shift();this.updatePartition(i+1,e,t-1,h);return}let l=a.nodes[i-1];if(l&&l.nodes.length>ur>>>1){n.partitions.unshift(a.partitions[i-1]);let u=l.nodes.pop();n.nodes.unshift(u);let h=l.partitions.pop();s.index+=1,this.updatePartition(i,e,t-1,h);return}if(c&&c.nodes.length+n.nodes.length<=ur){let u=a.partitions.splice(i,1)[0];return n.partitions.push(u),n.partitions.push(...c.partitions),n.nodes.push(...c.nodes),a.nodes.splice(i+1,1),i===0&&a.partitions.length>0&&this.updatePartition(i,e,t-1,a.partitions[0]),this.rebalanceBranch(e,t-1)}if(l&&l.nodes.length+n.nodes.length<=ur){s.node=l,s.index+=l.nodes.length;let u=a.partitions.splice(i-1,1)[0];return l.partitions.push(u),l.partitions.push(...n.partitions),l.nodes.push(...n.nodes),a.nodes.splice(i,1),this.rebalanceBranch(e,t-1)}}updatePartition(e,t,s,n){let o=t.branches[s];e>0?o.node.partitions[e-1]=n:s!==0&&this.updatePartition(t.branches[s-1].index,t,s-1,n)}validatePath(e){if(!this.isValid(e))throw new Error("Path is invalid due to mutation of the tree")}},au=class{key;right;indexDelta;constructor(e,t,s){this.key=e,this.right=t,this.indexDelta=s}};function Wa(r){let e="";for(let t=0;t<r.length;t++)e+=r[t].toString(16).padStart(2,"0");return e}function cu(r){return`${Wa(r.coord)}|${r.id}`}var lu=class{byKey;byId;constructor(){this.byKey=new iu(e=>cu(e)),this.byId=new Map}insert(e){let t=cu(e);this.byKey.insert(e),this.byId.set(e.id,t)}upsert(e,t){let s=Date.now(),n=this.byId.get(e);if(n){let i=this.byKey.find(n);i.on&&this.byKey.deleteAt(i),this.byId.delete(e)}let o={id:e,coord:t,relevance:0,lastAccess:s,state:"disconnected",accessCount:0,successCount:0,failureCount:0,avgLatencyMs:0};return this.insert(o),o}update(e,t){let s=this.byId.get(e);if(!s)return;let n=this.byKey.find(s),o=this.byKey.at(n);if(!o)return;let i={...o,...t};this.byKey.updateAt(n,i),cu(o)!==cu(i)&&(this.byKey.deleteAt(n),this.insert(i))}getById(e){let t=this.byId.get(e);if(!t)return;let s=this.byKey.find(t);return s.on?this.byKey.at(s):void 0}remove(e){let t=this.byId.get(e);if(!t)return;let s=this.byKey.find(t);s.on&&this.byKey.deleteAt(s),this.byId.delete(e)}list(){let e=[];for(let t of this.byKey.ascending(this.byKey.first()))e.push(this.byKey.at(t));return e}size(){return this.byId.size}setState(e,t){this.update(e,{state:t})}protectedIdsAround(e,t){let s=new Set;for(let n of this.neighborsRight(e,t))s.add(n);for(let n of this.neighborsLeft(e,t))s.add(n);return s}ceilPath(e){let t=`${e}|\0`,s=this.byKey.find(t);return s.on||(s=this.byKey.next(s)),s}floorPath(e){let t=`${e}|\uFFFF`,s=this.byKey.find(t);return s.on||(s=this.byKey.prior(s)),s}successorOfCoord(e){let t=Wa(e),s=this.ceilPath(t);if(s.on)return this.byKey.at(s);let n=this.byKey.first();return n.on?this.byKey.at(n):void 0}predecessorOfCoord(e){let t=Wa(e),s=this.floorPath(t);if(s.on)return this.byKey.at(s);let n=this.byKey.last();return n.on?this.byKey.at(n):void 0}neighborsRight(e,t){let s=[],n=Wa(e),o=this.ceilPath(n);o=o.on?o:this.byKey.first();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.first(),!o.on));)s.push(this.byKey.at(o).id),o=this.byKey.next(o),i++;return Array.from(new Set(s))}neighborsLeft(e,t){let s=[],n=Wa(e),o=this.floorPath(n);o=o.on?o:this.byKey.last();let i=0;for(;i<t&&!(!o.on&&(o=this.byKey.last(),!o.on));)s.push(this.byKey.at(o).id),o=this.byKey.prior(o),i++;return Array.from(new Set(s))}};us();Se();ge();async function Be(r){let e=r.toMultihash().bytes;return await Qe.encode(e)}async function Xt(r){return await Qe.encode(r)}function D5(r){return K(r,"base64url")}function M5(r="default"){let e=`/optimystic/${r}/fret/1.0.0`;return{PROTOCOL_NEIGHBORS:`${e}/neighbors`,PROTOCOL_NEIGHBORS_ANNOUNCE:`${e}/neighbors/announce`,PROTOCOL_MAYBE_ACT:`${e}/maybeAct`,PROTOCOL_LEAVE:`${e}/leave`,PROTOCOL_PING:`${e}/ping`}}var l0="/optimystic/default/fret/1.0.0/neighbors",u0="/optimystic/default/fret/1.0.0/neighbors/announce",h0="/optimystic/default/fret/1.0.0/maybeAct",d0="/optimystic/default/fret/1.0.0/leave",f0="/optimystic/default/fret/1.0.0/ping";async function hr(r){let e=JSON.stringify(r);return new TextEncoder().encode(e)}async function Zr(r){if(r.byteLength===0)throw new Error("empty response");let e=0,t=r.byteLength;for(;e<t&&(r[e]===0||r[e]===9||r[e]===10||r[e]===13||r[e]===32);)e++;for(;t>e&&(r[t-1]===0||r[t-1]===9||r[t-1]===10||r[t-1]===13||r[t-1]===32);)t--;if(t<=e)throw new Error("whitespace response");let s=new TextDecoder().decode(r.subarray(e,t));return JSON.parse(s)}ce();var O5=we(s0(),1),F_="optimystic:fret";function Zs(r){return(0,O5.default)(`${F_}:${r}`)}var p0=Zs("rpc:neighbors");function L5(r,e,t,s={PROTOCOL_NEIGHBORS:l0,PROTOCOL_NEIGHBORS_ANNOUNCE:u0}){r.handle(s.PROTOCOL_NEIGHBORS,async({stream:n})=>{try{let o=await e();await n.sink((async function*(){yield await hr(o)})());try{n.close?.()}catch{}}catch(o){console.error("neighbors handler error:",o)}}),t&&r.handle(s.PROTOCOL_NEIGHBORS_ANNOUNCE,async({stream:n})=>{try{let o=await N5(n),i=await Zr(o);t(i.from,i),await n.sink((async function*(){yield await hr({ok:!0})})());try{n.close?.()}catch{}}catch(o){console.error("neighbors announce handler error:",o)}})}async function R5(r,e,t=l0){let s=$(e),n=r.getConnections?.(s)??[];if(!Array.isArray(n)||n.length===0||typeof n[0]?.newStream!="function")return{v:1,from:e,timestamp:Date.now(),successors:[],predecessors:[],sig:""};let o;try{o=await n[0].newStream([t]);let i=await N5(o);return await Zr(i)}catch(i){return p0("fetchNeighbors decode failed for %s - %o",e,i),{v:1,from:e,timestamp:Date.now(),successors:[],predecessors:[],sig:""}}finally{if(o)try{await o.close()}catch{}}}async function m0(r,e,t,s=u0){let n=$(e),o=r.getConnections?.(n)??[];if(!Array.isArray(o)||o.length===0||typeof o[0]?.newStream!="function")return;let i;try{i=await o[0].newStream([s]),await i.sink((async function*(){yield await hr(t)})())}catch(a){p0("announceNeighbors failed to %s - %o",e,a)}finally{if(i)try{await i.close()}catch{}}}function U_(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")try{return e.subarray(0)}catch(t){p0("toBytes subarray failed - %o",t)}if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unsupported chunk type in neighbors read")}async function N5(r){let e=[];for await(let o of r.source)e.push(U_(o));let t=0;for(let o of e)t+=o.length;let s=new Uint8Array(t),n=0;for(let o of e)s.set(o,n),n+=o.length;return s}ce();function B5(r,e,t=h0){r.handle(t,async({stream:s})=>{try{let n=await U5(s),o=await Zr(n),i=await e(o);await s.sink((async function*(){yield await hr(i)})())}catch(n){console.error("maybeAct handler error:",n)}})}async function F5(r,e,t,s=h0){let n=$(e),o=r.getConnections?.(n)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([s]):i=await r.dialProtocol(n,[s]),await i.sink((async function*(){yield await hr(t)})());let a=await U5(i);return await Zr(a)}finally{if(i)try{await i.close()}catch{}}}function K_(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")return e.subarray(0);throw new Error("Unsupported chunk type in maybeAct read")}async function U5(r){let e=[];for await(let o of r.source)e.push(K_(o));let t=0;for(let o of e)t+=o.length;let s=new Uint8Array(t),n=0;for(let o of e)s.set(o,n),n+=o.length;return s}ce();function K5(r,e,t=d0){r.handle(t,async({stream:s})=>{try{let n=await z_(s),o=await Zr(n);await e(o),await s.sink((async function*(){yield await hr({ok:!0})})())}catch(n){console.error("leave handler error:",n)}})}async function H5(r,e,t,s=d0){let n=$(e),o=r.getConnections?.(n)??[],i;try{Array.isArray(o)&&o.length>0&&typeof o[0]?.newStream=="function"?i=await o[0].newStream([s]):i=await r.dialProtocol(n,[s]),await i.sink((async function*(){yield await hr(t)})())}finally{if(i)try{await i.close()}catch{}}}function H_(r){if(r instanceof Uint8Array)return r;let e=r;if(typeof e?.subarray=="function")return e.subarray(0);throw new Error("Unsupported chunk type in leave read")}async function z_(r){let e=[];for await(let o of r.source)e.push(H_(o));let t=0;for(let o of e)t+=o.length;let s=new Uint8Array(t),n=0;for(let o of e)s.set(o,n),n+=o.length;return s}ce();var g0=Zs("rpc:ping");function z5(r,e=f0,t){r.handle(e,async({stream:s})=>{let n={ok:!0,ts:Date.now()};if(t)try{let o=await t();o.size_estimate!==void 0&&(n.size_estimate=o.size_estimate,n.confidence=o.confidence)}catch(o){g0("getSizeEstimate failed - %o",o)}await s.sink((async function*(){yield await hr(n)})())})}async function ja(r,e,t=f0){let s=Date.now(),n=$(e),o;try{try{let l=r.getConnections?.(n)??[];if(Array.isArray(l)&&l.length>0&&typeof l[0]?.newStream=="function")o=await l[0].newStream([t]);else{let u=await r.dialProtocol(n,[t]);o=u.stream??u}}catch{let u=await r.dialProtocol(n,[t]);o=u.stream??u}let i=null;for await(let l of o.source)if(l!=null)try{if(l instanceof Uint8Array){i=l;break}if(typeof l.subarray=="function"){let u=l.subarray();if(u instanceof Uint8Array){i=u;break}if(ArrayBuffer.isView(u)){i=new Uint8Array(u.buffer,u.byteOffset,u.byteLength);break}}if(ArrayBuffer.isView(l)){i=new Uint8Array(l.buffer,l.byteOffset,l.byteLength);break}}catch(u){g0("sendPing chunk handling failed - %o",u)}let a=Math.max(0,Date.now()-s);if(!i||i.length===0)return{ok:!1,rttMs:a};let c=new TextDecoder().decode(i).trim();if(!c||c[0]!=="{"||!c.endsWith("}"))return{ok:!1,rttMs:a};try{let l=await Zr(i);return{ok:!!l.ok,rttMs:a,size_estimate:l.size_estimate,confidence:l.confidence}}catch(l){return g0("sendPing decode failed - %o",l),{ok:!1,rttMs:a}}}finally{if(o)try{await o.close()}catch{}}}ge();function q_(r){let e=0n;for(let t=0;t<r.length;t++)e=e<<8n|BigInt(r[t]);return e}function $_(r){if(r.length===0)return 0n;let e=[...r].sort((s,n)=>s<n?-1:s>n?1:0),t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2n:e[t]}function uu(r,e){let t=r.list(),s=t.length;if(s===0)return{n:0,confidence:0};if(s===1)return{n:1,confidence:.2};let n=1n<<256n,o=t.map(g=>q_(g.coord)).sort((g,y)=>g<y?-1:g>y?1:0),i=[];for(let g=1;g<o.length;g++)i.push(o[g]-o[g-1]);i.push(o[0]+n-o[o.length-1]);let a=$_(i),c=a>0n?a:n/BigInt(Math.max(1,s)),l=n/c,u=Math.max(1,Math.min(Number(l),1e9)),h=i[0],d=i[0];for(let g of i)g<h&&(h=g),g>d&&(d=g);let f=Math.min(1,s/Math.max(1,e*2)),p=d===0n?0:Number(h)/Number(d),m=Math.max(.05,Math.min(1,.5*f+.5*p));return{n:u,confidence:m}}var ui=class{capacity;refillPerSec;tokens;last;constructor(e,t){this.capacity=e,this.refillPerSec=t,this.tokens=e,this.last=Date.now()}tryTake(e=1){return this.refill(),this.tokens>=e?(this.tokens-=e,!0):!1}retryAfterMs(e=1){if(this.refill(),this.tokens>=e)return 0;let s=(e-this.tokens)/this.refillPerSec;return Math.ceil(s*1e3)}refill(){let e=Date.now(),t=(e-this.last)/1e3;t>0&&(this.tokens=Math.min(this.capacity,this.tokens+t*this.refillPerSec),this.last=e)}};ce();Se();var pt=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ws=class extends Error{static name="ValidationError";name="ValidationError"},Ya=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},hu=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};Vt();zr();Kt();ge();Se();wr();Kr();ge();Se();var Fe=re("node:net");jd();cl();Ro();Yd();Kr();ge();Se();function b0(r){return e=>K(e,r)}function w0(r){return e=>L(e,r)}function hi(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ln(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function q5(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=L(e[0],"base32"),s=parseInt(e[1],10);if(s<1||s>65536)throw new Error("Port number is not in range(1, 65536)");let n=Ln(s);return Ye([t,n],t.length+n.length)}function $5(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=or.decode(`b${e[0]}`),s=parseInt(e[1],10);if(s<1||s>65536)throw new Error("Port number is not in range(1, 65536)");let n=Ln(s);return Ye([t,n],t.length+n.length)}function x0(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),s=K(e,"base32"),n=hi(t);return`${s}:${n}`}var v0=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,s)=>{let n=parseInt(t,10);if(isNaN(n)||n<0||n>255)throw new pt("Invalid byte value in IP address");e[s]=n}),e},G5=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),s;for(s=0;s<t.length;s++){let o=(0,Fe.isIPv4)(t[s]),i;o&&(i=v0(t[s]),t[s]=K(i.subarray(0,2),"base16")),i!=null&&++s<8&&t.splice(s,0,K(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(s=0;s<t.length&&t[s]!=="";s++);let o=[s,1];for(s=9-t.length;s>0;s--)o.push("0");t.splice.apply(t,o)}let n=new Uint8Array(e+16);for(s=0;s<t.length;s++){t[s]===""&&(t[s]="0");let o=parseInt(t[s],16);if(isNaN(o)||o<0||o>65535)throw new pt("Invalid byte value in IP address");n[e++]=o>>8&255,n[e++]=o&255}return n},V5=function(r){if(r.byteLength!==4)throw new pt("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},W5=function(r){if(r.byteLength!==16)throw new pt("IPv6 address was incorrect length");let e=[];for(let s=0;s<r.byteLength;s+=2){let n=r[s],o=r[s+1],i=`${n.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let s=new URL(`http://[${t}]`);return s.hostname.substring(1,s.hostname.length-1)}catch{throw new pt(`Invalid IPv6 address "${t}"`)}};function j5(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new pt(`Invalid IPv6 address "${r}"`)}}var y0=Object.values(ua).map(r=>r.decoder),G_=(function(){let r=y0[0].or(y0[1]);return y0.slice(2).forEach(e=>r=r.or(e)),r})();function Y5(r){return G_.decode(r)}function X5(r){return e=>r.encoder.encode(e)}function V_(r){if(parseInt(r).toString()!==r)throw new ws("Value must be an integer")}function W_(r){if(r<0)throw new ws("Value must be a positive integer, or zero")}function j_(r){return e=>{if(e>r)throw new ws(`Value must be smaller than or equal to ${r}`)}}function Y_(...r){return e=>{for(let t of r)t(e)}}var Xa=Y_(V_,W_,j_(65535));var ct=-1,E0=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new hu(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(s=>{this.protocolsByName.delete(s)}))}},Rt=new E0,uA=[{code:4,name:"ip4",size:32,valueToBytes:v0,bytesToValue:V5,validate:r=>{if(!(0,Fe.isIPv4)(r))throw new ws(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ln,bytesToValue:hi,validate:Xa},{code:273,name:"udp",size:16,valueToBytes:Ln,bytesToValue:hi,validate:Xa},{code:33,name:"dccp",size:16,valueToBytes:Ln,bytesToValue:hi,validate:Xa},{code:41,name:"ip6",size:128,valueToBytes:G5,bytesToValue:W5,stringToValue:j5,validate:r=>{if(!(0,Fe.isIPv6)(r))throw new ws(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:ct},{code:43,name:"ipcidr",size:8,bytesToValue:b0("base10"),valueToBytes:w0("base10")},{code:53,name:"dns",size:ct,resolvable:!0},{code:54,name:"dns4",size:ct,resolvable:!0},{code:55,name:"dns6",size:ct,resolvable:!0},{code:56,name:"dnsaddr",size:ct,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Ln,bytesToValue:hi,validate:Xa},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ct,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:ct,bytesToValue:b0("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?w0("base58btc")(r):De.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:x0,valueToBytes:q5},{code:445,name:"onion3",size:296,bytesToValue:x0,valueToBytes:$5},{code:446,name:"garlic64",size:ct},{code:447,name:"garlic32",size:ct},{code:448,name:"tls"},{code:449,name:"sni",size:ct},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ct,bytesToValue:X5(Ud),valueToBytes:Y5},{code:480,name:"http"},{code:481,name:"http-path",size:ct,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ct}];uA.forEach(r=>{Rt.addProtocol(r)});function Z5(r){let e=[],t=0;for(;t<r.length;){let s=as(r,t),n=Rt.getProtocol(s),o=Le(s),i=hA(n,r,t+o),a=0;i>0&&n.size===ct&&(a=Le(i));let c=o+a+i,l={code:s,name:n.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+o+a,h=r.subarray(u,u+i);l.value=n.bytesToValue?.(h)??K(h)}e.push(l),t+=c}return e}function Q5(r){let e=0,t=[];for(let s of r){if(s.bytes==null){let n=Rt.getProtocol(s.code),o=Le(s.code),i,a=0,c=0;s.value!=null&&(i=n.valueToBytes?.(s.value)??L(s.value),a=i.byteLength,n.size===ct&&(c=Le(a)));let l=new Uint8Array(o+c+a),u=0;ko(s.code,l,u),u+=o,i!=null&&(n.size===ct&&(ko(a,l,u),u+=c),l.set(i,u)),s.bytes=l}t.push(s.bytes),e+=s.bytes.byteLength}return Ye(t,e)}function J5(r){if(r.charAt(0)!=="/")throw new pt('String multiaddr must start with "/"');let e=[],t="protocol",s="",n="";for(let o=1;o<r.length;o++){let i=r.charAt(o);i!=="/"&&(t==="protocol"?n+=r.charAt(o):s+=r.charAt(o));let a=o===r.length-1;if(i==="/"||a){let c=Rt.getProtocol(n);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),s="",n="",t="protocol";continue}else if(a)throw new pt(`Component ${n} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(s==="")throw new pt(`Component ${n} was missing value`);l.value=c.stringToValue?.(s)??s}e.push(l),s="",n="",t="protocol"}}}if(n!==""&&s!=="")throw new pt("Incomplete multiaddr");return e}function e4(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Rt.getProtocol(e.code);if(t==null)throw new pt(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function hA(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:as(e,t)}var dA=Symbol.for("nodejs.util.inspect.custom"),M0=Symbol.for("@multiformats/multiaddr"),fA=[53,54,55,56],D0=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}};function pA(r){if(r==null&&(r="/"),Js(r))return r.getComponents();if(r instanceof Uint8Array)return Z5(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),J5(r);if(Array.isArray(r))return r;throw new pt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var mu=class r{[M0]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=pA(e),t.validate!==!1&&mA(this)}get bytes(){return this.#r==null&&(this.#r=Q5(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=e4(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let e,t,s,n,o="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(o=`%${l??""}`),fA.includes(a)&&(t="tcp",n=443,s=`${l??""}${o}`,e=a===55?6:4),(a===6||a===273)&&(t=c==="tcp"?"tcp":"udp",n=parseInt(l??"")),(a===4||a===41)&&(t="tcp",s=`${l??""}${o}`,e=a===41?6:4);if(e==null||t==null||s==null||n==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:s,transport:t,port:n}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{let s=Rt.getProtocol(e);return{code:e,size:s.size??0,name:s.name,resolvable:!!s.resolvable,path:!!s.path}})}protoCodes(){return this.#e.map(({code:e})=>e)}protoNames(){return this.#e.map(({name:e})=>e)}tuples(){return this.#e.map(({code:e,value:t})=>{if(t==null)return[e];let s=Rt.getProtocol(e),n=[e];return t!=null&&n.push(s.valueToBytes?.(t)??L(t)),n})}stringTuples(){return this.#e.map(({code:e,value:t})=>t==null?[e]:[e,t])}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),s=this.toString(),n=s.lastIndexOf(t);if(n<0)throw new Ya(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(s.slice(0,n),{validate:!1})}decapsulateCode(e){let t;for(let s=this.#e.length-1;s>-1;s--)if(this.#e[s].code===e){t=s;break}return new r(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:s,value:n})=>{s===421&&e.push([s,n]),s===290&&(e=[])});let t=e.pop();if(t?.[1]!=null){let s=t[1];return s[0]==="Q"||s[0]==="1"?K(me.decode(`z${s}`),"base58btc"):K(De.parse(s).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let e of this.#e)if(Rt.getProtocol(e.code).path)return e.value??null;return null}equals(e){return ae(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let s=t4.get(t.name);if(s==null)throw new D0(`no available resolver for ${t.name}`);return(await s(this,e)).map(o=>G(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(this.#e.length!==2||this.#e[0].code!==4&&this.#e[0].code!==41||this.#e[1].code!==6&&this.#e[1].code!==273)}[dA](){return`Multiaddr(${this.toString()})`}};function mA(r){r.getComponents().forEach(e=>{let t=Rt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}var gu=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,s=e();return s===void 0&&(this.index=t),s}parseWith(e){let t=e();if(this.index===this.input.length)return t}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(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,s){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return s()})}readNumber(e,t,s,n){return this.readAtomically(()=>{let o=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*n)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let d=Number.parseInt(h,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(o*=e,o+=u,o>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!s&&c&&i>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let s=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(s===void 0)return;e[t]=s}return e})}readIPv6Addr(){let e=t=>{for(let s=0;s<t.length/2;s++){let n=s*2;if(s<t.length-3){let i=this.readSeparator(":",s,()=>this.readIPv4Addr());if(i!==void 0)return t[n]=i[0],t[n+1]=i[1],t[n+2]=i[2],t[n+3]=i[3],[n+4,!0]}let o=this.readSeparator(":",s,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[n,!1];t[n]=o>>8,t[n+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[s,n]=e(t);if(s===16)return t;if(n||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),i=16-(s+2),[a]=e(o.subarray(0,i));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var r4=45,gA=15,gi=new gu;function s4(r){if(!(r.length>gA))return gi.new(r).parseWith(()=>gi.readIPv4Addr())}function n4(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>r4))return gi.new(r).parseWith(()=>gi.readIPv6Addr())}function Qa(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>r4)return;let t=gi.new(r).parseWith(()=>gi.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function o4(r,e,t){let s=0;for(let n of r)if(!(s<e)){if(s>t)break;if(n!==255)return!1;s++}return!0}function i4(r,e,t,s){let n=0;for(let o of r)if(!(n<t)){if(n>s)break;if(o!==e[n])return!1;n++}return!0}function O0(r){switch(r.length){case Un:return r.join(".");case Kn:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function a4(r){let e=0;for(let[t,s]of r.entries()){if(s===255){e+=8;continue}for(;(s&128)!=0;)e++,s=s<<1;if((s&128)!=0)return-1;for(let n=t+1;n<r.length;n++)if(r[n]!=0)return-1;break}return e}function c4(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Un=4,Kn=16,Uz=parseInt("0xFFFF",16),yA=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Ja(r,e){e.length===Kn&&r.length===Un&&o4(e,0,11)&&(e=e.slice(12)),e.length===Un&&r.length===Kn&&i4(r,yA,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let s=new Uint8Array(t);for(let n=0;n<t;n++)s[n]=r[n]&e[n];return s}function l4(r,e){if(typeof e=="string"&&(e=Qa(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function L0(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let s=Un,n=s4(e);if(n==null&&(s=Kn,n=n4(e),n==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>s*8)throw new Error("Failed to parse given CIDR: "+r);let i=R0(o,8*s);return{network:Ja(n,i),mask:i}}function R0(r,e){if(e!==8*Un&&e!==8*Kn)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,s=new Uint8Array(t);for(let n=0;n<t;n++){if(r>=8){s[n]=255,r-=8;continue}s[n]=255-(255>>r),r=0}return s}var Hn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=L0(e));else{let s=Qa(e);if(s==null)throw new Error("Failed to parse network");t=String(t);let n=parseInt(t,10);if(Number.isNaN(n)||String(n).length!==t.length||n<0||n>s.length*8){let o=Qa(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=R0(n,8*s.length);this.network=Ja(s,this.mask)}}contains(e){return l4({network:this.network,mask:this.mask},e)}toString(){let e=a4(this.mask),t=e!==-1?String(e):c4(this.mask);return O0(this.network)+"/"+t}};function u4(r,e){return new Hn(r).contains(e)}ge();Se();function N0(r){let e,t;if(r.getComponents().forEach(s=>{(s.name==="ip4"||s.name==="ip6")&&(t=s.value),s.name==="ipcidr"&&(e=s.value)}),e==null||t==null)throw new Error("Invalid multiaddr");return new Hn(t,e)}function h4(r,e){return Rt.getProtocol(r).bytesToValue?.(e)??K(e,"base16")}var t4=new Map;function Js(r){return!!r?.[M0]}function G(r){return new mu(r)}function yi(r){let e=Rt.getProtocol(r);return{code:e.code,size:e.size??0,name:e.name,resolvable:!!e.resolvable,path:!!e.path}}function yu(r,e){let t=Math.max(r.length,e.length),s=new Uint8Array(t);for(let n=0;n<t;n++){let o=r[r.length-1-n]??0,i=e[e.length-1-n]??0;s[t-1-n]=o^i}return s}function B0(r,e){let t=Math.max(r.length,e.length);for(let s=0;s<t;s++){let n=r[s]??0,o=e[s]??0;if(n<o)return!0;if(n>o)return!1}return!1}function d4(r){for(let e=0;e<r.length;e++)if(r[e]!==0)return e;return Number.POSITIVE_INFINITY}function bA(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function f4(r,e,t,s){return B0(e,s)?!0:B0(s,e)?!1:r<t}function bu(r,e,t,s,n,o=1){let i,a=[];for(let u of t){let h=r.getById(u);if(!h)continue;let d=yu(h.coord,e),f=s(u),p=(f?1:0)+.25*n(u);a.push({id:u,dist:d,connected:f,score:p}),(!i||f4(u,d,i.id,i.dist))&&(i={id:u,dist:d})}if(!i)return;let c=d4(i.dist),l;for(let u of a){if(!u.connected)continue;if(d4(u.dist)<=c+o){if(!l){l={id:u.id,dist:u.dist,score:u.score};continue}f4(u.id,u.dist,l.id,l.dist)?l={id:u.id,dist:u.dist,score:u.score}:bA(u.dist,l.dist)&&(u.score>l.score||u.score===l.score&&u.id<l.id)&&(l={id:u.id,dist:u.dist,score:u.score})}}return l?.id??i.id}function p4(r=12,e=.08,t=.03,s=.6,n=.7,o=1.8,i=1e-6){let a=[];for(let c=0;c<r;c++)a.push((c+.5)/r);return{centers:a,occupancy:new Float64Array(r),alpha:t,sigma:e,beta:s,sMin:n,sMax:o,eps:i}}function wu(r,e){let t=yu(r,e),s=0;for(let o=0;o<t.length;o++){let i=t[o]??0;if(i===0){s+=8;continue}let a=7-Math.floor(Math.log2(i));s+=a;break}return 1-Math.min(256,s)/256}function m4(r,e){let t=r/Math.max(1e-9,e);return Math.exp(-.5*t*t)}function F0(r,e){for(let t=0;t<r.centers.length;t++){let s=m4(Math.abs(e-r.centers[t]),r.sigma);r.occupancy[t]=(1-r.alpha)*r.occupancy[t]+r.alpha*s}}function U0(r,e){let t=0,s=0;for(let i=0;i<r.centers.length;i++){let a=m4(Math.abs(e-r.centers[i]),r.sigma);t+=r.occupancy[i]*a,s+=1*a}let n=(s+r.eps)/(t+r.eps),o=Math.pow(n,r.beta);return Math.max(r.sMin,Math.min(r.sMax,o))}function wA(r,e){let t=Math.max(0,e-r.lastAccess),n=Math.log(2)/Math.max(1,6e4);return Math.exp(-n*t)}function xA(r){return Math.log1p(r.accessCount)/5}function vA(r){let e=r.successCount+r.failureCount,t=e>0?r.successCount/e:.5,s=r.avgLatencyMs>0?Math.min(1,r.avgLatencyMs/1e3):.5,n=.5*t+.5*(1-s);return Math.max(0,n)}function K0(r,e){return .4*wA(r,e)+.2*xA(r)+.4*vA(r)}function H0(r,e){return{...r,...e}}function g4(r,e,t,s=Date.now()){F0(t,e);let n=K0(r,s),o=U0(t,e),i=n*o;return H0(r,{lastAccess:s,relevance:i,accessCount:r.accessCount+1})}function y4(r,e,t,s,n=Date.now()){F0(s,t);let o=.2,i=r.avgLatencyMs>0?(1-o)*r.avgLatencyMs+o*e:e,a=K0({...r,avgLatencyMs:i,successCount:r.successCount+1},n),c=U0(s,t),l=a*c;return H0(r,{lastAccess:n,relevance:l,successCount:r.successCount+1,avgLatencyMs:i})}function b4(r,e,t,s=Date.now()){F0(t,e);let n=K0({...r,failureCount:r.failureCount+1},s)*.7,o=U0(t,e),i=n*o;return H0(r,{lastAccess:s,relevance:i,failureCount:r.failureCount+1})}var Dr=Zs("service:fret"),bi=class{mode="passive";store=new lu;cfg;node;stabilizing=!1;inflightAct=0;bucketNeighbors;bucketMaybeAct;bucketDiscovery;announcedIds=new Map;postBootstrapAnnounced=!1;sparsity=p4();cachedSelfCoord=null;preconnectRunning=!1;protocols;metadata;diag={peersDiscovered:0,snapshotsFetched:0,announcementsSent:0,pingsSent:0,pingsOk:0,pingsFail:0,maybeActForwarded:0,evictions:0};networkObservations=[];maxObservations=100;observationWindowMs=3e5;constructor(e,t){this.node=e,this.cfg={k:t?.k??15,m:t?.m??Math.ceil((t?.k??15)/2),capacity:t?.capacity??2048,profile:t?.profile??"core",bootstraps:t?.bootstraps??[],networkName:t?.networkName??"default"},this.protocols=M5(this.cfg.networkName),this.bucketDiscovery=new ui(this.cfg.profile==="core"?50:10,this.cfg.profile==="core"?25:3),this.bucketNeighbors=new ui(this.cfg.profile==="core"?20:8,this.cfg.profile==="core"?10:4),this.bucketMaybeAct=new ui(this.cfg.profile==="core"?32:8,this.cfg.profile==="core"?16:4)}getDiagnostics(){return this.diag}async selfCoord(){return this.cachedSelfCoord?this.cachedSelfCoord:(this.cachedSelfCoord=await Be(this.node.peerId),this.cachedSelfCoord)}enforceCapacity(){let e=Math.max(1,this.cfg.capacity);if(this.store.size()<=e)return;let t=this.cachedSelfCoord;if(!t)return;let s=this.store.protectedIdsAround(t,Math.max(2,this.cfg.m)),n=this.store.list();n.sort((o,i)=>o.relevance-i.relevance);for(let o of n){if(this.store.size()<=e)break;s.has(o.id)||this.store.remove(o.id)}}async applyTouch(e,t){let s=this.store.getById(e)??this.store.upsert(e,t),n=wu(await this.selfCoord(),t),o=g4(s,n,this.sparsity);this.store.update(e,{lastAccess:o.lastAccess,relevance:o.relevance,accessCount:o.accessCount})}async applySuccess(e,t,s){let n=this.store.getById(e)??this.store.upsert(e,t),o=wu(await this.selfCoord(),t),i=y4(n,s,o,this.sparsity);this.store.update(e,{lastAccess:i.lastAccess,relevance:i.relevance,successCount:i.successCount,avgLatencyMs:i.avgLatencyMs})}async applyFailure(e,t){let s=this.store.getById(e)??this.store.upsert(e,t),n=wu(await this.selfCoord(),t),o=b4(s,n,this.sparsity);this.store.update(e,{lastAccess:o.lastAccess,relevance:o.relevance,failureCount:o.failureCount})}async start(){await this.seedFromPeerStore(),this.registerRpcHandlers(),await this.proactiveAnnounceOnStart(),this.startStabilizationLoop(),this.mode==="active"&&this.preconnectNeighbors(),this.node.addEventListener("peer:connect",async e=>{if(!this.postBootstrapAnnounced){this.postBootstrapAnnounced=!0;try{await this.announceNeighborsBounded(8)}catch(t){Dr("postBootstrap announce failed - %o",t)}}}),this.node.addEventListener("peer:connect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let s=this.store.getById(t)?.coord??await Be($(t));this.store.setState(t,"connected"),await this.applyTouch(t,s)}catch(t){Dr("peer:connect handler failed - %o",t)}}),this.node.addEventListener("peer:disconnect",async e=>{try{let t=e?.detail?.id?.toString?.();if(!t)return;let s=this.store.getById(t)?.coord??await Be($(t));this.store.setState(t,"disconnected"),await this.applyFailure(t,s)}catch(t){Dr("peer:disconnect handler failed - %o",t)}})}async stop(){this.stabilizing=!1;try{await this.sendLeaveToNeighbors()}catch(e){console.warn("sendLeaveToNeighbors failed",e)}}setMode(e){this.mode=e,e==="active"&&!this.preconnectRunning&&this.startActivePreconnectLoop()}async ready(){}registerRpcHandlers(){L5(this.node,async()=>this.handleNeighborsRequest(),(e,t)=>{this.mergeAnnounceSnapshot(e,t)},this.protocols),B5(this.node,async e=>this.handleMaybeAct(e),this.protocols.PROTOCOL_MAYBE_ACT),K5(this.node,async e=>this.handleLeave(e.from),this.protocols.PROTOCOL_LEAVE),z5(this.node,this.protocols.PROTOCOL_PING,()=>this.getNetworkSizeEstimate())}async handleNeighborsRequest(){return this.bucketNeighbors.tryTake()?await this.snapshot():{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:[],predecessors:[],sig:""}}async handleMaybeAct(e){if(e.ttl<=0)return await this.nearAnchorOnly(e);if(e.activity&&e.activity.length>128*1024)return await this.nearAnchorOnly(e);if(!this.bucketMaybeAct.tryTake())return await this.nearAnchorOnly(e);let t=this.cfg.profile==="core"?16:4;if(this.inflightAct>=t)return this.nearAnchorOnly(e);this.inflightAct++;try{return await this.routeAct(e)}catch(s){return console.error("routeAct failed:",s),await this.nearAnchorOnly(e)}finally{this.inflightAct--}}isConnected(e){try{return this.node.getConnections($(e)).length>0}catch{return!1}}hasAddresses(e){try{let t=this.node.getMultiaddrsForPeer?.($(e))??[];return Array.isArray(t)&&t.length>0}catch{return!1}}async proactiveAnnounceOnStart(){try{await this.announceNeighborsBounded(8)}catch(e){console.warn("proactiveAnnounceOnStart failed",e)}}async announceNeighborsBounded(e){let t=await Be(this.node.peerId),s=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(t,"right",this.cfg.m),...this.getNeighbors(t,"left",this.cfg.m)])).filter(i=>i!==s).slice(0,e),o=await this.snapshot();for(let i of n)if(this.isConnected(i)||this.hasAddresses(i))try{await m0(this.node,i,o,this.protocols.PROTOCOL_NEIGHBORS_ANNOUNCE),this.diag.announcementsSent++}catch(a){console.warn("announce failed",i,a)}}async preconnectNeighbors(){try{let e=await Be(this.node.peerId),t=this.node.peerId.toString(),s=Array.from(new Set([...this.getNeighbors(e,"right",Math.min(6,this.cfg.m)),...this.getNeighbors(e,"left",Math.min(6,this.cfg.m))])).filter(n=>n!==t);for(let n of s)if(this.isConnected(n)||this.hasAddresses(n))try{await ja(this.node,n,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(o){Dr("preconnectNeighbors ping failed for %s - %o",n,o)}}catch(e){Dr("preconnectNeighbors outer failed - %o",e)}}startActivePreconnectLoop(){if(this.preconnectRunning)return;this.preconnectRunning=!0;let e=async()=>{if(!this.preconnectRunning||this.mode!=="active"){this.preconnectRunning=!1;return}try{let t=await this.selfCoord(),s=this.node.peerId.toString(),n=this.cfg.profile==="core"?6:3,o=Array.from(new Set([...this.getNeighbors(t,"right",Math.min(12,this.cfg.m)),...this.getNeighbors(t,"left",Math.min(12,this.cfg.m))])).filter(i=>i!==s).slice(0,n);for(let i of o)if(this.isConnected(i)||this.hasAddresses(i))try{await ja(this.node,i,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(a){Dr("active preconnect ping failed for %s - %o",i,a)}}catch(t){Dr("active preconnect tick failed - %o",t)}setTimeout(e,1e3)};e()}async sendLeaveToNeighbors(){try{let e=await Be(this.node.peerId),t=this.node.peerId.toString(),s=Array.from(new Set([...this.getNeighbors(e,"right",this.cfg.m),...this.getNeighbors(e,"left",this.cfg.m)])).filter(o=>o!==t).slice(0,8),n={v:1,from:this.node.peerId.toString(),timestamp:Date.now()};for(let o of s)try{await H5(this.node,o,n,this.protocols.PROTOCOL_LEAVE)}catch(i){Dr("sendLeave failed for %s - %o",o,i)}}catch(e){Dr("sendLeaveToNeighbors outer failed - %o",e)}}async handleLeave(e){try{let t=null,s=this.store.getById(e);if(s)t=s.coord;else try{t=await Be($(e))}catch(l){console.warn("handleLeave: could not hash departing peer id",e,l)}if(this.store.remove(e),t)try{await this.applyFailure(e,t)}catch{}if(!t)return;let n=Array.from(new Set([...this.store.neighborsRight(t,this.cfg.m),...this.store.neighborsLeft(t,this.cfg.m)])),o=this.expandCohort(n,t,Math.max(2,Math.ceil(this.cfg.m/2))),i=new Set(n),a=o.filter(l=>!i.has(l)),c=a.slice(0,Math.min(a.length,6));for(let l of c)try{if(await ja(this.node,l,this.protocols.PROTOCOL_PING),!this.isConnected(l)){let u=await this.snapshot();await m0(this.node,l,u,this.protocols.PROTOCOL_NEIGHBORS_ANNOUNCE)}}catch(u){console.warn("warm/announce failed for",l,u)}await this.mergeNeighborSnapshots(c.slice(0,4))}catch(t){console.error("handleLeave failed for",e,t)}}async mergeAnnounceSnapshot(e,t){try{let s=$(e),n=await Be(s),o=[];this.store.getById(e)||o.push(e),this.store.upsert(e,n),await this.applyTouch(e,n),t.metadata&&this.store.update(e,{metadata:t.metadata});for(let i of[...t.successors??[],...t.predecessors??[]])try{let a=await Be($(i));this.store.getById(i)||o.push(i),this.store.upsert(i,a),await this.applyTouch(i,a)}catch(a){console.warn("mergeAnnounceSnapshot: failed for",i,a)}for(let i of t.sample??[])try{let a=L(i.coord,"base64url");this.store.getById(i.id)||o.push(i.id),this.store.upsert(i.id,a),await this.applyTouch(i.id,a)}catch(a){Dr("mergeAnnounceSnapshot sample upsert failed for %s - %o",i.id,a)}this.enforceCapacity(),this.emitDiscovered(o)}catch(s){console.warn("mergeAnnounceSnapshot failed for",e,s)}}async seedFromPeerStore(){try{let e=this.node.peerStore?.getPeers?.()??[],t=[];for(let s of e)try{let n=await Be(s.id),o=s.id.toString();this.store.getById(o)||t.push(o),this.store.upsert(o,n)}catch(n){console.warn("failed to add peer from peerStore",s?.id?.toString?.(),n)}try{let s=await Be(this.node.peerId),n=this.node.peerId.toString();this.store.getById(n)||t.push(n),this.store.upsert(n,s)}catch(s){console.error("failed to add self to store",s)}this.enforceCapacity(),this.emitDiscovered(t)}catch(e){console.error("seedFromPeerStore failed:",e)}}startStabilizationLoop(){if(this.stabilizing)return;this.stabilizing=!0;let e=async()=>{if(this.stabilizing)try{await this.seedFromPeerStore(),await this.seedFromBootstraps(),await this.stabilizeOnce()}catch(t){console.error("stabilize tick failed:",t)}finally{let t=this.mode==="active"?300:1500;setTimeout(e,t)}};e()}async seedFromBootstraps(){if(!this.cfg.bootstraps||this.cfg.bootstraps.length===0)return;let e=[];for(let t of this.cfg.bootstraps.slice(0,8))try{let s=t;if(t.startsWith("/"))try{let a=G(t).getPeerId();a&&(s=a)}catch{}let n=$(s),o=await Be(n);this.store.getById(s)||e.push(s),this.store.upsert(s,o),await this.applyTouch(s,o)}catch(s){console.warn("seedFromBootstraps failed for",t,s)}this.enforceCapacity(),this.emitDiscovered(e)}async stabilizeOnce(){let e=await Be(this.node.peerId),t=this.node.peerId.toString(),n=this.getNeighbors(e,"both",Math.max(2,this.cfg.m)).filter(o=>o!==t&&(this.isConnected(o)||this.hasAddresses(o)));await this.probeNeighborsLatency(n.slice(0,4)),await this.mergeNeighborSnapshots(n.slice(0,4))}async probeNeighborsLatency(e){for(let t of e)try{let s=await ja(this.node,t,this.protocols.PROTOCOL_PING);if(this.diag.pingsSent++,s.ok){let n=this.store.getById(t)?.coord??await Be($(t));await this.applySuccess(t,n,s.rttMs),this.diag.pingsOk++}else{let n=this.store.getById(t)?.coord??await Be($(t));await this.applyFailure(t,n),this.diag.pingsFail++}}catch{try{let n=this.store.getById(t)?.coord??await Be($(t));await this.applyFailure(t,n),this.diag.pingsFail++}catch{}}}async mergeNeighborSnapshots(e){let t=[];for(let s of e)try{let n=await R5(this.node,s,this.protocols.PROTOCOL_NEIGHBORS);this.diag.snapshotsFetched++;let o=this.cfg.profile==="core"?16:8,i=this.cfg.profile==="core"?16:8,a=(n.successors??[]).slice(0,o),c=(n.predecessors??[]).slice(0,i);for(let u of[...a,...c])try{let h=await Be($(u));this.store.getById(u)||t.push(u),this.store.upsert(u,h),await this.applyTouch(u,h)}catch(h){console.warn("failed to merge neighbor",u,h)}let l=this.cfg.profile==="core"?8:6;for(let u of(n.sample??[]).slice(0,l))try{let h=L(u.coord,"base64url");this.store.getById(u.id)||t.push(u.id),this.store.upsert(u.id,h),await this.applyTouch(u.id,h)}catch(h){Dr("mergeNeighborSnapshots sample upsert failed for %s - %o",u.id,h)}}catch(n){console.warn("fetchNeighbors failed for",s,n)}this.enforceCapacity(),this.emitDiscovered(t)}async snapshot(){let e=await Be(this.node.peerId),{n:t,confidence:s}=uu(this.store,this.cfg.m),n=this.cfg.profile==="core"?12:6,o=this.cfg.profile==="core"?12:6,i=this.cfg.profile==="core"?8:6,a=this.getNeighbors(e,"right",this.cfg.m),c=this.getNeighbors(e,"left",this.cfg.m),l=a.slice(0,n),u=c.slice(0,o),h=Array.from(new Set([...l.slice(0,4),...u.slice(0,4)])).slice(0,i),d=await Promise.all(h.map(async f=>{let p=this.store.getById(f);return p?{id:f,coord:D5(p.coord),relevance:p.relevance}:{id:f,coord:"",relevance:0}}));return{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:l,predecessors:u,sample:d,size_estimate:t,confidence:s,sig:"",metadata:this.metadata}}neighborDistance(e,t,s){let n=new Set,o=Math.max(1,s),a=this.assembleCohort(t,o,n).findIndex(c=>c===e);return a>=0?a:Number.POSITIVE_INFINITY}getNeighbors(e,t,s){let n=[];return(t==="right"||t==="both")&&n.push(...this.store.neighborsRight(e,s)),(t==="left"||t==="both")&&n.push(...this.store.neighborsLeft(e,s)),Array.from(new Set(n)).slice(0,s)}nextSuccessor(e,t){let s=t.findIndex(n=>n.id===e.id);return t[(s+1)%t.length]}nextPredecessor(e,t){let s=t.findIndex(n=>n.id===e.id);return t[(s-1+t.length)%t.length]}assembleCohort(e,t,s){let n=[],o=s??new Set,i=this.store.neighborsRight(e,t*2),a=this.store.neighborsLeft(e,t*2),c=0,l=0;for(;n.length<t&&(c<i.length||l<a.length);)if(n.length%2===0){let u=i[c++];u&&!o.has(u)&&n.push(u)}else{let u=a[l++];u&&!o.has(u)&&n.push(u)}return Array.from(new Set(n)).slice(0,t)}expandCohort(e,t,s,n){let o=new Set(e),i=this.assembleCohort(t,e.length+s,n);for(let a of i)o.add(a);return Array.from(o)}async nearAnchorOnly(e){let t=L(e.key,"base64url"),s=await Xt(t),n=this.getNeighbors(s,"right",this.cfg.m),o=this.getNeighbors(s,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...n.slice(0,3),...o.slice(0,3)]),cohort_hint:Array.from(new Set([...n.slice(0,2),...o.slice(0,2)])),estimated_cluster_size:this.cfg.k,confidence:.5}}emitDiscovered(e){if(e.length===0)return;let t=Date.now(),s=this.cfg.profile==="core"?10*6e4:30*6e4,n=this.node,o=0;for(let i of Array.from(new Set(e)))if(!((this.announcedIds.get(i)??0)>t)){if(!this.bucketDiscovery.tryTake())break;try{let c=$(i);n.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:c,multiaddrs:[]}})),this.announcedIds.set(i,t+s),o++}catch(c){console.warn("emitDiscovered failed for",i,c)}}if(o>0&&this.announcedIds.size>4096)for(let[i,a]of this.announcedIds)a<=t&&this.announcedIds.delete(i)}pickAnchors(e){let t=Array.from(new Set(e));if(t.length===0)return[];let s=c=>.5,n=new Uint8Array(32),o=bu(this.store,n,t,c=>this.isConnected(c),s),i=t.filter(c=>c!==o),a=bu(this.store,n,i,c=>this.isConnected(c),s);return[o,a].filter(c=>!!c)}async routeAct(e){let t=L(e.key,"base64url"),s=await Xt(t),n=this.node.peerId.toString();if(this.neighborDistance(n,s,2)>1&&e.ttl>0){let h=new Set([...e.breadcrumbs??[],n]),d=this.assembleCohort(s,Math.max(4,this.cfg.m)).filter(m=>!h.has(m)),f=m=>.5,p=bu(this.store,s,d,m=>this.isConnected(m),f);if(p){let m={...e,ttl:e.ttl-1,breadcrumbs:[...e.breadcrumbs??[],n]};try{return await F5(this.node,p,m,this.protocols.PROTOCOL_MAYBE_ACT)}catch(g){console.warn("forward maybeAct failed to",p,g)}}}let{n:i,confidence:a}=uu(this.store,this.cfg.m),c=this.getNeighbors(s,"right",this.cfg.m),l=this.getNeighbors(s,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...c.slice(0,4),...l.slice(0,4)]),cohort_hint:Array.from(new Set([...c.slice(0,4),...l.slice(0,4)])),estimated_cluster_size:Math.max(this.cfg.k,i),confidence:a}}report(e){}reportNetworkSize(e,t,s="external"){let n=Date.now();this.networkObservations.push({estimate:e,confidence:t,timestamp:n,source:s});let o=n-this.observationWindowMs;this.networkObservations=this.networkObservations.filter(i=>i.timestamp>o),this.networkObservations.length>this.maxObservations&&(this.networkObservations=this.networkObservations.slice(-this.maxObservations))}getNetworkSizeEstimate(){let e=uu(this.store,this.cfg.m),t=Date.now(),s=[{estimate:e.n,confidence:e.confidence,timestamp:t,source:"fret"},...this.networkObservations];if(s.length===0)return{size_estimate:0,confidence:0,sources:0};let n=0,o=0,i=0;for(let l of s){let u=t-l.timestamp,h=Math.exp(-u/(this.observationWindowMs/3)),d=h*l.confidence;o+=l.estimate*d,i+=l.confidence*h,n+=d}if(n===0)return{size_estimate:0,confidence:0,sources:0};let a=Math.round(o/n),c=i/s.length;return{size_estimate:a,confidence:Math.min(1,c),sources:s.length}}getNetworkChurn(){if(this.networkObservations.length<2)return 0;let e=Date.now(),t=this.observationWindowMs/2,s=e-t,n=this.networkObservations.filter(l=>l.timestamp>s),o=this.networkObservations.filter(l=>l.timestamp<=s);if(n.length===0||o.length===0)return 0;let i=n.reduce((l,u)=>l+u.estimate,0)/n.length,a=o.reduce((l,u)=>l+u.estimate,0)/o.length;return(i-a)/t*6e4}detectPartition(){if(this.networkObservations.length<10)return!1;let e=this.getNetworkSizeEstimate();if(e.confidence<.3)return!1;let t=Date.now()-3e4,s=this.networkObservations.filter(c=>c.timestamp<t);if(s.length<3)return!1;let n=s.slice(-5).reduce((c,l)=>c+l.estimate,0)/Math.min(5,s.length);if(e.size_estimate/n<.5)return!0;let i=Math.abs(this.getNetworkChurn()),a=e.size_estimate*.1;return i>a}setMetadata(e){this.metadata=e}getMetadata(e){return this.store.getById(e)?.metadata}listPeers(){return this.store.list().map(e=>({id:e.id,metadata:e.metadata}))}};ce();var EA=Zs("service:discovery");function z0(r,e){let t=r;for(let s of e.list())try{let n=$(s.id);t.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:n,multiaddrs:[]}}))}catch(n){EA("seedDiscovery failed for %s - %o",s.id,n)}}var xu=class{components;cfg;inner=null;nodeRef=null;constructor(e,t){this.components=e,this.cfg=t}get[Symbol.toStringTag](){return"@optimystic/fret"}setLibp2p(e){this.nodeRef=e}ensure(){if(!this.inner){if(!this.nodeRef)throw new Error("Libp2pFretService: libp2p node not injected");this.inner=new bi(this.nodeRef,this.cfg)}return this.inner}async start(){if(this.ensure(),!this.nodeRef)throw new Error("Libp2pFretService.start: libp2p node not injected");z0(this.nodeRef,this.inner?.store??{}),await this.ensure().start()}async stop(){await this.inner?.stop()}async routeAct(e){return await this.ensure().routeAct(e)}getNeighborsForKey(e,t,s){return this.ensure().getNeighbors(e,t,s)}assembleCohortForKey(e,t){return this.ensure().assembleCohort(e,t)}getDiagnostics(){return this.ensure().getDiagnostics?.()}neighborDistance(e,t,s){return this.ensure().neighborDistance(e,t,s)}getNeighbors(e,t,s){return this.ensure().getNeighbors(e,t,s)}assembleCohort(e,t,s){return this.ensure().assembleCohort(e,t,s)}expandCohort(e,t,s,n){return this.ensure().expandCohort(e,t,s,n)}async ready(){await this.ensure().ready()}setMode(e){this.ensure().setMode(e)}setMetadata(e){this.ensure().setMetadata(e)}report(e){this.ensure().report(e)}getMetadata(e){return this.ensure().getMetadata(e)}listPeers(){return this.ensure().listPeers()}};function q0(r){return e=>new xu(e,r)}ce();var w4="/db-p2p/sync/",x4="1.0.0",ec=(r="")=>`${r}${w4}${x4}`;var tc=class extends cs{protocol;constructor(e,t,s=""){super(e,t),this.protocol=ec(s)}async requestBlock(e){return await this.processMessage(e,this.protocol)}getProtocol(){return this.protocol}};var rc=class{fretAdapter;peerNetwork;protocolPrefix;metrics={totalRequests:0,successByRing:new Map,failureByRing:new Map,averageDurationMs:0};constructor(e,t,s){this.fretAdapter=e,this.peerNetwork=t,this.protocolPrefix=s}log=lr("storage:restoration");async restore(e,t){let s=Date.now();this.metrics.totalRequests++;let n=await this.getMyRingPeers(e),o=this.getMyRingDepth();for(let a of n){let c=await this.queryPeer(a,e,t);if(c)return this.recordSuccess(o,e,Date.now()-s),c}for(let a=o-1;a>=0;a--){let c=this.fretAdapter.findPeersAtRing(a),l=this.filterByPartition(c,e,a);for(let u of l){let h=await this.queryPeer(u,e,t);if(h)return this.recordSuccess(a,e,Date.now()-s),h}}let i=Date.now()-s;this.log("restore failed for block %s after %dms",e,i)}createRestoreCallback(){return async(e,t)=>await this.restore(e,t)}async getMyRingPeers(e){let t=new TextEncoder().encode(e),s=await Xt(t);return this.fretAdapter.getFret().assembleCohort(s,10)}getMyRingDepth(){return this.fretAdapter.getMyArachnodeInfo()?.ringDepth??8}filterByPartition(e,t,s){if(s===0)return e;let n=this.extractBlockPrefix(t,s);return e.filter(o=>{let i=this.fretAdapter.getArachnodeInfo(o);return!i||!i.partition?!1:i.partition.prefixValue===n})}extractBlockPrefix(e,t){let s=new TextEncoder().encode(e),n=new Uint8Array(32);for(let i=0;i<Math.min(s.length,n.length);i++)n[i]=s[i];let o=0;for(let i=0;i<t;i++){let a=Math.floor(i/8),c=7-i%8,l=n[a]>>c&1;o=o<<1|l}return o}async queryPeer(e,t,s){try{let n=$(e),i=await new tc(n,this.peerNetwork,this.protocolPrefix).requestBlock({blockId:t,rev:s});return i.success?i.archive:void 0}catch(n){this.log("queryPeer failed for %s - %o",e,n);return}}recordSuccess(e,t,s){let n=this.metrics.successByRing.get(e)??0;this.metrics.successByRing.set(e,n+1);let o=Array.from(this.metrics.successByRing.values()).reduce((a,c)=>a+c,0),i=this.metrics.averageDurationMs*(o-1);this.metrics.averageDurationMs=(i+s)/o,console.log(`[Ring ${e}] Successfully restored block ${t} in ${s}ms`)}getMetrics(){return{...this.metrics}}};var sc=class{fretAdapter;storageMonitor;config;constructor(e,t,s){this.fretAdapter=e,this.storageMonitor=t,this.config=s}async determineRing(){let e=await this.storageMonitor.getCapacity();if(e.available<this.config.minCapacity)return-1;let n=1e3*(100*1024),o=e.available/n,i=Math.max(0,Math.ceil(-Math.log2(Math.max(.001,o))));return Math.min(i,16)}async calculatePartition(e,t){if(e===0)return;let s=await Be({toString:()=>t}),n=e,o=this.extractPrefix(s,n);return{prefixBits:n,prefixValue:o}}async createArachnodeInfo(e){let t=await this.storageMonitor.getCapacity(),s=await this.determineRing(),n=s>=0?await this.calculatePartition(s,e):void 0;return{ringDepth:Math.max(0,s),partition:n,capacity:{total:t.total,used:t.used,available:t.available},status:"active"}}async shouldTransition(){let e=await this.storageMonitor.getCapacity(),t=e.used/e.total;if(t>this.config.thresholds.moveOut)return{shouldMove:!0,direction:"out",newRingDepth:await this.determineRing()+1};if(t<this.config.thresholds.moveIn){let s=await this.determineRing();if(s>0)return{shouldMove:!0,direction:"in",newRingDepth:s-1}}return{shouldMove:!1}}extractPrefix(e,t){let s=0;for(let n=0;n<t;n++){let o=Math.floor(n/8),i=7-n%8,a=e[o]>>i&1;s=s<<1|a}return s}};var nc=class{storage;config;constructor(e,t={}){this.storage=e,this.config=t}async getCapacity(){let t=this.config.totalBytes??10737418240,s=this.config.usedBytes,n=this.config.availableBytes;if(s!==void 0||n!==void 0||this.config.totalBytes!==void 0){let a=s??Math.max(0,t-(n??t)),c=n??Math.max(0,t-a);return{total:t,used:Math.min(t,Math.max(0,a)),available:Math.max(0,Math.min(t,c))}}let o=await this.estimateUsedSpace(),i=Math.max(0,t-o);return{total:t,used:o,available:i}}async estimateUsedSpace(){return 0}};var oc=class r{fret;static ARACHNODE_KEY="arachnode";constructor(e){this.fret=e}setArachnodeInfo(e){this.fret.setMetadata({[r.ARACHNODE_KEY]:e})}getArachnodeInfo(e){return this.fret.getMetadata(e)?.[r.ARACHNODE_KEY]}getMyArachnodeInfo(){let e=this.fret.node?.peerId?.toString();if(e)return this.getArachnodeInfo(e)}findPeersAtRing(e){return this.fret.listPeers().filter(s=>s.metadata?.[r.ARACHNODE_KEY]?.ringDepth===e).map(s=>s.id)}getKnownRings(){let e=this.fret.listPeers(),t=new Set;for(let s of e){let n=s.metadata?.[r.ARACHNODE_KEY];n?.ringDepth!==void 0&&t.add(n.ringDepth)}return Array.from(t).sort((s,n)=>s-n)}getRingStats(){let e=this.fret.listPeers(),t=new Map;for(let s of e){let n=s.metadata?.[r.ARACHNODE_KEY];if(n){let o=t.get(n.ringDepth)??{count:0,totalCapacity:0};t.set(n.ringDepth,{count:o.count+1,totalCapacity:o.totalCapacity+n.capacity.available})}}return Array.from(t.entries()).map(([s,n])=>({ringDepth:s,peerCount:n.count,avgCapacity:n.totalCapacity/n.count})).sort((s,n)=>s.ringDepth-n.ringDepth)}getFret(){return this.fret}};ge();Se();var vu=class{components;running=!1;log;protocol;repo;registrar;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("db-p2p:sync-service"),this.protocol=ec(t.protocolPrefix??""),this.repo=e.repo,this.registrar=e.registrar}async start(){this.running||(await this.registrar.handle(this.protocol,async e=>{await this.handleSyncRequest(e.stream)}),this.running=!0,this.log("Sync service started on protocol %s",this.protocol))}async stop(){this.running&&(await this.registrar.unhandle(this.protocol),this.running=!1,this.log("Sync service stopped"))}async handleSyncRequest(e){try{let t=await this.readRequest(e);this.log("[Ring Zulu] Received sync request for block %s revision %s",t.blockId,t.rev??"latest");let s=await this.buildArchive(t.blockId,t.rev,t.includePending,t.maxRevisions),n=s?{success:!0,archive:s,responderId:e.id}:{success:!1,error:"Block not found in local storage"};await this.sendResponse(e,n),this.log("[Ring Zulu] %s sync request for block %s",n.success?"Fulfilled":"Failed",t.blockId)}catch(t){this.log.error("Error handling sync request:",t);try{let s={success:!1,error:t instanceof Error?t.message:"Unknown error"};await this.sendResponse(e,s)}catch(s){this.log.error("Failed to send error response:",s)}}finally{try{await e.close()}catch{}}}async readRequest(e){let t=[];if(await st(e.source,Gt,async n=>{for await(let o of n)t.push(o.subarray())}),t.length===0)throw new Error("No request received");let s=K(t[0],"utf8");return JSON.parse(s)}async sendResponse(e,t){let s=JSON.stringify(t),n=L(s,"utf8");await st([n],sr,e.sink)}async buildArchive(e,t,s,n){try{let o=t!==void 0?{rev:t,committed:[],pending:[]}:void 0,a=(await this.repo.get({blockIds:[e],context:o}))[e];if(!a||!a.state.latest)return;let c=a.state.latest;return{blockId:e,revisions:{[c.rev]:{action:{actionId:c.actionId,transform:{insert:a.block}},block:a.block}},range:[c.rev,c.rev+1]}}catch(o){this.log.error("Error building archive for block %s:",e,o);return}}},$0=(r={})=>e=>new vu(e,r);Se();ce();var ic=class r{libp2p;clusterSize;selfCoordinationConfig;networkHighWaterMark=1;lastConnectedTime=Date.now();constructor(e,t=16,s){this.libp2p=e,this.clusterSize=t,this.selfCoordinationConfig={gracePeriodMs:s?.gracePeriodMs??3e4,shrinkageThreshold:s?.shrinkageThreshold??.5,allowSelfCoordination:s?.allowSelfCoordination??!0},this.setupConnectionTracking()}coordinatorCache=new Map;static MAX_CACHE_ENTRIES=1e3;log=lr("libp2p-key-network");toCacheKey(e){return K(e,"base64url")}setupConnectionTracking(){this.libp2p.addEventListener("connection:open",()=>{this.updateNetworkObservations()})}updateNetworkObservations(){(this.libp2p.getConnections?.()??[]).length>0&&(this.lastConnectedTime=Date.now());try{let s=this.getFret().getNetworkSizeEstimate();s.size_estimate>this.networkHighWaterMark&&(this.networkHighWaterMark=s.size_estimate,this.log("network-hwm-updated mark=%d confidence=%f",this.networkHighWaterMark,s.confidence))}catch{let s=(this.libp2p.getConnections?.().length??0)+1;s>this.networkHighWaterMark&&(this.networkHighWaterMark=s,this.log("network-hwm-updated mark=%d (from connections)",this.networkHighWaterMark))}}shouldAllowSelfCoordination(){if(!this.selfCoordinationConfig.allowSelfCoordination)return{allow:!1,reason:"disabled"};if(this.networkHighWaterMark<=1)return{allow:!0,reason:"bootstrap-node"};try{let t=this.getFret();if(t.detectPartition())return this.log("self-coord-blocked: partition-detected"),{allow:!1,reason:"partition-detected"};let s=t.getNetworkSizeEstimate(),n=1-s.size_estimate/this.networkHighWaterMark;if(n>this.selfCoordinationConfig.shrinkageThreshold)return this.log("self-coord-blocked: suspicious-shrinkage current=%d hwm=%d shrinkage=%f",s.size_estimate,this.networkHighWaterMark,n),{allow:!1,reason:"suspicious-shrinkage"}}catch{let t=this.libp2p.getConnections?.()??[];if(this.networkHighWaterMark>1&&t.length===0){let s=Date.now()-this.lastConnectedTime;if(s<this.selfCoordinationConfig.gracePeriodMs)return this.log("self-coord-blocked: grace-period-not-elapsed since=%dms",s),{allow:!1,reason:"grace-period-not-elapsed"}}}let e=Date.now()-this.lastConnectedTime;return e<this.selfCoordinationConfig.gracePeriodMs&&(this.libp2p.getConnections?.()??[]).length===0?(this.log("self-coord-blocked: grace-period-not-elapsed since=%dms",e),{allow:!1,reason:"grace-period-not-elapsed"}):(this.log("self-coord-allowed: extended-isolation (warn)"),{allow:!0,reason:"extended-isolation",warn:!0})}recordCoordinator(e,t,s=1800*1e3){let n=this.toCacheKey(e),o=Date.now();for(let[i,a]of this.coordinatorCache)a.expires<=o&&this.coordinatorCache.delete(i);for(this.coordinatorCache.set(n,{id:t,expires:o+s});this.coordinatorCache.size>r.MAX_CACHE_ENTRIES;){let i=this.coordinatorCache.keys().next().value;if(i==null)break;this.coordinatorCache.delete(i)}}getCachedCoordinator(e){let t=this.toCacheKey(e),s=this.coordinatorCache.get(t);if(s&&s.expires>Date.now())return s.id;s&&this.coordinatorCache.delete(t)}connect(e,t,s){let n=this.libp2p.getConnections?.(e)??[];if(Array.isArray(n)&&n.length>0&&typeof n[0]?.newStream=="function")return n[0].newStream([t]);let o={runOnLimitedConnection:!0,negotiateFully:!1};return this.libp2p.dialProtocol(e,[t],o)}getFret(){let e=this.libp2p.services?.fret;if(e==null)throw new Error("FRET service is not registered on this libp2p node");return e}async getNeighborIdsForKey(e,t){let s=this.getFret(),n=await Xt(e),o=s.getNeighbors(n,"both",t);return Array.from(new Set(o)).slice(0,t)}async findCoordinator(e,t){let s=new Set((t?.excludedPeers??[]).map(l=>l.toString())),n=this.toCacheKey(e).substring(0,12);this.log("findCoordinator:start key=%s excluded=%o",n,Array.from(s).map(l=>l.substring(0,12)));let o=this.getCachedCoordinator(e);if(o!=null&&!s.has(o.toString()))return this.log("findCoordinator:cached-hit key=%s coordinator=%s",n,o.toString().substring(0,12)),o;let i=3,a=500;for(let l=0;l<i;l++){let u=(this.libp2p.getConnections?.()??[]).map(f=>f.remotePeer),h=new Set(u.map(f=>f.toString()));this.log("findCoordinator:connected-peers key=%s count=%d peers=%o attempt=%d",n,u.length,u.map(f=>f.toString().substring(0,12)),l);try{let f=await this.getNeighborIdsForKey(e,this.clusterSize);this.log("findCoordinator:fret-neighbors key=%s candidates=%o",n,f.map(g=>g.substring(0,12)));let p=f.filter(g=>h.has(g)||g===this.libp2p.peerId.toString());this.log("findCoordinator:fret-connected key=%s count=%d peers=%o",n,p.length,p.map(g=>g.substring(0,12)));let m=p.find(g=>!s.has(g));if(m){let g=$(m);return this.recordCoordinator(e,g),this.log("findCoordinator:fret-selected key=%s coordinator=%s",n,m.substring(0,12)),g}}catch(f){this.log("findCoordinator getNeighborIdsForKey failed - %o",f)}let d=u.find(f=>!s.has(f.toString()));if(d)return this.recordCoordinator(e,d),this.log("findCoordinator:connected-fallback key=%s coordinator=%s",n,d.toString().substring(0,12)),d;if(u.length===0&&l<i-1){this.log("findCoordinator:no-connections-retry key=%s attempt=%d delay=%dms",n,l,a),await new Promise(f=>setTimeout(f,a));continue}}let c=this.libp2p.peerId;if(!s.has(c.toString())){let l=this.shouldAllowSelfCoordination();if(!l.allow)throw this.log("findCoordinator:self-coord-blocked key=%s reason=%s",n,l.reason),new Error(`Self-coordination blocked: ${l.reason}. No coordinator available for key.`);return l.warn?this.log("findCoordinator:self-selected-warn key=%s coordinator=%s reason=%s",n,c.toString().substring(0,12),l.reason):this.log("findCoordinator:self-selected key=%s coordinator=%s reason=%s",n,c.toString().substring(0,12),l.reason),c}throw this.log("findCoordinator:all-excluded key=%s self=%s",n,c.toString().substring(0,12)),new Error("No coordinator available for key (all candidates excluded)")}getConnectedAddrsByPeer(){let e=this.libp2p.getConnections(),t={};for(let s of e){let n=s.remotePeer.toString(),o=s.remoteAddr?.toString?.();o&&(t[n]??=[]).push(o)}return t}parseMultiaddrs(e){let t=[];for(let s of e)try{t.push(G(s))}catch(n){console.warn("invalid multiaddr from connection",s,n)}return t}async findCluster(e){let t=this.getFret(),s=await Xt(e),n=t.assembleCohort(s,this.clusterSize),o=this.toCacheKey(e).substring(0,12),i=Array.from(new Set([...n,this.libp2p.peerId.toString()])),a=this.getConnectedAddrsByPeer(),c=Object.keys(a);this.log("findCluster key=%s fretCohort=%d connected=%d cohortPeers=%o",o,n.length,c.length,i.map(u=>u.substring(0,12)));let l={};for(let u of i){if(u===this.libp2p.peerId.toString()){l[u]={multiaddrs:this.libp2p.getMultiaddrs(),publicKey:this.libp2p.peerId.publicKey?.raw??new Uint8Array};continue}let h=a[u]??[],d=this.parseMultiaddrs(h);l[u]={multiaddrs:d,publicKey:new Uint8Array}}return this.log("findCluster:result key=%s clusterSize=%d withAddrs=%d connectedInCohort=%d",o,Object.keys(l).length,Object.values(l).filter(u=>u.multiaddrs.length>0).length,i.filter(u=>c.includes(u)||u===this.libp2p.peerId.toString()).length),l}};ft();ce();X();function wi(r){if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:E4}=Object.prototype,{propertyIsEnumerable:SA}=Object,xi=(r,e,t)=>{Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})},IA=void 0,v4={concatArrays:!1,ignoreUndefined:!1},Eu=r=>{let e=[];for(let t in r)E4.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let s of t)SA.call(r,s)&&e.push(s)}return e};function vi(r){return Array.isArray(r)?_A(r):wi(r)?AA(r):r}function _A(r){let e=r.slice(0,0);return Eu(r).forEach(t=>{xi(e,t,vi(r[t]))}),e}function AA(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return Eu(r).forEach(t=>{xi(e,t,vi(r[t]))}),e}var S4=(r,e,t,s)=>(t.forEach(n=>{typeof e[n]>"u"&&s.ignoreUndefined||(n in r&&r[n]!==Object.getPrototypeOf(r)?xi(r,n,G0(r[n],e[n],s)):xi(r,n,vi(e[n])))}),r),CA=(r,e,t)=>{let s=r.slice(0,0),n=0;return[r,e].forEach(o=>{let i=[];for(let a=0;a<o.length;a++)E4.call(o,a)&&(i.push(String(a)),o===r?xi(s,n++,o[a]):xi(s,n++,vi(o[a])));s=S4(s,o,Eu(o).filter(a=>!i.includes(a)),t)}),s};function G0(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?CA(r,e,t):!wi(e)||!wi(r)?vi(e):S4(r,e,Eu(e),t)}function Su(...r){let e=G0(vi(v4),this!==IA&&this||{},v4),t={_:{}};for(let s of r)if(s!==void 0){if(!wi(s))throw new TypeError("`"+s+"` is not an Option Object");t=G0(t,{_:s},e)}return t._}var We=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var _4=re("dns/promises");function Iu(r){let e=[Et.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}Se();var V0=60;function _u(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:Et[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:Et[e.type],TTL:e.TTL??e.ttl??V0,data:e.data instanceof Uint8Array?K(e.data):e.data}))}}var TA=async(r,e={})=>{let t=new _4.Resolver,s=()=>{t.cancel()},n=Iu(e.types);try{e.signal?.addEventListener("abort",s);let o=await Promise.all(n.map(async i=>{if(i===Et.A)return Au(r,i,await t.resolve4(r));if(i===Et.CNAME)return Au(r,i,await t.resolveCname(r));if(i===Et.TXT)return Au(r,i,await t.resolveTxt(r));if(i===Et.AAAA)return Au(r,i,await t.resolve6(r));throw new TypeError("Unsupported DNS record type")}));return _u({Question:n.map(i=>({name:r,type:i})),Answer:o.flat()})}finally{e.signal?.removeEventListener("abort",s)}};function A4(){return[TA]}function I4(r,e,t){return{name:r,type:e,data:t}}function Au(r,e,t){return Array.isArray(t)||(t=[t]),t.map(s=>Array.isArray(s)?s.map(n=>I4(r,e,n)):I4(r,e,s)).flat()}var P4=we(T4(),1);var W0=class{lru;constructor(e){this.lru=(0,P4.default)(e)}get(e,t){let s=!0,n=[];for(let o of t){let i=this.getAnswers(e,o);if(i.length===0){s=!1;break}n.push(...i)}if(s)return _u({answers:n})}getAnswers(e,t){let s=`${e.toLowerCase()}-${t}`,n=this.lru.get(s);if(n!=null){let o=n.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:Et[a.type]}));return o.length===0&&this.lru.remove(s),o}return[]}add(e,t){let s=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(s)??[];n.push({expires:Date.now()+(t.TTL??V0)*1e3,value:t}),this.lru.set(s,n)}remove(e,t){let s=`${e.toLowerCase()}-${t}`;this.lru.remove(s)}clear(){this.lru.clear()}};function k4(r){return new W0(r)}var PA=1e3,Cu=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=k4(e.cacheSize??PA),Object.entries(e.resolvers??{}).forEach(([t,s])=>{Array.isArray(s)||(s=[s]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=s}),this.resolvers["."]==null&&(this.resolvers["."]=A4())}async query(e,t={}){let s=Iu(t.types),n=t.cached!==!1?this.cache.get(e,s):void 0;if(n!=null)return t.onProgress?.(new We("dns:cache",n)),n;let o=`${e.split(".").pop()}.`,i=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:s});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new We("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${s} failed`)}};var Et;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Et||(Et={}));function D4(r={}){return new Cu(r)}var j0=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let s=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(s==null)return[e];let o=await this.getDNS(t).query(`_dnsaddr.${s}`,{signal:t?.signal,types:[Et.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of o.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(G(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=D4()),this.dns)}},zn=new j0;var kA={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:zn}},transportManager:{faultTolerance:_n.FATAL_ALL}};async function M4(r){let e=Su(kA,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new V("Private network is enforced, but no protector was provided");return e}ft();X();Ro();Vt();cl();var R4=we(re("node:tty"),1),Mu=we(re("node:util"),1);function DA(r,e){if(typeof r=="string")return MA(r);if(typeof r=="number")return RA(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var Tu=DA;function MA(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:s="ms"}=e.groups,n=parseFloat(t),o=s.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return n*315576e5;case"months":case"month":case"mo":return n*26298e5;case"weeks":case"week":case"w":return n*6048e5;case"days":case"day":case"d":return n*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return n*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return n*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return n*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:throw Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function OA(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function LA(r){let e=Math.abs(r);return e>=315576e5?qn(r,e,315576e5,"year"):e>=26298e5?qn(r,e,26298e5,"month"):e>=6048e5?qn(r,e,6048e5,"week"):e>=864e5?qn(r,e,864e5,"day"):e>=36e5?qn(r,e,36e5,"hour"):e>=6e4?qn(r,e,6e4,"minute"):e>=1e3?qn(r,e,1e3,"second"):`${r} ms`}function RA(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?LA(r):OA(r)}function qn(r,e,t,s){let n=e>=t*1.5;return`${Math.round(r/t)} ${s}${n?"s":""}`}var ku=we(re("node:process"),1),L4=we(re("node:os"),1),Y0=we(re("node:tty"),1);function fr(r,e=globalThis.Deno?globalThis.Deno.args:ku.default.argv){let t=r.startsWith("-")?"":r.length===1?"-":"--",s=e.indexOf(t+r),n=e.indexOf("--");return s!==-1&&(n===-1||s<n)}var{env:Te}=ku.default,Pu;fr("no-color")||fr("no-colors")||fr("color=false")||fr("color=never")?Pu=0:(fr("color")||fr("colors")||fr("color=true")||fr("color=always"))&&(Pu=1);function NA(){if(!("FORCE_COLOR"in Te))return;if(Te.FORCE_COLOR==="true")return 1;if(Te.FORCE_COLOR==="false")return 0;if(Te.FORCE_COLOR.length===0)return 1;let r=Math.min(Number.parseInt(Te.FORCE_COLOR,10),3);if([0,1,2,3].includes(r))return r}function BA(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function FA(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let s=NA();s!==void 0&&(Pu=s);let n=t?Pu:s;if(n===0)return 0;if(t){if(fr("color=16m")||fr("color=full")||fr("color=truecolor"))return 3;if(fr("color=256"))return 2}if("TF_BUILD"in Te&&"AGENT_NAME"in Te)return 1;if(r&&!e&&n===void 0)return 0;let o=n||0;if(Te.TERM==="dumb")return o;if(ku.default.platform==="win32"){let i=L4.default.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in Te)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in Te)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in Te)||Te.CI_NAME==="codeship"?1:o;if("TEAMCITY_VERSION"in Te)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Te.TEAMCITY_VERSION)?1:0;if(Te.COLORTERM==="truecolor"||Te.TERM==="xterm-kitty"||Te.TERM==="xterm-ghostty"||Te.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Te){let i=Number.parseInt((Te.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Te.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Te.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Te.TERM)||"COLORTERM"in Te?1:o}function O4(r,e={}){let t=FA(r,{streamIsTTY:r&&r.isTTY,...e});return BA(t)}var UA={stdout:O4({isTTY:Y0.default.isatty(1)}),stderr:O4({isTTY:Y0.default.isatty(2)})},Du=UA;function X0(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=n,t.enabled=i,t.humanize=Tu,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let h=0;for(let d=0;d<u.length;d++)h=(h<<5)-h+u.charCodeAt(d),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(u){let h,d=null,f,p;function m(...g){if(!m.enabled)return;let y=m,w=Number(new Date),b=w-(h||w);y.diff=b,y.prev=h,y.curr=w,h=w,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(P,T)=>{if(P==="%%")return"%";x++;let D=t.formatters[T];if(typeof D=="function"){let v=g[x];P=D.call(y,v),g.splice(x,1),x--}return P}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=s,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(u)),p),set:g=>{d=g}}),typeof t.init=="function"&&t.init(m),m}function s(u,h){let d=t(this.namespace+(typeof h>"u"?":":h)+u);return d.log=this.log,d}function n(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let h,d=(typeof u=="string"?u:"").split(/[\s,]+/),f=d.length;for(h=0;h<f;h++)d[h]&&(u=d[h].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function o(){let u=[...t.names.map(a),...t.skips.map(a).map(h=>"-"+h)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let h,d;for(h=0,d=t.skips.length;h<d;h++)if(t.skips[h].test(u))return!1;for(h=0,d=t.names.length;h<d;h++)if(t.names[h].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var N4=[6,2,3,4,5,1];Du.stderr!==!1&&(Du.stderr??Du).level>=2&&(N4=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]);var Ei=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(n,o)=>o.toUpperCase()),s=process.env[e];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),r[t]=s,r},{});function KA(){return"colors"in Ei?!!Ei.colors:R4.default.isatty(process.stderr.fd)}function HA(r){let{namespace:e,useColors:t}=this;if(t===!0){let s=this.color,n="\x1B[3"+(s<8?s:"8;5;"+s),o=` ${n};1m${e} \x1B[0m`;r[0]=o+r[0].split(`
|
|
7
|
+
`).join(`
|
|
8
|
+
`+o),r.push(n+"m+"+Tu(this.diff)+"\x1B[0m")}else r[0]=zA()+e+" "+r[0]}function zA(){return Ei.hideDate!=null?"":new Date().toISOString()+" "}function qA(...r){return process.stderr.write(Mu.default.format(...r)+`
|
|
9
|
+
`)}function $A(r){r!=null?process.env.DEBUG=r:delete process.env.DEBUG}function GA(){return process.env.DEBUG}function VA(r){r.inspectOpts={};let e=Object.keys(Ei);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=Ei[e[t]]}function WA(r){r.o=function(e){return this.inspectOpts.colors=this.useColors,Mu.default.inspect(e,this.inspectOpts).split(`
|
|
10
|
+
`).map(t=>t.trim()).join(" ")},r.O=function(e){return this.inspectOpts.colors=this.useColors,Mu.default.inspect(e,this.inspectOpts)}}var B4=X0({init:VA,log:qA,formatArgs:HA,save:$A,load:GA,useColors:KA,setupFormatters:WA,colors:N4,inspectOpts:Ei});var $t=B4;$t.formatters.b=r=>r==null?"undefined":me.baseEncode(r);$t.formatters.t=r=>r==null?"undefined":or.baseEncode(r);$t.formatters.m=r=>r==null?"undefined":Fd.baseEncode(r);$t.formatters.p=r=>r==null?"undefined":r.toString();$t.formatters.c=r=>r==null?"undefined":r.toString();$t.formatters.k=r=>r==null?"undefined":r.toString();$t.formatters.a=r=>r==null?"undefined":r.toString();$t.formatters.e=r=>r==null?"undefined":F4(r.stack)??F4(r.message)??r.toString();function jA(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function Ou(){return{forComponent(r){return U4(r)}}}function U4(r){let e=jA(`${r}:trace`);return $t.enabled(`${r}:trace`)&&$t.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=$t(`${r}:trace`)),Object.assign($t(r),{error:$t(`${r}:error`),trace:e,newScope:t=>U4(`${r}:${t}`)})}function F4(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}ce();Vt();ir();function $n(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let s=r.next(),n=s.value;return s.done===!0||n==null?{done:!0,value:void 0}:{done:!1,value:e(n)}}};return t}function Lu(r){let e=Ht(me.decode(`z${r}`));return Pr(e)}var pr=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,s]of e.entries())this.map.set(t.toString(),{key:t,value:s})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return $n(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,s)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return $n(this.map.values(),e=>e.key)}values(){return $n(this.map.values(),e=>e.value)}get size(){return this.map.size}};var Gn=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return $n(this.set.entries(),e=>{let t=Lu(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let s=Lu(t);e(s,s,this)})}has(e){return this.set.has(e.toString())}values(){return $n(this.set.values(),e=>Lu(e))}intersection(e){let t=new r;for(let s of e)this.has(s)&&t.add(s);return t}difference(e){let t=new r;for(let s of this)e.has(s)||t.add(s);return t}union(e){let t=new r;for(let s of e)t.add(s);for(let s of this)t.add(s);return t}};m6();var Z0={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},K4={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},H4=new globalThis.TextEncoder;function YA(r,e){let t=Z0[e],s=K4[e];for(let n=0;n<r.length;n++)s^=BigInt(r[n]),s=BigInt.asUintN(e,s*t);return s}function XA(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let s=Z0[e],n=K4[e],o=r;for(;o.length>0;){let i=H4.encodeInto(o,t);o=o.slice(i.read);for(let a=0;a<i.written;a++)n^=BigInt(t[a]),n=BigInt.asUintN(e,n*s)}return n}function Q0(r,{size:e=32,utf8Buffer:t}={}){if(!Z0[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return XA(r,e,t);r=H4.encode(r)}return YA(r,e)}ge();var ac={hash:r=>Number(Q0(r,{size:32})),hashV:(r,e)=>ZA(ac.hash(r,e))};function ZA(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),L(e,"base16")}ge();nt();Kt();var J0=64,Mr=class{fp;h;seed;constructor(e,t,s,n=2){if(n>J0)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,s),i=ie(n);for(let a=0;a<i.length;a++)i[a]=o[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=s}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ae(this.fp,e.fp):!1}};function Vn(r,e){return Math.floor(Math.random()*(e-r))+r}var Wn=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Mr))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Mr))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Mr))throw new TypeError("Invalid Fingerprint");let t=Vn(0,this.contents.length-1),s=this.contents[t];return this.contents[t]=e,s}remove(e){if(!(e instanceof Mr))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(s=>e.equals(s));return t>-1?(this.contents[t]=null,!0):!1}};var QA=500,cc=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??ac,this.seed=e.seed??Vn(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=L(e));let t=new Mr(e,this.hash,this.seed,this.fingerprintSize),s=this.hash.hash(e,this.seed)%this.filterSize,n=(s^t.hash())%this.filterSize;if(this.buckets[s]==null&&(this.buckets[s]=new Wn(this.bucketSize)),this.buckets[n]==null&&(this.buckets[n]=new Wn(this.bucketSize)),this.buckets[s].add(t)||this.buckets[n].add(t))return this.count++,!0;let o=[s,n],i=o[Vn(0,o.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Wn(this.bucketSize));for(let a=0;a<QA;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Wn(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=L(e));let t=new Mr(e,this.hash,this.seed,this.fingerprintSize),s=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[s]?.has(t)??!1;if(n)return n;let o=(s^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=L(e));let t=new Mr(e,this.hash,this.seed,this.fingerprintSize),s=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[s]?.remove(t)??!1;if(n)return this.count--,n;let o=(s^t.hash())%this.filterSize,i=this.buckets[o]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},JA={1:.5,2:.84,4:.95,8:.98};function eC(r=.001){return r>.002?2:r>1e-5?4:8}function z4(r,e=.001){let t=eC(e),s=JA[t],n=Math.round(r/s),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),J0);return{filterSize:n,bucketSize:t,fingerprintSize:o}}ge();var Ru=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??ac,this.seed=e.seed??Vn(0,Math.pow(2,10)),this.filterSeries=[new cc({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=L(e)),this.has(e))return!0;let t=this.filterSeries.find(s=>s.reliable);if(t==null){let s=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new cc({filterSize:s,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=L(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function lc(r,e=.001,t){return new Ru({...z4(r,e),...t??{}})}var e2=class extends pr{metric;constructor(e){super();let{name:t,metrics:s}=e;this.metric=s.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function t2(r){let{name:e,metrics:t}=r,s;return t!=null?s=new e2({name:e,metrics:t}):s=new pr,s}ce();X();ce();ft();wr();ot();Kt();ge();zs();nt();var uc;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(s.uint32(10),s.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(s.uint32(18),s.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(s.uint32(26),s.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(s.uint32(42),s.bytes(t.signature)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={publicKey:ie(0),payloadType:ie(0),payload:ie(0),signature:ie(0)},i=s==null?t.len:t.pos+s;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=t.bytes();break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})(uc||(uc={}));var Nu=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Or=class r{static createFromProtobuf=e=>{let t=uc.decode(e),s=Je(t.publicKey);return new r({publicKey:s,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,s)=>{if(t==null)throw new Error("Missing private key");let n=e.domain,o=e.codec,i=e.marshal(),a=q4(n,o,i),c=await t.sign(a.subarray(),s);return new r({publicKey:t.publicKey,payloadType:o,payload:i,signature:c})};static openAndCertify=async(e,t,s)=>{let n=r.createFromProtobuf(e);if(!await n.validate(t,s))throw new Nu("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:s,payload:n,signature:o}=e;this.publicKey=t,this.payloadType=s,this.payload=n,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=uc.encode({publicKey:Ve(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:ae(this.marshal(),e.marshal())}async validate(e,t){let s=q4(e,this.payloadType,this.payload);return this.publicKey.verify(s.subarray(),this.signature,t)}},q4=(r,e,t)=>{let s=L(r),n=rr(s.byteLength),o=rr(e.length),i=rr(t.length);return new W(n,s,o,e,i,t)};ce();function $4(r,e){let t=(s,n)=>s.toString().localeCompare(n.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((s,n)=>e[n].equals(s)))}ir();var G4="libp2p-peer-record",V4=Uint8Array.from([3,1]);zs();nt();var hc;(function(r){let e;(function(s){let n;s.codec=()=>(n==null&&(n=he((o,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(o.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(o,i,a={})=>{let c={multiaddr:ie(0)},l=i==null?o.len:o.pos+i;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.multiaddr=o.bytes();break}default:{o.skipType(u&7);break}}}return c})),n),s.encode=o=>ue(o,s.codec()),s.decode=(o,i)=>le(o,s.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=he((s,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),s.peerId!=null&&s.peerId.byteLength>0&&(n.uint32(10),n.bytes(s.peerId)),s.seq!=null&&s.seq!==0n&&(n.uint32(16),n.uint64(s.seq)),s.addresses!=null)for(let i of s.addresses)n.uint32(26),r.AddressInfo.codec().encode(i,n);o.lengthDelimited!==!1&&n.ldelim()},(s,n,o={})=>{let i={peerId:ie(0),seq:0n,addresses:[]},a=n==null?s.len:s.pos+n;for(;s.pos<a;){let c=s.uint32();switch(c>>>3){case 1:{i.peerId=s.bytes();break}case 2:{i.seq=s.uint64();break}case 3:{if(o.limits?.addresses!=null&&i.addresses.length===o.limits.addresses)throw new Ie('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(s,s.uint32(),{limits:o.limits?.addresses$}));break}default:{s.skipType(c&7);break}}}return i})),t),r.encode=s=>ue(s,r.codec()),r.decode=(s,n)=>le(s,r.codec(),n)})(hc||(hc={}));var Qt=class r{static createFromProtobuf=e=>{let t=hc.decode(e),s=Pr(Ht(t.peerId)),n=(t.addresses??[]).map(i=>G(i.multiaddr)),o=t.seq;return new r({peerId:s,multiaddrs:n,seqNumber:o})};static DOMAIN=G4;static CODEC=V4;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:s,seqNumber:n}=e;this.peerId=t,this.multiaddrs=s??[],this.seqNumber=n??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=hc.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!$4(this.multiaddrs,e.multiaddrs))}};function tC(r){return r[Symbol.asyncIterator]!=null}function rC(r){if(tC(r))return(async()=>{let t=[];for await(let s of r)t.push(s);return t})();let e=[];for(let t of r)e.push(t);return e}var dc=rC;X();ce();var Jt=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};Ze();async function er(r,e,t,s){let n=new Jt(s?.errorMessage);s?.errorCode!=null&&(n.code=s.errorCode);let o=s?.errorEvent??"error";return t?.aborted===!0?Promise.reject(n):new Promise((i,a)=>{function c(){s2(t,"abort",h),s2(r,e,l),s2(r,o,u)}let l=d=>{try{if(s?.filter?.(d)===!1)return}catch(f){c(),a(f);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??s?.error??new Error(`The "${s?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(n)};r2(t,"abort",h),r2(r,e,l),r2(r,o,u)})}function r2(r,e,t){r!=null&&(W4(r)?r.addEventListener(e,t):r.addListener(e,t))}function s2(r,e,t){r!=null&&(W4(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function W4(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Bu=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};Ze();var Fu=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Jt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function sC(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Uu=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=sC(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,J(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,s)=>t&&s.signal?.aborted===!0,!0)&&(this.controller.abort(new Jt),this.cleanup())}async join(e={}){let t=new Fu(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ce(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function n2(r,e){let t,s=function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)};return s.start=()=>{},s.stop=()=>{clearTimeout(t)},s}var fc=class extends Xe{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=n2(this.emitEmpty.bind(this),1),this.emitIdle=n2(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Bu;let s=new Uu(e,t);return this.enqueue(s),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),s.join(t).then(n=>(this.safeDispatchEvent("success",{detail:{job:s,result:n}}),n)).catch(n=>{if(s.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===s){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:s,error:n}}),n})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Jt)}),this.clear()}async onEmpty(e){this.size!==0&&await er(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await er(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await er(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=dt({objectMode:!0}),s=c=>{c!=null?this.abort():this.clear(),t.end(c)},n=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{s(c.detail.error)},i=()=>{s()},a=()=>{s(new Jt("Queue aborted"))};this.addEventListener("success",n),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",n),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),s()}}};var mc=we(re("node:cluster"),1),qu=we(re("node:worker_threads"),1);Ze();var jn="lock:worker:request-read",Yn="lock:worker:abort-read-request",Xn="lock:worker:release-read",Zn="lock:master:grant-read",Qn="lock:master:error-read",Jn="lock:worker:request-write",eo="lock:worker:abort-write-request",to="lock:worker:release-write",ro="lock:master:grant-write",so="lock:master:error-write",en="lock:worker:finalize",Ku="mortice",j4={singleProcess:!1};var o2=(r,e,t,s,n,o,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===n&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(h=>{let d=f=>{if(f?.data==null)return;let p={type:f.data.type,name:f.data.name,identifier:f.data.identifier};p.type===a&&p.identifier===u.identifier&&(e.removeEventListener("message",d),h())};e.addEventListener("message",d)})},onError:h=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:h.message,name:h.name,stack:h.stack}})}}}),u.type===o&&r.safeDispatchEvent(s,{detail:{name:u.name,identifier:u.identifier}}),u.type===en&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var i2=(r,e,t,s,n,o,i,a)=>(c,l)=>{l!=null&&(l.type===s&&r.safeDispatchEvent(e,{detail:{name:l.name,identifier:l.identifier,handler:async()=>{c.send({type:a,name:l.name,identifier:l.identifier}),await new Promise(u=>{let h=d=>{d.type===i&&d.identifier===l.identifier&&(c.removeListener("message",h),u())};c.on("message",h)})},onError:u=>{c.send({type:o,name:l.name,identifier:l.identifier,error:{message:u.message,name:u.name,stack:u.stack}})}}}),l.type===n&&r.safeDispatchEvent(t,{detail:{name:l.name,identifier:l.identifier}}),l.type===en&&r.safeDispatchEvent("finalizeRequest",{detail:{name:l.name}}))};var pc=(r=10)=>Math.random().toString().substring(2,r+2);var Hu=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Ku)}readLock(e){return this.sendRequest(jn,Yn,Zn,Qn,Xn,e)}writeLock(e){return this.sendRequest(Jn,eo,ro,so,to,e)}finalize(){this.channel.postMessage({type:en,name:this.name}),this.channel.close()}async sendRequest(e,t,s,n,o,i){i?.signal?.throwIfAborted();let a=pc();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let h=d=>{if(d.data?.identifier===a&&(d.data?.type===s&&(this.channel.removeEventListener("message",h),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),d.data.type===n)){this.channel.removeEventListener("message",h),i?.signal?.removeEventListener("abort",u);let f=new Error;d.data.error!=null&&(f.message=d.data.error.message,f.name=d.data.error.name,f.stack=d.data.error.stack),l(f)}};this.channel.addEventListener("message",h)})}};var zu=class{name;constructor(e){this.name=e}readLock(e){return this.sendRequest(jn,Yn,Zn,Qn,Xn,e)}writeLock(e){return this.sendRequest(Jn,eo,ro,so,to,e)}finalize(){if(process.send==null)throw new Error("No send method on process - are we a cluster worker?");process.send({type:en,identifier:pc(),name:this.name})}async sendRequest(e,t,s,n,o,i){i?.signal?.throwIfAborted();let a=pc();if(process.send==null)throw new Error("No send method on process - are we a cluster worker?");return process.send({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{process.send?.({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let h=d=>{if(d.identifier===a&&(d.type===s&&(process.removeListener("message",h),i?.signal?.removeEventListener("abort",u),c(()=>{process.send?.({type:o,identifier:a,name:this.name})})),d.type===n)){process.removeListener("message",h),i?.signal?.removeEventListener("abort",u);let f=new Error;d.error!=null&&(f.message=d.error.message,f.name=d.error.name,f.stack=d.error.stack),l(f)}};process.on("message",h)})}};function nC(){return qu.default.isMainThread===!1||qu.default.isInternalThread===!0?!1:mc.default.isPrimary}var Y4=r=>{if(r=Object.assign({},j4,r),nC()||r.singleProcess){let e=new Xe;mc.default.on("message",i2(e,"requestReadLock","abortReadLockRequest",jn,Yn,Qn,Xn,Zn)),mc.default.on("message",i2(e,"requestWriteLock","abortWriteLockRequest",Jn,eo,so,to,ro));let t=new BroadcastChannel(Ku);return t.addEventListener("message",o2(e,t,"requestReadLock","abortReadLockRequest",jn,Yn,Qn,Xn,Zn)),t.addEventListener("message",o2(e,t,"requestWriteLock","abortWriteLockRequest",Jn,eo,so,to,ro)),t.unref?.(),e}if(mc.default.isWorker)return new zu(r.name);if(qu.default.isMainThread===!1)return new Hu(r.name);throw new Error("Not a cluster worker or worker thread")};var no=new Map,gc;function X4(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function oC(r){if(gc==null&&(gc=Y4(r),!X4(gc))){let e=gc;e.addEventListener("requestReadLock",t=>{let s=t.detail.name,n=t.detail.identifier,o=no.get(s);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==s||c.detail.identifier!==n||i.abort()};e.addEventListener("abortReadLockRequest",a),o.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let s=t.detail.name,n=t.detail.identifier,o=no.get(s);if(o==null)return;let i=new AbortController,a=c=>{c.detail.name!==s||c.detail.identifier!==n||i.abort()};e.addEventListener("abortWriteLockRequest",a),o.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let s=t.detail.name,n=no.get(s);n?.finalize()})}return gc}async function a2(r,e){let t,s,n=new Promise((i,a)=>{t=i,s=a}),o=()=>{s(new Jt)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",o),i()})})},{signal:e?.signal}).catch(i=>{s(i)}),n}var Z4=(r,e)=>{let t=no.get(r);if(t!=null)return t;let s=oC(e);if(X4(s))return t=s,no.set(r,t),t;let n=new fc({concurrency:1}),o;return t={async readLock(i){if(o!=null)return a2(o,i);o=new fc({concurrency:e.concurrency,autoStart:!1});let a=o,c=a2(o,i);return n.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(i){return o=null,a2(n,i)},finalize:()=>{no.delete(r)},queue:n},no.set(r,t),e.autoFinalize===!0&&n.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var iC={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function c2(r){let e=Object.assign({},iC,r);return Z4(e.name,e)}Ro();zr();zs();nt();var xs;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=he((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:ie(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let h=i.uint32();switch(h>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(h&7);break}}}return l})),o),n.encode=i=>ue(i,n.codec()),n.decode=(i,a)=>le(i,n.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(n){let o;n.codec=()=>(o==null&&(o=he((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Gu.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let h=i.uint32();switch(h>>>3){case 1:{l.key=i.string();break}case 2:{l.value=Gu.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(h&7);break}}}return l})),o),n.encode=i=>ue(i,n.codec()),n.decode=(i,a)=>le(i,n.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let s;r.codec=()=>(s==null&&(s=he((n,o,i={})=>{if(i.lengthDelimited!==!1&&o.fork(),n.addresses!=null)for(let a of n.addresses)o.uint32(10),$u.codec().encode(a,o);if(n.protocols!=null)for(let a of n.protocols)o.uint32(18),o.string(a);if(n.publicKey!=null&&(o.uint32(34),o.bytes(n.publicKey)),n.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(n.peerRecordEnvelope)),n.metadata!=null&&n.metadata.size!==0)for(let[a,c]of n.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(n.tags!=null&&n.tags.size!==0)for(let[a,c]of n.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);n.updated!=null&&(o.uint32(64),o.uint64Number(n.updated)),i.lengthDelimited!==!1&&o.ldelim()},(n,o,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?n.len:n.pos+o;for(;n.pos<c;){let l=n.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new Ie('Decode error - map field "addresses" had too many elements');a.addresses.push($u.codec().decode(n,n.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new Ie('Decode error - map field "protocols" had too many elements');a.protocols.push(n.string());break}case 4:{a.publicKey=n.bytes();break}case 5:{a.peerRecordEnvelope=n.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new ba('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(n,n.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new ba('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(n,n.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=n.uint64Number();break}default:{n.skipType(l&7);break}}}return a})),s),r.encode=n=>ue(n,r.codec()),r.decode=(n,o)=>le(n,r.codec(),o)})(xs||(xs={}));var $u;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(s.uint32(10),s.bytes(t.multiaddr)),t.isCertified!=null&&(s.uint32(16),s.bool(t.isCertified)),t.observed!=null&&(s.uint32(24),s.uint64Number(t.observed)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={multiaddr:ie(0)},i=s==null?t.len:t.pos+s;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.multiaddr=t.bytes();break}case 2:{o.isCertified=t.bool();break}case 3:{o.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})($u||($u={}));var Gu;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.value!=null&&t.value!==0&&(s.uint32(8),s.uint32(t.value)),t.expiry!=null&&(s.uint32(16),s.uint64(t.expiry)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={value:0},i=s==null?t.len:t.pos+s;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.value=t.uint32();break}case 2:{o.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})(Gu||(Gu={}));ft();ce();function aC(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let s=Je(e.publicKey,t);return gs(s)}function Q4(r,e,t){let s=xs.decode(e);return Si(r,s,t)}function Si(r,e,t){let s=new Map,n=BigInt(Date.now());for(let[o,i]of e.tags.entries())i.expiry!=null&&i.expiry<n||s.set(o,i);return{...e,id:aC(r,e),addresses:e.addresses.filter(({observed:o})=>o!=null&&o>Date.now()-t).map(({multiaddr:o,isCertified:i})=>({multiaddr:G(o),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:s}}Kt();function J4(r,e){return cC(r.addresses,e.addresses)&&lC(r.protocols,e.protocols)&&uC(r.publicKey,e.publicKey)&&hC(r.peerRecordEnvelope,e.peerRecordEnvelope)&&dC(r.metadata,e.metadata)&&fC(r.tags,e.tags)}function cC(r,e){return tb(r,e,(t,s)=>!(t.isCertified!==s.isCertified||!ae(t.multiaddr,s.multiaddr)))}function lC(r,e){return tb(r,e,(t,s)=>t===s)}function uC(r,e){return eb(r,e)}function hC(r,e){return eb(r,e)}function dC(r,e){return rb(r,e,(t,s)=>ae(t,s))}function fC(r,e){return rb(r,e,(t,s)=>t.value===s.value&&t.expiry===s.expiry)}function eb(r,e){return r==null&&e==null?!0:r!=null&&e!=null?ae(r,e):!1}function tb(r,e,t){if(r.length!==e.length)return!1;for(let s=0;s<r.length;s++)if(!t(r[s],e[s]))return!1;return!0}function rb(r,e,t){if(r.size!==e.size)return!1;for(let[s,n]of r.entries()){let o=e.get(s);if(o==null||!t(n,o))return!1}return!0}X();ge();Se();var vs="/",sb=new TextEncoder().encode(vs),Vu=sb[0],oo=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=L(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Vu)throw new Error("Invalid key")}toString(e="utf8"){return K(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(vs))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=sb),this._buf[0]!==Vu){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Vu,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Vu;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),s=e.list();for(let n=0;n<t.length;n++){if(s.length<n+1)return!1;let o=t[n],i=s[n];if(o<i)return!0;if(o>i)return!1}return t.length<s.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(vs).slice(1)}type(){return pC(this.baseNamespace())}name(){return mC(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(vs)||(e+=vs),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(vs):new r(e.slice(0,-1).join(vs))}child(e){return this.toString()===vs?e:e.toString()===vs?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...gC(e.map(t=>t.namespaces()))])}};function pC(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function mC(r){let e=r.split(":");return e[e.length-1]}function gC(r){return[].concat(...r)}var l2="/peers/";function yc(r){if(!Vs(r)||r.type==null)throw new V("Invalid PeerId");let e=r.toCID().toString();return new oo(`${l2}${e}`)}ft();X();Kt();X();async function nb(r,e,t,s,n){let o=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=G(i.multiaddr)),!Js(i.multiaddr))throw new V("Multiaddr was invalid");if(!await e(r,i.multiaddr,n))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=o.get(c);l!=null?i.isCertified=l.isCertified||a:o.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...o.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getPeerId();return r.equals(c)&&(a=a.decapsulate(G(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function ju(r,e,t,s){if(e==null)throw new V("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new V("publicKey bytes do not match peer id publicKey bytes");let n=s.existingPeer?.peer;if(n!=null&&!r.equals(n.id))throw new V("peer id did not match existing peer id");let o=n?.addresses??[],i=new Set(n?.protocols??[]),a=n?.metadata??new Map,c=n?.tags??new Map,l=n?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Wu(d,{validate:ob})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Wu(d,{validate:ib,map:ab})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,p]of d)p==null?a.delete(f):a.set(f,p);a=Wu([...a.entries()],{validate:ob})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[p,m]of d)m==null?f.delete(p):f.set(p,m);c=Wu([...f.entries()],{validate:ib,map:ab})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;n?.id.publicKey!=null?u=Ve(n.id.publicKey):e.publicKey!=null?u=Ve(e.publicKey):r.publicKey!=null&&(u=Ve(r.publicKey));let h={addresses:await nb(r,s.addressFilter??(async()=>!0),o,s.existingPeer?.peerPB.addresses,s),protocols:[...i.values()].sort((d,f)=>d.localeCompare(f)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return h.addresses.forEach(d=>{d.observed=s.existingPeer?.peerPB.addresses?.find(f=>ae(f.multiaddr,f.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete h.publicKey,h}function Wu(r,e){let t=new Map;for(let[s,n]of r)n!=null&&e.validate(s,n);for(let[s,n]of r.sort(([o],[i])=>o.localeCompare(i)))n!=null&&t.set(s,e.map?.(s,n)??n);return t}function ob(r,e){if(typeof r!="string")throw new V("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new V("Metadata value must be a Uint8Array")}function ib(r,e){if(typeof r!="string")throw new V("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new V("Tag value must be an integer");if(e.value<0||e.value>100)throw new V("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new V("Tag ttl must be an integer");if(e.ttl<0)throw new V("Tag ttl must be between greater than 0")}}function ab(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let s={value:e.value??0};return t!=null&&(s.expiry=t),s}function cb(r){let e=r.toString().split("/")[2],t=De.parse(e,or);return Wr(t)}function u2(r,e,t){let s=cb(r);return Q4(s,e,t)}function yC(r,e){return{prefix:l2,filters:(r.filters??[]).map(t=>({key:s,value:n})=>t(u2(s,n,e))),orders:(r.orders??[]).map(t=>(s,n)=>t(u2(s.key,s.value,e),u2(n.key,n.value,e)))}}var Yu=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=t2({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:c2({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let s=this.getLock(e);try{let n=await s.lock.readLock(t);return()=>{n(),this.maybeRemoveLock(e,s)}}catch(n){throw this.maybeRemoveLock(e,s),n}}async getWriteLock(e,t){let s=this.getLock(e);try{let n=await s.lock.writeLock(t);return()=>{n(),this.maybeRemoveLock(e,s)}}catch(n){throw this.maybeRemoveLock(e,s),n}}async has(e,t){try{return await this.load(e,t),!0}catch(s){if(s.name!=="NotFoundError")throw s}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(yc(e),t)}async load(e,t){let s=yc(e),n=await this.datastore.get(s,t),o=xs.decode(n);if(this.#r(e,o))throw await this.datastore.delete(s,t),new An;return Si(e,o,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,s){let n=await this.#e(e,s),o=await ju(e,t,"patch",{...s,addressFilter:this.addressFilter});return this.#t(e,o,n)}async patch(e,t,s){let n=await this.#e(e,s),o=await ju(e,t,"patch",{...s,addressFilter:this.addressFilter,existingPeer:n});return this.#t(e,o,n)}async merge(e,t,s){let n=await this.#e(e,s),o=await ju(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#t(e,o,n)}async*all(e){for await(let{key:t,value:s}of this.datastore.query(yC(e??{},this.maxAddressAge),e)){let n=cb(t);if(n.equals(this.peerId))continue;let o=xs.decode(s);if(this.#r(n,o)){await this.datastore.delete(t,e);continue}yield Si(n,o,this.peerId.equals(n)?1/0:this.maxAddressAge)}}async#e(e,t){try{let s=yc(e),n=await this.datastore.get(s,t),o=xs.decode(n);if(this.#r(e,o))throw await this.datastore.delete(s,t),new An;return{peerPB:o,peer:Si(e,o,this.maxAddressAge)}}catch(s){s.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",s)}}async#t(e,t,s,n){t.updated=Date.now();let o=xs.encode(t);return await this.datastore.put(yc(e),o,n),{peer:Si(e,t,this.maxAddressAge),previous:s?.peer,updated:s==null||!J4(t,s.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let s=t.updated<Date.now()-this.maxPeerAge,n=Date.now()-this.maxAddressAge,o=t.addresses.filter(i=>i.observed!=null&&i.observed>n);return s&&o.length===0}};var h2=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Yu(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let s of this.store.all(t))e(s)}async all(e){return dc(this.store.all(e))}async delete(e,t){let s=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{s()}}async has(e,t){let s=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),s?.()}}async get(e,t){let s=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{s?.()}}async getInfo(e,t){let s=await this.get(e,t);return{id:s.id,multiaddrs:s.addresses.map(({multiaddr:n})=>n)}}async save(e,t,s){let n=await this.store.getWriteLock(e,s);try{let o=await this.store.save(e,t,s);return this.#e(e,o),o.peer}finally{n?.()}}async patch(e,t,s){let n=await this.store.getWriteLock(e,s);try{let o=await this.store.patch(e,t,s);return this.#e(e,o),o.peer}finally{n?.()}}async merge(e,t,s){let n=await this.store.getWriteLock(e,s);try{let o=await this.store.merge(e,t,s);return this.#e(e,o),o.peer}finally{n?.()}}async consumePeerRecord(e,t,s){let n=Vs(t)?t:Vs(t?.expectedPeer)?t.expectedPeer:void 0,o=Vs(t)||t===void 0?s:t,i=await Or.openAndCertify(e,Qt.DOMAIN,o),a=Wr(i.publicKey.toCID());if(n?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",n,a),!1;let c=Qt.createFromProtobuf(i.payload),l;try{l=await this.get(a,o)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=Or.createFromProtobuf(l.peerRecordEnvelope),h=Qt.createFromProtobuf(u.payload);if(h.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",h.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},o),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function lb(r,e={}){return new h2(r,e)}var Xu=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};function bC(r){return r[Symbol.asyncIterator]!=null}function wC(r){if(bC(r))return(async()=>{for await(let e of r);})();for(let e of r);}var d2=wC;function xC(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],s=[];return{peek:()=>e.next(),push:n=>{s.push(n)},next:()=>s.length>0?{done:!1,value:s.shift()}:e.next(),[t](){return this}}}var Zu=xC;function vC(r){return r[Symbol.asyncIterator]!=null}function EC(r,e){let t=0;if(vC(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let s=Zu(r),{value:n,done:o}=s.next();if(o===!0)return(function*(){})();let i=e(n,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield n);for(let c of s)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield n);for(let c of s)a(c,t++)&&(yield c)})()}var io=EC;function SC(r){return r[Symbol.asyncIterator]!=null}function IC(r,e){return SC(r)?(async function*(){yield*(await dc(r)).sort(e)})():(function*(){yield*dc(r).sort(e)})()}var f2=IC;function _C(r){return r[Symbol.asyncIterator]!=null}function AC(r,e){return _C(r)?(async function*(){let t=0;if(!(e<1)){for await(let s of r)if(yield s,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let s of r)if(yield s,t++,t===e)return}})()}var p2=AC;var Qu=class{put(e,t,s){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:s,value:n}of e)await this.put(s,n,t),yield s}async*getMany(e,t={}){for await(let s of e)yield{key:s,value:await this.get(s,t)}}async*deleteMany(e,t={}){for await(let s of e)await this.delete(s,t),yield s}batch(){let e=[],t=[];return{put(s,n){e.push({key:s,value:n})},delete(s){t.push(s)},commit:async s=>{await d2(this.putMany(e,s)),e=[],await d2(this.deleteMany(t,s)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let s=this._all(e,t);if(e.prefix!=null){let n=e.prefix;s=io(s,o=>o.key.toString().startsWith(n))}if(Array.isArray(e.filters)&&(s=e.filters.reduce((n,o)=>io(n,o),s)),Array.isArray(e.orders)&&(s=e.orders.reduce((n,o)=>f2(n,o),s)),e.offset!=null){let n=0,o=e.offset;s=io(s,()=>n++>=o)}return e.limit!=null&&(s=p2(s,e.limit)),s}queryKeys(e,t){let s=this._allKeys(e,t);if(e.prefix!=null){let n=e.prefix;s=io(s,o=>o.toString().startsWith(n))}if(Array.isArray(e.filters)&&(s=e.filters.reduce((n,o)=>io(n,o),s)),Array.isArray(e.orders)&&(s=e.orders.reduce((n,o)=>f2(n,o),s)),e.offset!=null){let n=e.offset,o=0;s=io(s,()=>o++>=n)}return e.limit!=null&&(s=p2(s,e.limit)),s}};var Ju=class extends Qu{data;constructor(){super(),this.data=new Map}put(e,t,s){return s?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let s=this.data.get(e.toString());if(s==null)throw new Xu;return s}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[s,n]of this.data.entries())yield{key:new oo(s),value:n},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let s of this.data.keys())yield new oo(s),t?.signal?.throwIfAborted()}};Ze();Kr();ge();ce();function bc(r,e){let t,s=function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)};return s.start=()=>{},s.stop=()=>{clearTimeout(t)},s}var hb=we(ub(),1),CC=["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"],TC=CC.map(r=>new hb.Netmask(r));function m2(r){for(let e of TC)if(e.contains(r))return!0;return!1}function PC(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function kC(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),s=e[e.length-2].padStart(4,"0"),n=`${parseInt(s.substring(0,2),16)}.${parseInt(s.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return m2(n)}function DC(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function MC(r){let e=r.split(":"),t=e[e.length-1];return m2(t)}function OC(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^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(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Ii(r){if((0,Fe.isIPv4)(r))return m2(r);if(PC(r))return kC(r);if(DC(r))return MC(r);if((0,Fe.isIPv6)(r))return OC(r)}var Pe=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),Y=(r,e)=>({match:t=>{let s=t[0];return s?.code!==r||s.value==null||e!=null&&s.value!==e?!1:t.slice(1)}}),ne=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),St=(...r)=>({match:e=>{let t;for(let s of r){let n=s.match(e);n!==!1&&(t==null||n.length<t.length)&&(t=n)}return t??!1}}),ye=(...r)=>({match:e=>{for(let t of r){let s=t.match(e);if(s===!1)return!1;e=s}return e}});function Ae(...r){function e(n){if(n==null)return!1;let o=n.getComponents();for(let i of r){let a=i.match(o);if(a===!1)return!1;o=a}return o}function t(n){return e(n)!==!1}function s(n){let o=e(n);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:s}}var LC=Y(421),db=Ae(LC),t1=Y(54),r1=Y(55),s1=Y(56),y2=Y(53),Bj=Ae(t1,ne(Y(421))),Fj=Ae(r1,ne(Y(421))),Uj=Ae(s1,ne(Y(421))),Kj=Ae(St(y2,s1,t1,r1),ne(Y(421))),fb=ye(Y(4),ne(Y(43))),pb=ye(ne(Y(42)),Y(41),ne(Y(43))),b2=St(fb,pb),ao=St(b2,y2,t1,r1,s1),mb=Ae(St(b2,ye(St(y2,s1,t1,r1),ne(Y(421))))),w2=Ae(fb),x2=Ae(pb),Hj=Ae(b2),v2=ye(ao,Y(6)),xc=ye(ao,Y(273)),Es=Ae(ye(v2,ne(Y(421)))),zj=Ae(xc),E2=ye(xc,Pe(460),ne(Y(421))),n1=ye(xc,Pe(461),ne(Y(421))),RC=St(E2,n1),qj=Ae(E2),gb=Ae(n1),g2=St(ao,v2,xc,E2,n1),yb=St(ye(g2,Pe(477),ne(Y(421)))),vc=Ae(yb),bb=St(ye(g2,Pe(478),ne(Y(421))),ye(g2,Pe(448),ne(Y(449)),Pe(477),ne(Y(421)))),Ec=Ae(bb),wb=ye(xc,Pe(280),ne(Y(466)),ne(Y(466)),ne(Y(421))),S2=Ae(wb),xb=ye(n1,Pe(465),ne(Y(466)),ne(Y(466)),ne(Y(421))),I2=Ae(xb),e1=St(yb,bb,ye(v2,ne(Y(421))),ye(RC,ne(Y(421))),ye(ao,ne(Y(421))),wb,xb,Y(421)),$j=Ae(e1),NC=ye(e1,Pe(290),Y(421)),Sc=Ae(NC),BC=St(ye(e1,Pe(290),Pe(281),ne(Y(421))),ye(e1,Pe(281),ne(Y(421))),ye(Pe(281),ne(Y(421)))),_2=Ae(BC),FC=St(ye(ao,Y(6),Pe(480),ne(Y(421))),ye(ao,Pe(480),ne(Y(421)))),Gj=Ae(FC),UC=ye(ao,St(ye(Y(6,"443"),Pe(480)),ye(Y(6),Pe(443)),ye(Y(6),Pe(448),Pe(480)),ye(Pe(448),Pe(480)),Pe(448),Pe(443)),ne(Y(421))),Vj=Ae(UC),KC=St(ye(Y(777),ne(Y(421)))),Wj=Ae(KC),HC=St(ye(Y(400),ne(Y(421)))),jj=Ae(HC);var A2=class extends Map{metric;constructor(e){super();let{name:t,metrics:s}=e;this.metric=s.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function It(r){let{name:e,metrics:t}=r,s;return t!=null?s=new A2({name:e,metrics:t}):s=new Map,s}var vb=864e13;var zC=448,C2=449,qC=53,$C=54,GC=55,VC=56,o1=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=It({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=this.findHost(e);for(let s of this.mappings.values())if(s.domain===t)return!0;return!1}add(e,t){t.forEach(s=>{this.log("add DNS mapping %s to %s",s,e);let n=Ii(s)===!0;this.mappings.set(s,{domain:e,verified:n,expires:n?vb-Date.now():0,lastVerified:n?vb-Date.now():void 0})})}remove(e){let t=this.findHost(e),s=!1;for(let[n,o]of this.mappings.entries())o.domain===t&&(this.log("removing %s to %s DNS mapping %e",n,o.domain),this.mappings.delete(n),s=s||o.verified);return s}getAll(e){let t=[];for(let s=0;s<e.length;s++){let o=e[s].multiaddr.stringTuples(),i=o[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(o,c.domain)&&(e.splice(s,1),s--,t.push({multiaddr:G(`/${o.map(u=>[yi(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let s=0;s<e.length;s++)if(e[s][0]===zC&&e[s+1]?.[0]!==C2)return e.splice(s+1,0,[C2,t]),!0;return!1}confirm(e,t){let s=this.findHost(e),n=!1;for(let[o,i]of this.mappings.entries())i.domain===s&&(this.log("marking %s to %s DNS mapping as verified",o,i.domain),n=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return n}unconfirm(e,t){let s=this.findHost(e),n=!1;for(let[o,i]of this.mappings.entries())i.domain===s&&(this.log("removing verification of %s to %s DNS mapping",o,i.domain),n=n||i.verified,i.verified=!1,i.expires=Date.now()+t);return n}findHost(e){for(let t of e.stringTuples())if(t[0]===C2||t[0]===qC||t[0]===$C||t[0]===GC||t[0]===VC)return t[1]}};var T2=4,P2=41,k2=6,WC=273,i1=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=It({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=e.stringTuples();for(let s of this.mappings.values())for(let n of s)if(n.externalIp===t[0][1])return!0;return!1}add(e,t,s,n=t,o="tcp"){let i=`${e}-${t}-${o}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:s,externalPort:n,externalFamily:(0,Fe.isIPv4)(s)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=e.stringTuples(),s=t[0][1]??"",n=t[1][0]===k2?"tcp":"udp",o=parseInt(t[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===s&&u.externalPort===o&&u.protocol===n&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,s,o,n),i=i||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return i}getAll(e){let t=[];for(let{multiaddr:s}of e){let n=s.stringTuples(),o;if((n[0][0]===T2||n[0][0]===P2)&&n[1][0]===k2?o=`${n[0][1]}-${n[1][1]}-tcp`:(n[0][0]===T2||n[0][0]===P2)&&n[1][0]===WC&&(o=`${n[0][1]}-${n[1][1]}-udp`),o==null)continue;let i=this.mappings.get(o);if(i!=null)for(let a of i)n[0][0]=a.externalFamily===4?T2:P2,n[0][1]=a.externalIp,n[1][1]=`${a.externalPort}`,t.push({multiaddr:G(`/${n.map(c=>[yi(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let n=e.stringTuples()[0][1],o=!1;for(let i of this.mappings.values())for(let a of i)a.externalIp===n&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let s=e.stringTuples(),n=s[0][1]??"",o=s[1][0]===k2?"tcp":"udp",i=parseInt(s[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===i&&u.protocol===o&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,i,o),a=a||u.verified,u.verified=!1,u.expires=Date.now()+t)}return a}};function Eb(r){try{for(let{code:e,value:t}of r.getComponents())if(e!==42&&t!=null){if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}}catch{}return!1}function a1(r){try{for(let{code:e}of r.getComponents())if(e!==42)return e===4||e===41}catch{}return!1}function Ss(r){try{if(!a1(r))return!1;let[[,e]]=r.stringTuples();return e==null?!1:Ii(e)??!1}catch{}return!0}var jC={maxObservedAddresses:10},c1=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=It({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??jC.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Ss(e)||Eb(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:G(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let s=e.toString(),n=this.addresses.get(s)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.log("marking observed address %a as verified",s),this.addresses.set(s,n),o}};var YC=[4,41,53,54,55,56];function D2(r){try{for(let{code:e}of r.getComponents())if(e!==42)return YC.includes(e)}catch{}return!1}var XC={maxObservedAddresses:10},l1=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=It({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??XC.maxObservedAddresses}get(e,t){if(Ss(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let s=this.toKey(e),n=this.addresses.get(s);return n==null&&(n={verified:!D2(e),expires:0},this.addresses.set(s,n)),{multiaddr:e,verified:n.verified,type:"transport",expires:n.expires,lastVerified:n.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),s=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),s}confirm(e,t){let s=this.toKey(e),n=this.addresses.get(s)??{verified:!1,expires:0,lastVerified:0},o=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.addresses.set(s,n),o}unconfirm(e,t){let s=this.toKey(e),n=this.addresses.get(s)??{verified:!1,expires:0},o=n.verified;return n.verified=!1,n.expires=Date.now()+t,this.addresses.set(s,n),o}toKey(e){if(D2(e)){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}};var Sb=6e4,Ib={maxObservedAddresses:10,addressVerificationTTL:Sb*10,addressVerificationRetry:Sb*5},ZC=r=>r;function M2(r,e){let t=r.getPeerId();return t!=null&&$(t).equals(e)&&(r=r.decapsulate(G(`/p2p/${e.toString()}`))),r}var u1=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:s=[],announce:n=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=s.map(i=>i.toString()),this.announce=new Set(n.map(i=>i.toString())),this.appendAnnounce=new Set(o.map(i=>i.toString())),this.observed=new c1(e,t),this.dnsMappings=new o1(e,t),this.ipMappings=new i1(e,t),this.transportAddresses=new l1(e,t),this.announceFilter=t.announceFilter??ZC,this.observedAddressFilter=lc(1024),this.addressVerificationTTL=t.addressVerificationTTL??Ib.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??Ib.addressVerificationRetry,this._updatePeerStoreAddresses=bc(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>G(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>G(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>G(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=e.stringTuples(),s=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(s)||(this.observedAddressFilter.add(s),e=M2(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=M2(e,this.components.peerId);let s=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&s&&(s=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&s&&(s=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&s&&(s=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),s=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&s&&(s=!1)),s||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=M2(e,this.components.peerId);let s=!1;this.observed.has(e)&&!this.observed.remove(e)&&s&&(s=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&s&&(s=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&s&&(s=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&s&&(s=!1),s&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(s=>{if(!s.verified)return!1;let n=s.multiaddr.toString();return e.has(n)?!1:(e.add(n),!0)}).map(s=>s.multiaddr);return this.announceFilter(t.map(s=>{let n=G(s);return n.getComponents().pop()?.value===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(n=>{n.updateAnnounceAddrs(e)}),e.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(n=>this.transportAddresses.get(n,this.addressVerificationTTL)));let s=this.getAppendAnnounceAddrs();return s.length>0&&(this.components.transportManager.getListeners().forEach(n=>{n.updateAnnounceAddrs(s)}),t=t.concat(s.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(G(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,s,n=t,o="tcp"){this.ipMappings.add(e,t,s,n,o),this.observed.removePrefixed(`/ip${(0,Fe.isIPv4)(s)?4:6}/${s}/${o}/${n}`)}removePublicAddressMapping(e,t,s,n=t,o="tcp"){this.ipMappings.remove(G(`/ip${(0,Fe.isIPv4)(s)?4:6}/${s}/${o}/${n}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;let t=e.toOptions();if(t.family===6||t.host==="127.0.0.1"||Ii(t.host)===!0)return!1;let s=this.components.transportManager.getListeners(),n=[o=>vc.exactMatch(o)||Ec.exactMatch(o),o=>Es.exactMatch(o),o=>gb.exactMatch(o)];for(let o of n){if(!o(e))continue;let i=s.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&o(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>l.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.transport),!0}return!1}};X();var _b;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(_b||(_b={}));var h1=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},d1=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},_i=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Ic=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},f1=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},p1=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},m1=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},_c=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},g1=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},y1=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},b1=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},w1=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},x1=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},co=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},lo=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},v1=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},E1=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var O2=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,s]of Object.entries(e))this.components[t]=s;this.components.logger==null&&(this.components.logger=Ou())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Gl(t)).map(async t=>{await t[e]?.()}))}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")}},JC=["metrics","connectionProtector","dns"],e7=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Ab(r={}){let e=new O2(r);return new Proxy(e,{get(s,n,o){if(typeof n=="string"&&!e7.includes(n)){let i=e.components[n];if(i==null&&!JC.includes(n))throw new h1(`${n} not set`);return i}return Reflect.get(s,n,o)},set(s,n,o){return typeof n=="string"?e.components[n]=o:Reflect.set(s,n,o),!0}})}function Cb(r){let e={};for(let t of Object.values(r.components))for(let s of t7(t))e[s]=!0;for(let t of Object.values(r.components))for(let s of r7(t))if(e[s]!==!0)throw new d1(`Service "${s7(t)}" required capability "${s}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function t7(r){return Array.isArray(r?.[et])?r[et]:[]}function r7(r){return Array.isArray(r?.[ka])?r[ka]:[]}function s7(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function Tb(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async()=>!1,denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}X();var Pb=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},n7=new WeakMap;function o7({clearTimeout:r,setTimeout:e}={}){return(t,{value:s,signal:n}={})=>{if(n?.aborted)return Promise.reject(Pb());let o,i,a,c=r??clearTimeout,l=()=>{c(o),a(Pb())},u=()=>{n&&n.removeEventListener("abort",l)},h=new Promise((d,f)=>{i=()=>{u(),d(s)},a=f,o=(e??setTimeout)(i,t)});return n&&n.addEventListener("abort",l,{once:!0}),n7.set(h,()=>{c(o),o=null,i()}),h}}var i7=o7(),kb=i7;var S1=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},I1=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var _1=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new L2}async consume(e,t=1,s={}){let n=this.getKey(e),o=this._getKeySecDuration(s),i=this.memoryStorage.incrby(n,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(n,i.consumedPoints,this.blockDuration)),new S1("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await kb(a)}return i}penalty(e,t=1,s={}){let n=this.getKey(e),o=this._getKeySecDuration(s),i=this.memoryStorage.incrby(n,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,s={}){let n=this.getKey(e),o=this._getKeySecDuration(s),i=this.memoryStorage.incrby(n,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let s=t*1e3,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:n,isFirstInDuration:!1}}set(e,t,s=0){let n=(s>=0?s:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,s),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},L2=class{storage;constructor(){this.storage=new Map}incrby(e,t,s){let n=this.storage.get(e);if(n!=null){let o=n.expiresAt!=null?n.expiresAt.getTime()-new Date().getTime():-1;return n.expiresAt==null||o>0?(n.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,s)}return this.set(e,t,s)}set(e,t,s){let n=s*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,i),n>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},n),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};X();ce();function A1(r){if(Vs(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let s=e[0].getPeerId();t=s==null?void 0:$(s),e.forEach(n=>{if(!Js(n))throw new js("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(t!=null)throw new V("Multiaddrs must all have the same peer id or have no peer id")}else{let i=$(o);if(t?.equals(i)!==!0)throw new V("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(s=>!db.exactMatch(s)),{peerId:t,multiaddrs:e}}var a7=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Db(r,e){let t=r?.streams?.map(n=>n.protocol)??[],s=e?.closableProtocols??a7;if(!(t.filter(n=>n!=null&&!s.includes(n)).length>0))try{await r?.close(e)}catch(n){r?.abort(n)}}function Ac(r){try{let e;typeof r=="string"?e=G(r):e=r;let t=new Set([...e.getComponents().map(s=>s.name)]);if(!t.has("ipcidr")){let n=t.has("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(n)}return N0(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var C1=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(s=>Ac(s)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.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(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,s=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,s),t<=s)return;let n=new pr;for(let c of e){let l=c.remotePeer;if(!n.has(l)){n.set(l,0);try{let u=await this.peerStore.get(l);n.set(l,[...u.tags.values()].reduce((h,d)=>h+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,n),i=Math.max(t-s,0),a=[];for(let c of o)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>u.contains(c.remoteAddr.nodeAddress().address))||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await Db(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((s,n)=>{let o=s.timeline.open,i=n.timeline.open;return o<i?1:o>i?-1:0}).sort((s,n)=>s.direction==="outbound"&&n.direction==="inbound"?1:s.direction==="inbound"&&n.direction==="outbound"?-1:0).sort((s,n)=>s.streams.length>n.streams.length?1:s.streams.length<n.streams.length?-1:0).sort((s,n)=>{let o=t.get(s.remotePeer)??0,i=t.get(n.remotePeer)??0;return o>i?1:o<i?-1:0})}};var Mb="last-dial-failure",Ob="last-dial-success";var Lb=300,T1=100;X();X();Ze();X();Ze();X();var P1=class{deferred;signal;constructor(e){this.signal=e,this.deferred=fe(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Lt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function c7(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var k1=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=c7(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,J(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,s)=>t&&s.signal?.aborted===!0,!0)&&(this.controller.abort(new Lt),this.cleanup())}async join(e={}){let t=new P1(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ce(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Ai=class extends Xe{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=bc(this.emitEmpty.bind(this),1),this.emitIdle=bc(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new I1;let s=new k1(e,t);return this.enqueue(s),this.safeDispatchEvent("add"),this.tryToStartAnother(),s.join(t).then(n=>(this.safeDispatchEvent("completed",{detail:n}),this.safeDispatchEvent("success",{detail:{job:s,result:n}}),n)).catch(n=>{if(s.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===s){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:s,error:n}}),n})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Lt)}),this.clear()}async onEmpty(e){this.size!==0&&await er(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await er(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await er(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=dt({objectMode:!0}),s=c=>{c!=null?this.abort():this.clear(),t.end(c)},n=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{s(c.detail.error)},i=()=>{s()},a=()=>{s(new Lt("Queue aborted"))};this.addEventListener("completed",n),this.addEventListener("failure",o),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("failure",o),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),s()}}};var D1=class extends Ai{constructor(e={}){super({...e,sort:(t,s)=>t.options.priority>s.options.priority?-1:t.options.priority<s.options.priority?1:0})}};function Is(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function s(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let n=e.signal;return n.clear=s,n}Ze();ge();function Rb(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function R2(r){if(!a1(r))return!1;let{address:e}=r.nodeAddress();return Rb(e)}function l7(r,e){let t=Es.exactMatch(r.multiaddr),s=Es.exactMatch(e.multiaddr);if(t&&!s)return-1;if(!t&&s)return 1;let n=Ec.exactMatch(r.multiaddr),o=Ec.exactMatch(e.multiaddr);if(n&&!o)return-1;if(!n&&o)return 1;let i=vc.exactMatch(r.multiaddr),a=vc.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=_2.exactMatch(r.multiaddr),l=_2.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=S2.exactMatch(r.multiaddr),h=S2.exactMatch(e.multiaddr);if(u&&!h)return-1;if(!u&&h)return 1;let d=I2.exactMatch(r.multiaddr),f=I2.exactMatch(e.multiaddr);return d&&!f?-1:!d&&f?1:0}function u7(r,e){let t=R2(r.multiaddr),s=R2(e.multiaddr);return t&&!s?1:!t&&s?-1:0}function h7(r,e){let t=Ss(r.multiaddr),s=Ss(e.multiaddr);return t&&!s?1:!t&&s?-1:0}function d7(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function f7(r,e){let t=Sc.exactMatch(r.multiaddr),s=Sc.exactMatch(e.multiaddr);return t&&!s?1:!t&&s?-1:0}function Nb(r){return r.sort(l7).sort(d7).sort(f7).sort(h7).sort(u7)}async function N2(r,e,t){let s=t.depth??0;if(s>(t.maxRecursiveDepth??32))throw new E1("Max recursive depth reached");let n=!1,o=[];for(let i of Object.values(e))if(i.canResolve(r)){n=!0;let a=await i.resolve(r,t);for(let c of a)o.push(...await N2(c,e,{...t,depth:s+1}))}return n===!1&&o.push(r),o}var Cc={maxParallelDials:T1,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:zn}},M1=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Cc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Cc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Cc.dialTimeout,this.connections=t.connections??new pr,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Cc.resolvers,this.shutDownController=new AbortController,J(1/0,this.shutDownController.signal),this.queue=new D1({concurrency:t.maxParallelDials??Cc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",s=>{s.detail?.error.name!==Lt.name&&this.log.error("error in dial queue - %e",s.detail)})}start(){this.shutDownController=new AbortController,J(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:s,multiaddrs:n}=A1(e),o=Array.from(this.connections.values()).flat().find(a=>t.force===!0||a.limits!=null?!1:a.remotePeer.equals(s)?!0:n.find(c=>c.equals(a.remoteAddr)));if(o?.status==="open")return this.log("already connected to %a",o.remoteAddr),t.onProgress?.(new We("dial-queue:already-connected")),o;let i=this.queue.queue.find(a=>{if(s?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of n)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",s);for(let a of n)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new We("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Zo("Dial queue is full");return this.log("creating dial target for %p",s,n.map(a=>a.toString())),t.onProgress?.(new We("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new We("dial-queue:start-dial"));let c=Is([this.shutDownController.signal,a.signal]);J(1/0,c);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:s,priority:t.priority??K2,multiaddrs:new Set(n.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let s=e.peerId,n=e.multiaddrs,o=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",s);i||n.size>0;){c++,i=!1;let u=[],h=new Set(e.multiaddrs);n.clear(),this.log("calculating addrs to dial %p from %s",s,[...h]);let d=await this.calculateMultiaddrs(s,h,{...e,signal:t});for(let f of d){if(o.has(f.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",f.multiaddr,s);continue}u.push(f)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",s,u.map(f=>f.multiaddr.toString())),e?.onProgress?.(new We("dial-queue:calculated-addresses",u));for(let f of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Zo("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(f.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",f.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[Ob]:L(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",s,m)}return p}catch(p){if(this.log.error("dial failed to %a",f.multiaddr,p),o.add(f.multiaddr.toString()),s!=null)try{await this.components.peerStore.merge(s,{metadata:{[Mb]:L(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",s,m)}if(t.aborted)throw new Vr(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,s={}){let n=[...t].map(h=>({multiaddr:G(h),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Zo("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new _c("The dial request is blocked by gater.allowDialPeer");if(n.length===0){this.log("loading multiaddrs for %p",e);try{let h=await this.components.peerStore.get(e);n.push(...h.addresses),this.log("loaded multiaddrs for %p",e,n.map(({multiaddr:d})=>d.toString()))}catch(h){if(h.name!=="NotFoundError")throw h}}if(n.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let h=await this.components.peerRouting.findPeer(e,s);this.log("found multiaddrs for %p in the peer routing",e,n.map(({multiaddr:d})=>d.toString())),n.push(...h.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(h){h.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,h)}}}let o=(await Promise.all(n.map(async h=>{let d=await N2(h.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...s});return d.length===1&&d[0].equals(h.multiaddr)?h:d.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let h=`/p2p/${e.toString()}`;o=o.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(h),isCertified:d.isCertified}:d)}let i=o.filter(h=>{if(this.components.transportManager.dialTransportForMultiaddr(h.multiaddr)==null)return!1;let d=h.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let h of i){let d=h.multiaddr.toString(),f=a.get(d);if(f!=null){f.isCertified=f.isCertified||h.isCertified||!1;continue}a.set(d,h)}let c=[...a.values()];if(c.length===0)throw new b1("The dial request has no valid addresses");let l=[];for(let h of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(h.multiaddr)||l.push(h);let u=this.addressSorter==null?Nb(l):l.sort(this.addressSorter);if(u.length===0)throw new _c("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr:h})=>h.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:h})=>h.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let s=await this.calculateMultiaddrs(void 0,new Set(e.map(n=>n.toString())),t);return t.runOnLimitedConnection===!1?s.find(n=>!Sc.matches(n.multiaddr))!=null:!0}catch(s){this.log.trace("error calculating if multiaddr(s) were dialable",s)}return!1}};X();var O1=class extends Ai{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var qb=we(Hb(),1);var m7=Object.prototype.toString,g7=r=>m7.call(r)==="[object Error]",y7=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function H2(r){if(!(r&&g7(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:s}=r;return t==="Load failed"?s===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")?!0:y7.has(t)}var z2=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},zb=(r,e,t)=>{let s=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=s,r};async function q2(r,e){return new Promise((t,s)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let n=qb.default.operation(e),o=()=>{n.stop(),s(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",o),n.stop()};n.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof z2)throw c.originalError;if(c instanceof TypeError&&!H2(c))throw c;if(zb(c,a,e),await e.shouldRetry(c)||(n.stop(),s(c)),await e.onFailedAttempt(c),!n.retry(c))throw n.mainError()}catch(l){zb(l,a,e),i(),s(l)}}})})}var L1=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new O1({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",s=>{this.maybeReconnect(s.detail).catch(n=>{this.log.error("failed to maybe reconnect to %p - %e",s.detail,n)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);$b(t)&&(this.queue.has(e)||this.queue.add(async s=>{await q2(async n=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:s?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,n,this.retries,o),o}},{signal:s?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async s=>{this.log.error("failed to reconnect to %p - %e",e,s);let n={};[...t.tags.keys()].forEach(o=>{o.startsWith(xp)&&(n[o]=void 0)}),await this.peerStore.merge(e,{tags:n}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async s=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,s)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>$b(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(s=>{this.log.error(s)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function $b(r){for(let e of r.tags.keys())if(e.startsWith(xp))return!0;return!1}var K2=50,$2={maxConnections:Lb,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},R1=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??$2.maxConnections,this.maxConnections<1)throw new V("Connection Manager maxConnections must be greater than 0");this.connections=new pr,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(s=>Ac(s)),this.deny=(t.deny??[]).map(s=>Ac(s)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??$2.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new _1({points:t.inboundConnectionThreshold??$2.inboundConnectionThreshold,duration:1}),this.connectionPruner=new C1({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(s=>G(s))}),this.dialQueue=new M1(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??T1,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:zn},connections:this.connections}),this.reconnectQueue=new L1({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let s of t)e[s.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let s of t)for(let n of s.streams){let o=`${n.direction} ${n.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let s of this.connections.values())for(let n of s){let o={};for(let i of n.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[i,a]of Object.entries(o))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[s,n]of Object.entries(e)){n=n.sort((i,a)=>i-a);let o=Math.floor(n.length*.9);t[s]=n[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await By(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 Fy(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let s of t)e.push((async()=>{try{await s.close()}catch(n){this.log.error(n)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new V("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let s=t.remotePeer,n=!this.connections.has(s),o=this.connections.get(s)??[];o.push(t),this.connections.set(s,o),s.publicKey!=null&&s.type==="RSA"&&await this.peerStore.patch(s,{publicKey:s.publicKey}),n&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,s=t.remotePeer,o=(this.connections.get(s)??[]).filter(i=>i.id!==t.id);this.connections.set(s,o),o.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",s),this.connections.delete(s),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let s of this.connections.values())t=t.concat(s);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Tr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:s}=A1(e);if(this.peerId.equals(s))throw new Xo("Can not dial self");if(s!=null&&t.force!==!0){this.log("dial %p",s);let a=this.getConnections(s).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p as %a",s,a.remoteAddr),t.onProgress?.(new We("dial-queue:already-connected")),a}let n=await this.dialQueue.dial(e,{...t,priority:t.priority??K2});if(n.status!=="open")throw new Yo("Remote closed connection during opening");let o=this.connections.get(n.remotePeer);o==null&&(o=[],this.connections.set(n.remotePeer,o));let i=!1;for(let a of o)if(a.id===n.id&&(i=!0),t.force!==!0&&a.id!==n.id&&a.remoteAddr.equals(n.remoteAddr))return n.abort(new js("Duplicate multiaddr connection")),a;return i||o.push(n),n}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let s=this.connections.get(e)??[];await Promise.all(s.map(async n=>{try{await n.close(t)}catch(o){n.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(n=>n.contains(e.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(n=>n.contains(e.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let n=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(n,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,n),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(s=>G(s))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};X();Ze();var Ci=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let s=this.alpha(t,this.previousTime),n=e-this.movingAverage,o=s*n;this.movingAverage=s*e+(1-s)*this.movingAverage,this.variance=(1-s)*(this.variance+n*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+s*n}else this.movingAverage=e;this.previousTime=t}};var x7=1.2,v7=2,E7=5e3,S7=6e4,I7=5e3,N1=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??I7;this.success=new Ci(t),this.failure=new Ci(t),this.next=new Ci(t),this.failureMultiplier=e.failureMultiplier??v7,this.timeoutMultiplier=e.timeoutMultiplier??x7,this.minTimeout=e.minTimeout??E7,this.maxTimeout=e.maxTimeout??S7,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let s=AbortSignal.timeout(t),n=Is([e.signal,s]);return J(1/0,n,s),n.start=Date.now(),n.timeout=t,n}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};ot();var B1=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function ho(r,e){let t=Jc();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let s=r.source;r.source[Symbol.iterator]!=null?s=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(s=r.source[Symbol.asyncIterator]());let n=new W;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await Ce(s.next(),i?.signal);return c===!0?null:l}for(;n.byteLength<i.bytes;){let{value:c,done:l}=await Ce(s.next(),i?.signal);if(l===!0)throw new B1("unexpected end of input");n.append(c)}let a=n.sublist(0,i.bytes);return n.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(n.byteLength>0){let i=r.source;r.source=(async function*(){e?.yieldBytes===!1?yield n:yield*n,yield*i})()}return r}}}Ze();var _7=1e4,A7="1.0.0",C7="ping",T7="ipfs",Gb=32,P7=!0,F1=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??T7}/${C7}/${A7}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??_7,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??P7,this.timeout=new N1({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[et]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,J(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let s=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),n=await e.newStream(this.protocol,{signal:s,runOnLimitedConnection:!0}),o=ho(n);t=Date.now(),await Promise.all([o.write(Gr(Gb),{signal:s}),o.read({bytes:Gb,signal:s})]),e.rtt=Date.now()-t,await o.unwrap().close({signal:s})}catch(s){if(s.name!=="UnsupportedProtocolError")throw s;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};X();Se();var U1=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([s],n)=>({...n,cid:s.toString()}),getAttributesFromYieldedValue:(s,n)=>({...n,providers:[...Array.isArray(n.providers)?n.providers:[],s.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([s],n)=>({...n,cid:s.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([s],n)=>({...n,cid:s.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([s])=>({key:K(s,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([s])=>({key:K(s,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new _i("No content routers available");let s=this,n=new Gn;for await(let o of dn(...s.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!n.has(o.id)&&(n.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new _i("No content routers available");await Promise.all(this.routers.filter(s=>s.provide instanceof Function).map(async s=>{await s.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new _i("No content routers available");await Promise.all(this.routers.filter(s=>s.cancelReprovide instanceof Function).map(async s=>{await s.cancelReprovide(e,t)}))}async put(e,t,s){if(!this.isStarted())throw new Tr;await Promise.all(this.routers.filter(n=>n.put instanceof Function).map(async n=>{await n.put(e,t,s)}))}async get(e,t){if(!this.isStarted())throw new Tr;return Promise.any(this.routers.filter(s=>s.get instanceof Function).map(async s=>s.get(e,t)))}};X();var K1=globalThis.CustomEvent??Event;async function*G2(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let s=e.ordered??!1,n=new EventTarget,o=[],i=fe(),a=fe(),c=!1,l,u=!1;n.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(o.length===t&&(i=fe(),await i.promise),u)break;let m={done:!1};o.push(m),p().then(g=>{m.done=!0,m.ok=!0,m.value=g,n.dispatchEvent(new K1("task-complete"))},g=>{m.done=!0,m.err=g,n.dispatchEvent(new K1("task-complete"))})}c=!0,n.dispatchEvent(new K1("task-complete"))}catch(p){l=p,n.dispatchEvent(new K1("task-complete"))}});function h(){return s?o[0]?.done:!!o.find(p=>p.done)}function*d(){for(;o.length>0&&o[0].done;){let p=o[0];if(o.shift(),p.ok)yield p.value;else throw u=!0,i.resolve(),p.err;i.resolve()}}function*f(){for(;h();)for(let p=0;p<o.length;p++)if(o[p].done){let m=o[p];if(o.splice(p,1),p--,m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(h()||(a=fe(),await a.promise),l!=null||(s?yield*d():yield*f(),l!=null))throw l;if(c&&o.length===0)break}}Se();var H1=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([s],n)=>({...n,peer:s.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([s],n)=>({...n,key:K(s,"base36")}),getAttributesFromYieldedValue:(s,n)=>({...n,peers:[...Array.isArray(n.peers)?n.peers:[],s.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Ic("No peer routers available");if(e.toString()===this.peerId.toString())throw new f1("Should not try to find self");let s=this,n=dn(...this.routers.filter(o=>o.findPeer instanceof Function).map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(i){s.log.error(i)}})()));for await(let o of n)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),o;throw new An}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Ic("No peer routers available");let s=this,n=lc(1024);for await(let o of G2((async function*(){let i=dn(...s.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await s.findPeer(a.id,{...t,useCache:!1})}catch(c){s.log.error("could not find peer multiaddrs",c);return}return a}})()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!n.has(o.id.toMultihash().bytes)&&(n.add(o.id.toMultihash().bytes),yield o))}};Ze();var z1=class extends Xe{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,J(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,J(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Is([this.shutdownController.signal,e?.signal]);J(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=fe(),yield(await er(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,J(1/0,this.walkController.signal);let e=Is([this.walkController.signal,this.shutdownController.signal]);J(1/0,e);let t=Date.now(),s=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let n=Gr(32),o=Date.now();for await(let i of this.peerRouting.getClosestPeers(n,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-o,this.walkers),s++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Ce(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",n,this.walkers,s)}catch(n){this.log.error("random walk errored",n),this.safeDispatchEvent("walk:error",{detail:n})}this.log("no walkers left, ended walk")}).catch(n=>{this.log.error("random walk errored",n)}).finally(()=>{this.log("finished walk, found %d peers after %dms",s,Date.now()-t),this.walking=!1})}};X();var V2=32,W2=64,q1=class{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[s,n]of this.topologies)t[s]=n.size;return t}}),this.handlers=It({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),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)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new p1(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,s){if(this.handlers.has(e)&&s?.force!==!0)throw new m1(`Handler already registered for protocol ${e}`);let n=Su.bind({ignoreUndefined:!0})({maxInboundStreams:V2,maxOutboundStreams:W2},s);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},s)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new V("invalid topology");let s=`${(Math.random()*1e9).toString(36)}${Date.now()}`,n=this.topologies.get(e);return n==null&&(n=new Map,this.topologies.set(e,n)),n.set(s,t),s}unregister(e){for(let[t,s]of this.topologies.entries())s.has(e)&&(s.delete(e),s.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail,s={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(t,s).then(n=>{for(let o of n.protocols){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())a.filter?.has(t)!==!1&&(a.filter?.remove(t),a.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:s}=e.detail,n=(s?.protocols??[]).filter(o=>!t.protocols.includes(o));for(let o of n){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,s=e.detail.connection,n=e.detail.peerId;for(let o of t){let i=this.topologies.get(o);if(i!=null)for(let a of i.values())s.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(n)!==!0&&(a.filter?.add(n),a.onConnect?.(n,s))}}};X();var $1=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=It({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=It({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??_n.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new V("Transport must have a valid tag");if(this.transports.has(t))throw new V(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,s]of this.listeners)for(this.log("closing listeners for %s",t);s.length>0;){let n=s.pop();n!=null&&e.push(n.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let s=this.dialTransportForMultiaddr(e);if(s==null)throw new v1(`No transport available for address ${String(e)}`);return t?.onProgress?.(new We("transport-manager:selected-transport",s[Symbol.toStringTag])),s.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let s of t)e=[...e,...s.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Tr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(o=>{t.errors.set(o.toString(),new g1)});let s=[];for(let[o,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",o,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(o)??[];u==null&&(u=[],this.listeners.set(o,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let h=u.findIndex(d=>d===l);u.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),w2.matches(c)?t.ipv4.attempts++:x2.matches(c)&&t.ipv6.attempts++,s.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),w2.matches(c)&&t.ipv4.success++,x2.matches(c)&&t.ipv6.success++},h=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,h),t.errors.set(c.toString(),h),h}))}}let n=await Promise.allSettled(s);if(!(n.length>0&&n.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===_n.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new y1(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
|
|
11
|
+
${[...t.errors.entries()].map(([o,i])=>`
|
|
12
|
+
${o}: ${`${i.stack??i}`.split(`
|
|
13
|
+
`).join(`
|
|
14
|
+
`)}
|
|
15
|
+
`).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,s=e.ipv6.success===0;return t&&s}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let s=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let n=t.pop();n!=null&&s.push(n.close())}await Promise.all(s),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};X();var mt="/multistream/1.0.0";X();wr();ot();var G1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},V1=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},W1=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Jr(r,e={}){let t=ho(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Le(e.maxDataLength));let s=e?.lengthDecoder??as,n=e?.lengthEncoder??rr;return{read:async i=>{let a=-1,c=new W;for(;;){c.append(await t.read({...i,bytes:1}));try{a=s(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new G1("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new W1("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new V1("message length too long");return t.read({...i,bytes:a})},write:async(i,a)=>{await t.write(new W(n(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new W(...i.flatMap(l=>[n(l.byteLength),l]));await t.write(c,a)},unwrap:()=>t.unwrap()}}wr();ot();ge();X();ge();Se();var k7=L(`
|
|
16
|
+
`);async function fo(r,e,t){await r.write(e,t)}async function Vb(r,e,t){await r.writeV(e,t)}async function D7(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==k7[0])throw e.log.error("Invalid mss message - missing newline",t),new Yt("Missing newline");return t.sublist(0,-1)}async function tn(r,e){let t=await D7(r,e);return K(t.subarray())}async function Ti(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return M7(r,e[0],t);let s=Jr(r,{...t,maxDataLength:1024}),n=e.shift();if(n==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',mt,n);let o=L(`${mt}
|
|
17
|
+
`),i=L(`${n}
|
|
18
|
+
`);await Vb(s,[o,i],t),t.log.trace("select: reading multistream-select header");let a=await tn(s,t);if(t.log.trace('select: read "%s"',a),a===mt&&(t.log.trace("select: reading protocol response"),a=await tn(s,t),t.log.trace('select: read "%s"',a)),a===n)return{stream:s.unwrap(),protocol:n};for(let c of e){t.log.trace('select: write "%s"',c),await fo(s,L(`${c}
|
|
19
|
+
`),t),t.log.trace("select: reading protocol response");let l=await tn(s,t);if(t.log.trace('select: read "%s" for "%s"',l,c),l===c)return{stream:s.unwrap(),protocol:c}}throw new Cn("protocol selection failed")}function M7(r,e,t){let s=r.sink.bind(r),n=r.source,o=!1,i=!1,a=fe(),c=!1,l=!1,u=fe(),h=!1,d=!1,f=fe(),p=Jr({sink:s,source:n},{...t,maxDataLength:1024});r.sink=async w=>{let{sink:b}=p.unwrap();await b((async function*(){let x=!1;for await(let E of w){if(l&&await u.promise,c)yield E;else{l=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',mt,e,E.byteLength);let P=`${e}
|
|
20
|
+
`;yield new W(Uint8Array.from([19]),L(`${mt}
|
|
21
|
+
`),rr(P.length),L(P),E).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',mt,e,E.byteLength),c=!0,l=!1,u.resolve(),m().catch(T=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,T)})}x=!0}x||await m()})())};async function m(){if(i){t.log.trace("optimistic: already negotiating %s stream",e),await a.promise;return}i=!0;try{c||(t.log.trace("optimistic: doing send protocol for %s stream",e),await g()),h||(t.log.trace("optimistic: doing read protocol for %s stream",e),await y())}finally{i=!1,o=!0,a.resolve()}}async function g(){if(l){await u.promise;return}l=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',mt,e),await p.writeV([L(`${mt}
|
|
22
|
+
`),L(`${e}
|
|
23
|
+
`)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',mt,e)}finally{c=!0,l=!1,u.resolve()}}async function y(){if(d){await f.promise;return}d=!0;try{t.log.trace("optimistic: reading multistream select header");let w=await tn(p,t);if(t.log.trace('optimistic: read multistream select header "%s"',w),w===mt&&(w=await tn(p,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',w,e),w!==e)throw new Cn("protocol selection failed")}finally{h=!0,d=!1,f.resolve()}}if(r.source=(async function*(){await m(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*p.unwrap().source})(),r.closeRead!=null){let w=r.closeRead.bind(r);r.closeRead=async b=>{o||await m().catch(x=>{t.log.error("could not negotiate protocol before close read",x)}),await w(b)}}if(r.closeWrite!=null){let w=r.closeWrite.bind(r);r.closeWrite=async b=>{o||await m().catch(x=>{t.log.error("could not negotiate protocol before close write",x)}),await w(b)}}if(r.close!=null){let w=r.close.bind(r);r.close=async b=>{let x=[];l&&x.push(u.promise),d&&x.push(f.promise),x.length>0?await Ce(Promise.all(x),b?.signal):(o=!0,i=!1,a.resolve()),await w(b)}}return{stream:r,protocol:e}}ot();ge();async function Pi(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let s=Jr(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let n=await tn(s,t);if(t.log.trace('handle: read "%s"',n),n===mt){t.log.trace('handle: respond with "%s" for "%s"',mt,n),await fo(s,L(`${mt}
|
|
24
|
+
`),t),t.log.trace('handle: responded with "%s" for "%s"',mt,n);continue}if(e.includes(n))return t.log.trace('handle: respond with "%s" for "%s"',n,n),await fo(s,L(`${n}
|
|
25
|
+
`),t),t.log.trace('handle: responded with "%s" for "%s"',n,n),{stream:s.unwrap(),protocol:n};if(n==="ls"){let o=new W(...e.map(i=>sr.single(L(`${i}
|
|
26
|
+
`))),L(`
|
|
27
|
+
`));t.log.trace('handle: respond with "%s" for %s',e,n),await fo(s,o,t),t.log.trace('handle: responded with "%s" for %s',e,n);continue}t.log.trace('handle: respond with "na" for "%s"',n),await fo(s,L(`na
|
|
28
|
+
`),t),t.log('handle: responded with "na" for "%s"',n)}}ce();Ze();X();Ze();var O7=500,X2=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;constructor(e,t){this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.status="open",this.timeline=t.maConn.timeline,this.encryption=t.encryption,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this.tags=[],t.muxerFactory!=null&&(this.multiplexer=t.muxerFactory.protocol,this.muxer=t.muxerFactory.createStreamMuxer({direction:this.direction,log:this.log,onIncomingStream:s=>{this.onIncomingStream(s)}}),Promise.all([this.muxer.sink(this.maConn.source),this.maConn.sink(this.muxer.source)]).catch(s=>{this.log.error("error piping data through muxer - %e",s)}))}[Symbol.toStringTag]="Connection";[yy]=!0;get streams(){return this.muxer?.streams??[]}newStream=async(e,t={})=>{if(this.status==="closing")throw new Nl("the connection is being closed");if(this.status==="closed")throw new Yo("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Pa("Cannot open protocol stream on limited connection");if(this.muxer==null)throw new co("Connection is not multiplexed");this.log.trace("starting new stream for protocols %s",e);let s=await this.muxer.newStream();this.log.trace("started new stream %s for protocols %s",s.id,e);try{if(t.signal==null){s.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);J(1/0,c),t={...t,signal:c}}s.log.trace("selecting protocol from protocols %s",e);let{stream:n,protocol:o}=await Ti(s,e,{...t,log:s.log,yieldBytes:!0});s.log("selected protocol %s",o);let i=R7(o,this.components.registrar,t),a=Yb(o,"outbound",this);if(a>=i){let c=new Qo(`Too many outbound protocol streams for protocol "${o}" - ${a}/${i}`);throw s.abort(c),c}return await this.components.peerStore.merge(this.remotePeer,{protocols:[o]}),s.source=n.source,s.sink=n.sink,s.protocol=o,n.closeWrite!=null&&(s.closeWrite=n.closeWrite),n.closeRead!=null&&(s.closeRead=n.closeRead),n.close!=null&&(s.close=n.close),this.components.metrics?.trackProtocolStream(s,this),s.direction="outbound",s}catch(n){throw this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,n),s.timeline.close==null&&s.abort(n),n}};onIncomingStream(e){let t=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);J(1/0,t),Promise.resolve().then(async()=>{let s=this.components.registrar.getProtocols(),{stream:n,protocol:o}=await Pi(e,s,{signal:t,log:e.log,yieldBytes:!1});this.log("incoming %s stream opened",o);let i=L7(o,this.components.registrar);if(Yb(o,"inbound",this)===i){let u=new ql(`Too many inbound protocol streams for protocol "${o}" - limit ${i}`);throw e.abort(u),u}e.source=n.source,e.sink=n.sink,e.protocol=o,n.closeWrite!=null&&(e.closeWrite=n.closeWrite),n.closeRead!=null&&(e.closeRead=n.closeRead),n.close!=null&&(e.close=n.close),await this.components.peerStore.merge(this.remotePeer,{protocols:[o]},{signal:t}),this.components.metrics?.trackProtocolStream(e,this);let{handler:c,options:l}=this.components.registrar.getHandler(o);if(this.limits!=null&&l.runOnLimitedConnection!==!0)throw new Pa("Cannot open protocol stream on limited connection");await c({connection:this,stream:e})}).catch(async s=>{this.log.error("error handling incoming stream id %s - %e",e.id,s),e.abort(s)})}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(O7);J(1/0,t),e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this.muxer?.close(e),await this.maConn.close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.muxer?.abort(e),this.maConn.abort(e),this.status="closed",this.timeline.close=Date.now())}};function Xb(r,e){return new X2(r,e)}function L7(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return V2}function R7(r,e,t={}){try{let{options:s}=e.getHandler(r);if(s.maxOutboundStreams!=null)return s.maxOutboundStreams}catch(s){if(s.name!=="UnhandledProtocolError")throw s}return t.maxOutboundStreams??W2}function Yb(r,e,t){let s=0;return t.streams.forEach(n=>{n.direction===e&&n.protocol===r&&s++}),s}var j1=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=It({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(s=>{this.connectionEncrypters.set(s.protocol,s)}),this.streamMuxers=It({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(s=>{this.streamMuxers.set(s.protocol,s)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let s=this.components.connectionGater[e];if(s==null)return;if(await s.apply(this.components.connectionGater,t)===!0)throw new w1(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Is([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return J(1/0,t),t}async upgradeInbound(e,t){let s=!1,n=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),s=await Ce(this.components.connectionManager.acceptIncomingConnection(e),n),!s)throw new x1("Connection denied");await Ce(this.shouldBlockConnection("denyInboundConnection",e),n),await this._performUpgrade(e,"inbound",{...t,signal:n})}catch(o){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[o.name??"Error"]:!0}),o}finally{n.clear(),s&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let s=e.remoteAddr.getPeerId(),n;s!=null&&(n=$(s),await Ce(this.shouldBlockConnection("denyOutboundConnection",n,e),t.signal));let o="outbound";return t.initiator===!1&&(o="inbound"),await this._performUpgrade(e,o,t)}catch(s){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[s.name??"Error"]:!0}),s}}async _performUpgrade(e,t,s){let n,o,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let u=e;if(s?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),u=await d.protect(e,s))}try{if(n=u,s?.skipEncryption!==!0){s?.onProgress?.(new We(`upgrader:encrypt-${t}-connection`)),{conn:n,remotePeer:o,protocol:c,streamMuxer:a}=await(t==="inbound"?this._encryptInbound(u,s):this._encryptOutbound(u,s));let d={...u,...n};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,d)}else{let d=e.remoteAddr.getPeerId();if(d==null)throw new js(`${t} connection that skipped encryption must have a peer id`);let f=$(d);c="native",o=f}if(o.equals(this.components.peerId)){let d=new Xo("Can not dial self");throw e.abort(d),d}if(i=n,s?.muxerFactory!=null)a=s.muxerFactory;else if(a==null&&this.streamMuxers.size>0){s?.onProgress?.(new We(`upgrader:multiplex-${t}-connection`));let d=await(t==="inbound"?this._multiplexInbound({...u,...n},this.streamMuxers,s):this._multiplexOutbound({...u,...n},this.streamMuxers,s));a=d.muxerFactory,i=d.stream}}catch(d){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e);let h=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:o,limits:s?.limits});return h.log("successfully upgraded %s connection",t),h}_createConnection(e){let{id:t,cryptoProtocol:s,direction:n,maConn:o,upgradedConn:i,remotePeer:a,muxerFactory:c,limits:l}=e,u,h=o.timeline;return o.timeline=new Proxy(h,{set:(...d)=>(d[1]==="close"&&d[2]!=null&&h.close==null&&(async()=>{try{u.status==="open"&&await u.close()}catch(f){u.log.error("error closing connection after timeline close %e",f)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(f=>{u.log.error("error thrown while dispatching connection:close event %e",f)}),Reflect.set(...d))}),o.timeline.upgraded=Date.now(),u=Xb(this.components,{id:t,maConn:i,remotePeer:a,direction:n,muxerFactory:c,encryption:s,limits:l,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout}),this.events.safeDispatchEvent("connection:open",{detail:u}),u}async _encryptInbound(e,t){let s=Array.from(this.connectionEncrypters.keys());try{let{stream:n,protocol:o}=await Pi(e,s,{...t,log:e.log}),i=this.connectionEncrypters.get(o);if(i==null)throw new lo(`no crypto module found for ${o}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,o),{...await i.secureInbound(n,t),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,n),new lo(n.message)}}async _encryptOutbound(e,t){let s=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",s);let{stream:n,protocol:o}=await Ti(e,s,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(o);if(i==null)throw new lo(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,o),{...await i.secureOutbound(n,t),protocol:o}}catch(n){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,n),new lo(n.message)}}async _multiplexOutbound(e,t,s){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:i}=await Ti(e,n,{...s,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new co(String(o))}}async _multiplexInbound(e,t,s){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:i}=await Pi(e,n,{...s,log:e.log}),a=t.get(i);return{stream:o,muxerFactory:a}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new co(String(o))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var rn=we(re("node:process"),1);var Y1="2.10.0",X1="js-libp2p";function Qb(r,e){let t="node",s=rn.default.versions.node;return rn.default.versions.deno!=null&&(t="deno",s=rn.default.versions.deno),rn.default.versions.bun!=null&&(t="bun",s=rn.default.versions.bun),rn.default.versions.electron!=null&&(t="electron",s=rn.default.versions.electron),`${r??X1}/${e??Y1} ${t}/${s.replaceAll("v","")}`}var Z1=class extends Xe{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Xe,s=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=s(l),h=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||h},J(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Ou(),this.log=this.logger.forComponent("libp2p"),this.services={};let n=e.nodeInfo?.name??X1,o=e.nodeInfo?.version??Y1,i=this.components=Ab({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:n,version:o,userAgent:e.nodeInfo?.userAgent??Qb(n,o)},logger:this.logger,events:t,datastore:e.datastore??new Ju,connectionGater:Tb(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",lb(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(h=>h.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new j1(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new $1(this.components,e.transportManager)),this.configureComponent("connectionManager",new R1(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new F1(this.components,e.connectionMonitor)),this.configureComponent("registrar",new q1(this.components)),this.configureComponent("addressManager",new u1(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new H1(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new U1(this.components,{routers:c})),this.configureComponent("randomWalk",new z1(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],h=u(this.components);if(h==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=h,this.configureComponent(l,h),h[bp]!=null&&(this.log("registering service %s for content routing",l),c.push(h[bp])),h[wp]!=null&&(this.log("registering service %s for peer routing",l),a.push(h[wp])),h[Ta]!=null&&(this.log("registering service %s for peer discovery",l),h[Ta].addEventListener?.("peer",d=>{this.#e(d)}))}Cb(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Gn;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,s={}){if(t==null)throw new V("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new V("no protocols were provided to open a stream");return(await this.dial(e,s)).newStream(t,s)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Js(e)&&(e=$(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let s=Ye([L("/pk/"),e.toMultihash().bytes]),n=await this.contentRouting.get(s,t),o=Je(n);return await this.peerStore.patch(e,{publicKey:o},t),o}async handle(e,t,s){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.handle(n,t,s)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async s=>{await this.components.registrar.unhandle(s,t)}))}async register(e,t,s){return this.components.registrar.register(e,t,s)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(s=>{this.log.error(s)})}};async function Jb(r={}){r.privateKey??=await my("Ed25519");let e=new Z1({...await M4(r),peerId:vp(r.privateKey)});return r.start!==!1&&await e.start(),e}var hw=we(re("net"),1);X();var uw=we(re("net"),1);X();var tw=we(re("node:os"),1);function ew(r){return!!(r.startsWith("169.254.")||r.toLowerCase().startsWith("fe80"))}var N7={4:"IPv4",6:"IPv6"};function B7(r){return["0.0.0.0","::"].includes(r)}function F7(r){let e=[],t=tw.default.networkInterfaces();for(let[,s]of Object.entries(t))if(s!=null)for(let n of s)ew(n.address)||n.family===N7[r]&&e.push(n.address);return e}function rw(r,e){if(r==null)return[];let t=r.toOptions();if(B7(t.host)){let s=[];for(let n of F7(t.family))s.push(G(`/ip${t.family}/${n}/${t.transport}/${e??t.port}`));return s}return[G(`/ip${t.family}/${t.host}/${t.transport}/${e??t.port}`)]}Ze();var Z2=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Q2=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},sw=r=>globalThis.DOMException===void 0?new Q2(r):new DOMException(r),nw=r=>{let e=r.reason===void 0?sw("This operation was aborted."):r.reason;return e instanceof Error?e:sw(e)};function J2(r,e){let{milliseconds:t,fallback:s,message:n,customTimers:o={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:f}=e;f.aborted&&h(nw(f)),a=()=>{h(nw(f))},f.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,h);return}let d=new Z2;i=o.setTimeout.call(void 0,()=>{if(s){try{u(s())}catch(f){h(f)}return}typeof r.cancel=="function"&&r.cancel(),n===!1?u():n instanceof Error?h(n):(d.message=n??`Promise timed out after ${t} milliseconds`,h(d))},t),(async()=>{try{u(await r)}catch(f){h(f)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},l}var U7=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function K7(r,e,t){let s,n=new Promise((o,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=U7(r),h=(...f)=>{let p=t.multiArgs?f:f[0];t.filter&&!t.filter(p)||(c.push(p),t.count===c.length&&(s(),o(c)))},d=f=>{s(),i(f)};s=()=>{for(let f of a)u(f,h);for(let f of t.rejectionEvents)u(f,d)};for(let f of a)l(f,h);for(let f of t.rejectionEvents)l(f,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&o(c)});if(n.cancel=s,typeof t.timeout=="number"){let o=J2(n,{milliseconds:t.timeout});return o.cancel=s,o}return n}function em(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let s=K7(r,e,t),n=s.then(o=>o[0]);return n.cancel=s.cancel,n}X();X();function ow(r,e){if(typeof r!="string")throw new V(`invalid ip provided: ${r}`);if(typeof e=="string"&&(e=parseInt(e)),isNaN(e))throw new V(`invalid port provided: ${e}`);if((0,Fe.isIPv4)(r))return G(`/ip4/${r}/tcp/${e}`);if((0,Fe.isIPv6)(r))return G(`/ip6/${r}/tcp/${e}`);throw new V(`invalid ip:port for creating a multiaddr: ${r}:${e}`)}function iw(r){if(z7(r))return(async function*(){let e=r.getReader();try{for(;;){let{done:t,value:s}=await e.read();if(t)return;yield s}}finally{e.releaseLock()}})();if(H7(r))return r;throw new Error("unknown stream")}function H7(r){return r[Symbol.asyncIterator]!=null}function z7(r){return typeof r?.getReader=="function"}function aw(r){return async e=>{let t=async()=>{q7(e)&&await e.return(void 0)},s,n,o=y=>{s=y,t().catch(w=>{w=new AggregateError([s,w],"The Writable emitted an error, additionally an error occurred while ending the Source")}).finally(()=>{n?.(y)})},i,a=!1,c=()=>{a=!0,i?.()},l,u=!1,h=()=>{u=!0,l?.()},d,f=()=>{d?.()},p=async()=>new Promise((y,w)=>{i=d=y,n=w,r.once("drain",f)}),m=async()=>(await t(),new Promise((y,w)=>{if(a||u||s!=null){y();return}l=i=y,n=w})),g=()=>{r.removeListener("error",o),r.removeListener("close",c),r.removeListener("finish",h),r.removeListener("drain",f)};r.once("error",o),r.once("close",c),r.once("finish",h);try{for await(let y of e){if(!r.writable||r.destroyed||s!=null)break;r.write(y)||await p()}}catch(y){s==null&&r.destroy(y),s=y}try{if(r.writable&&r.end(),await m(),s!=null)throw s}finally{g()}}}function q7(r){return r.return!=null}function tm(r){return{sink:aw(r),source:iw(r)}}var cw=we(re("os"),1),lw=we(re("path"),1);function ki(r,e={}){let t=r.getPath();if(t!=null)return cw.default.platform()==="win32"?{path:lw.default.join("\\\\.\\pipe\\",t)}:{path:t};let s=r.toOptions();return{...e,...s,ipv6Only:s.family===6}}var Q1=(r,e)=>{let t,s=e.direction,n=e.metrics,o=e.metricPrefix??"",i=e.socketInactivityTimeout??12e4,a=e.socketCloseTimeout??500,c=!1,l=!1;e.listeningAddr?.getPath()!=null&&(e.remoteAddr=e.listeningAddr),e.remoteAddr?.getPath()!=null&&(e.localAddr=e.remoteAddr),r.on("error",g=>{l=!0,c||(m.log.error("%s socket error - %e",s,g),n?.increment({[`${o}error`]:!0})),r.destroy(),m.timeline.close=Date.now()});let u;if(e.remoteAddr!=null)u=e.remoteAddr;else{if(r.remoteAddress==null||r.remotePort==null)throw new V("Could not determine remote address or port");u=ow(r.remoteAddress,r.remotePort)}let h=ki(u),d=h.path??`${h.host??""}:${h.port??""}`,{sink:f,source:p}=tm(r);r.setTimeout(i),r.once("timeout",()=>{c=!0,m.log("%s %s socket read timeout",s,d),n?.increment({[`${o}timeout`]:!0}),r.destroy(new Vr),m.timeline.close=Date.now()}),r.once("close",()=>{!c&&!l&&(m.log("%s %s socket close",s,d),n?.increment({[`${o}close`]:!0})),r.destroy(),m.timeline.close=Date.now()}),r.once("end",()=>{m.log("%s %s socket end",s,d),n?.increment({[`${o}end`]:!0})});let m={async sink(g){try{await f((async function*(){for await(let y of g)y instanceof Uint8Array?yield y:yield y.subarray()})())}catch(y){y.type!=="aborted"&&m.log.error("%s %s error in sink - %e",s,d,y)}r.end()},source:p,remoteAddr:u,timeline:{open:Date.now()},async close(g={}){if(r.closed){m.log("the %s %s socket is already closed",s,d);return}if(r.destroyed){m.log("the %s %s socket is already destroyed",s,d);return}if(t!=null)return t.promise;try{t=fe(),r.end();let y=$7(r),w=g.signal??AbortSignal.timeout(a);r.writableLength>0&&(m.log("%s %s draining socket",s,d),await er(y,"drain",w,{errorEvent:"error"}),m.log("%s %s socket drained",s,d)),await Promise.all([er(y,"close",w,{errorEvent:"error"}),r.destroy()])}catch(y){this.abort(y)}finally{t.resolve()}},abort:g=>{m.log("%s %s socket abort due to error - %e",s,d,g),r.destroy(),m.timeline.close=Date.now()},log:e.logger.forComponent("libp2p:tcp:connection")};return m};function $7(r){return{addEventListener:(t,s)=>{r.addListener(t,s)},removeEventListener:(t,s)=>{r.removeListener(t,s)}}}var ut;(function(r){r[r.INACTIVE=0]="INACTIVE",r[r.ACTIVE=1]="ACTIVE",r[r.PAUSED=2]="PAUSED"})(ut||(ut={}));var J1=class extends Xe{context;server;sockets=new Set;status={code:ut.INACTIVE};metrics;addr;log;shutdownController;constructor(e){if(super(),this.context=e,e.keepAlive=e.keepAlive??!0,e.noDelay=e.noDelay??!0,this.shutdownController=new AbortController,J(1/0,this.shutdownController.signal),this.log=e.logger.forComponent("libp2p:tcp:listener"),this.addr="unknown",this.server=uw.default.createServer(e,this.onSocket.bind(this)),e.maxConnections!==void 0&&(this.server.maxConnections=e.maxConnections),e.closeServerOnMaxConnections!=null&&e.closeServerOnMaxConnections.closeAbove<e.closeServerOnMaxConnections.listenBelow)throw new V("closeAbove must be >= listenBelow");e.metrics?.registerMetricGroup("libp2p_tcp_inbound_connections_total",{label:"address",help:"Current active connections in TCP listener",calculate:()=>({[this.addr]:this.sockets.size})}),this.metrics={status:e.metrics?.registerMetricGroup("libp2p_tcp_listener_status_info",{label:"address",help:"Current status of the TCP listener socket"}),errors:e.metrics?.registerMetricGroup("libp2p_tcp_listener_errors_total",{label:"address",help:"Total count of TCP listener errors by type"}),events:e.metrics?.registerMetricGroup("libp2p_tcp_listener_events_total",{label:"address",help:"Total count of TCP listener events by type"})},this.server.on("listening",()=>{let t=this.server.address();t==null?this.addr="unknown":typeof t=="string"?this.addr=t:this.addr=`${t.address}:${t.port}`,this.metrics.status?.update({[this.addr]:ut.ACTIVE}),this.safeDispatchEvent("listening")}).on("error",t=>{this.metrics.errors?.increment({[`${this.addr} listen_error`]:!0}),this.safeDispatchEvent("error",{detail:t})}).on("close",()=>{this.metrics.status?.update({[this.addr]:this.status.code}),this.status.code!==ut.PAUSED&&this.safeDispatchEvent("close")}).on("drop",()=>{this.metrics.events?.increment({[`${this.addr} drop`]:!0})})}onSocket(e){if(this.metrics.events?.increment({[`${this.addr} connection`]:!0}),this.status.code!==ut.ACTIVE)throw e.destroy(),new Tr("Server is not listening yet");let t;try{t=Q1(e,{listeningAddr:this.status.listeningAddr,socketInactivityTimeout:this.context.socketInactivityTimeout,socketCloseTimeout:this.context.socketCloseTimeout,metrics:this.metrics?.events,metricPrefix:`${this.addr} `,logger:this.context.logger,direction:"inbound"})}catch(s){this.log.error("inbound connection failed",s),this.metrics.errors?.increment({[`${this.addr} inbound_to_connection`]:!0}),e.destroy();return}this.log("new inbound connection %s",t.remoteAddr),this.sockets.add(e),this.context.upgrader.upgradeInbound(t,{signal:this.shutdownController.signal}).then(()=>{this.log("inbound connection upgraded %s",t.remoteAddr),e.once("close",()=>{this.sockets.delete(e),this.context.closeServerOnMaxConnections!=null&&this.sockets.size<this.context.closeServerOnMaxConnections.listenBelow&&this.resume().catch(s=>{this.log.error("error attempting to listen server once connection count under limit",s),this.context.closeServerOnMaxConnections?.onListenError?.(s)})}),this.context.closeServerOnMaxConnections!=null&&this.sockets.size>=this.context.closeServerOnMaxConnections.closeAbove&&this.pause()}).catch(async s=>{this.log.error("inbound connection upgrade failed",s),this.metrics.errors?.increment({[`${this.addr} inbound_upgrade`]:!0}),this.sockets.delete(e),t.abort(s)})}getAddrs(){if(this.status.code===ut.INACTIVE)return[];let e=this.server.address();return e==null?[]:typeof e=="string"?[G(`/unix/${encodeURIComponent(e)}`)]:rw(this.status.listeningAddr,e.port)}updateAnnounceAddrs(){}async listen(e){if(this.status.code===ut.ACTIVE||this.status.code===ut.PAUSED)throw new zl("server is already listening");try{this.status={code:ut.ACTIVE,listeningAddr:e,netConfig:ki(e,this.context)},await this.resume()}catch(t){throw this.status={code:ut.INACTIVE},t}}async close(){let e=[];this.server.listening&&e.push(em(this.server,"close")),this.pause(!0),this.shutdownController.abort(),this.sockets.forEach(t=>{t.readable&&(e.push(em(t,"close")),t.destroy())}),await Promise.all(e)}async resume(){if(this.server.listening||this.status.code===ut.INACTIVE)return;let e=this.status.netConfig;await new Promise((t,s)=>{this.server.once("error",s),this.server.listen(e,t)}),this.status={...this.status,code:ut.ACTIVE},this.log("listening on %s",this.server.address())}pause(e=!1){if(!this.server.listening&&this.status.code===ut.PAUSED&&e){this.status={code:ut.INACTIVE};return}!this.server.listening||this.status.code!==ut.ACTIVE||(this.log("closing server on %s",this.server.address()),this.status=e?{code:ut.INACTIVE}:{...this.status,code:ut.PAUSED},this.server.close())}};var eh=class{opts;metrics;components;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:tcp"),this.opts=t,this.components=e,e.metrics!=null&&(this.metrics={events:e.metrics.registerCounterGroup("libp2p_tcp_dialer_events_total",{label:"event",help:"Total count of TCP dialer events by type"}),errors:e.metrics.registerCounterGroup("libp2p_tcp_dialer_errors_total",{label:"event",help:"Total count of TCP dialer events by type"})})}[Ly]=!0;[Symbol.toStringTag]="@libp2p/tcp";[et]=["@libp2p/transport"];async dial(e,t){t.keepAlive=t.keepAlive??!0,t.noDelay=t.noDelay??!0;let s=await this._connect(e,t),n;try{n=Q1(s,{remoteAddr:e,socketInactivityTimeout:this.opts.outboundSocketInactivityTimeout,socketCloseTimeout:this.opts.socketCloseTimeout,metrics:this.metrics?.events,logger:this.components.logger,direction:"outbound"})}catch(o){throw this.metrics?.errors.increment({outbound_to_connection:!0}),s.destroy(o),o}try{return this.log("new outbound connection %s",n.remoteAddr),await t.upgrader.upgradeOutbound(n,t)}catch(o){throw this.metrics?.errors.increment({outbound_upgrade:!0}),this.log.error("error upgrading outbound connection",o),n.abort(o),o}}async _connect(e,t){t.signal.throwIfAborted(),t.onProgress?.(new We("tcp:open-connection"));let s;return new Promise((n,o)=>{let i=Date.now(),a=ki(e,{...this.opts.dialOpts??{},...t});this.log("dialing %a",e),s=hw.default.connect(a);let c=f=>{this.log.error("dial to %a errored - %e",e,f);let p=a.path??`${a.host??""}:${a.port}`;f.message=`connection error ${p}: ${f.message}`,this.metrics?.events.increment({error:!0}),d(f)},l=()=>{this.log("connection timeout %a",e),this.metrics?.events.increment({timeout:!0});let f=new Vr(`Connection timeout after ${Date.now()-i}ms`);s.emit("error",f)},u=()=>{this.log("connection opened %a",e),this.metrics?.events.increment({connect:!0}),d()},h=()=>{this.log("connection aborted %a",e),this.metrics?.events.increment({abort:!0}),d(new Lt)},d=f=>{if(s.removeListener("error",c),s.removeListener("timeout",l),s.removeListener("connect",u),t.signal!=null&&t.signal.removeEventListener("abort",h),f!=null){o(f);return}n(s)};s.on("error",c),s.on("timeout",l),s.on("connect",u),t.signal.addEventListener("abort",h)}).catch(n=>{throw s?.destroy(),n})}createListener(e){return new J1({...this.opts.listenOpts??{},...e,maxConnections:this.opts.maxConnections,backlog:this.opts.backlog,closeServerOnMaxConnections:this.opts.closeServerOnMaxConnections,socketInactivityTimeout:this.opts.inboundSocketInactivityTimeout,socketCloseTimeout:this.opts.socketCloseTimeout,metrics:this.components.metrics,logger:this.components.logger})}listenFilter(e){return e.filter(t=>Es.exactMatch(t)||t.toString().startsWith("/unix/"))}dialFilter(e){return this.listenFilter(e)}};function dw(r={}){return e=>new eh(e,r)}ft();X();ce();function rm(){let r=fe(),e=!1;return{sink:async t=>{if(e)throw new Error("already piped");e=!0,r.resolve(t)},source:(async function*(){yield*await r.promise})()}}function fw(){let r=rm(),e=rm();return[{source:r.source,sink:e.sink},{source:e.source,sink:r.sink}]}nt();var Di=!!globalThis.process?.env?.DUMP_SESSION_KEYS;var ns=we(re("node:crypto"),1),Th=we(xw(),1);var cT=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,vw=cT?uT:lT;function lT(r=0){return new Uint8Array(r)}function uT(r=0){let e=Buffer.allocUnsafe(r);return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Ew=Uint8Array.from([0,97,115,109,1,0,0,0,1,43,8,96,2,127,127,0,96,1,127,0,96,1,127,1,127,96,2,127,127,1,127,96,0,0,96,3,127,127,127,0,96,4,127,127,127,127,0,96,3,127,127,126,0,2,13,1,3,101,110,118,5,97,98,111,114,116,0,6,3,23,22,0,0,0,0,0,7,2,3,3,2,4,5,1,2,5,0,1,1,0,1,1,4,5,3,1,0,1,6,187,1,37,127,0,65,4,11,127,0,65,128,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,0,11,7,169,1,13,8,72,65,83,95,83,73,77,68,3,36,22,98,97,116,99,104,72,97,115,104,52,85,105,110,116,65,114,114,97,121,54,52,115,0,17,26,98,97,116,99,104,72,97,115,104,52,72,97,115,104,79,98,106,101,99,116,73,110,112,117,116,115,0,18,12,73,78,80,85,84,95,76,69,78,71,84,72,3,1,15,80,65,82,65,76,76,69,76,95,70,65,67,84,79,82,3,0,5,105,110,112,117,116,3,30,6,111,117,116,112,117,116,3,32,4,105,110,105,116,0,11,6,117,112,100,97,116,101,0,19,5,102,105,110,97,108,0,20,6,100,105,103,101,115,116,0,21,8,100,105,103,101,115,116,54,52,0,16,6,109,101,109,111,114,121,2,0,8,1,22,12,1,18,10,153,23,22,9,0,32,0,32,1,54,2,0,11,9,0,32,0,32,1,54,2,4,11,9,0,32,0,32,1,54,2,8,11,192,1,1,4,127,32,1,40,2,0,65,124,113,34,3,65,128,2,73,4,127,32,3,65,4,118,5,65,31,65,252,255,255,255,3,32,3,32,3,65,252,255,255,255,3,79,27,34,3,103,107,34,4,65,7,107,33,2,32,3,32,4,65,4,107,118,65,16,115,11,33,3,32,1,40,2,8,33,5,32,1,40,2,4,34,4,4,64,32,4,32,5,16,3,11,32,5,4,64,32,5,32,4,16,2,11,32,1,32,0,32,2,65,4,116,32,3,106,65,2,116,106,34,1,40,2,96,70,4,64,32,1,32,5,54,2,96,32,5,69,4,64,32,0,32,2,65,2,116,106,34,1,40,2,4,65,126,32,3,119,113,33,3,32,1,32,3,54,2,4,32,3,69,4,64,32,0,32,0,40,2,0,65,126,32,2,119,113,16,1,11,11,11,11,181,2,1,5,127,32,1,40,2,0,33,3,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,2,65,1,113,4,64,32,0,32,4,16,4,32,1,32,3,65,4,106,32,2,65,124,113,106,34,3,16,1,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,2,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,1,40,2,0,33,6,32,0,32,1,16,4,32,1,32,6,65,4,106,32,3,65,124,113,106,34,3,16,1,11,32,4,32,2,65,2,114,16,1,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,5,65,31,65,252,255,255,255,3,32,2,32,2,65,252,255,255,255,3,79,27,34,2,103,107,34,3,65,7,107,33,5,32,2,32,3,65,4,107,118,65,16,115,11,34,2,32,5,65,4,116,106,65,2,116,106,40,2,96,33,3,32,1,65,0,16,2,32,1,32,3,16,3,32,3,4,64,32,3,32,1,16,2,11,32,0,32,5,65,4,116,32,2,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,5,116,114,16,1,32,0,32,5,65,2,116,106,34,0,32,0,40,2,4,65,1,32,2,116,114,54,2,4,11,130,1,1,3,127,32,1,65,19,106,65,112,113,65,4,107,33,1,32,0,40,2,160,12,34,3,4,64,32,3,32,1,65,16,107,34,5,70,4,64,32,3,40,2,0,33,4,32,5,33,1,11,11,32,2,167,65,112,113,32,1,107,34,3,65,20,73,4,64,15,11,32,1,32,4,65,2,113,32,3,65,8,107,34,3,65,1,114,114,16,1,32,1,65,0,16,2,32,1,65,0,16,3,32,1,65,4,106,32,3,106,34,3,65,2,16,1,32,0,32,3,54,2,160,12,32,0,32,1,16,5,11,29,0,32,0,65,1,65,27,32,0,103,107,116,106,65,1,107,32,0,32,0,65,254,255,255,255,1,73,27,11,142,1,1,2,127,32,1,65,128,2,73,4,127,32,1,65,4,118,5,65,31,32,1,16,7,34,1,103,107,34,3,65,7,107,33,2,32,1,32,3,65,4,107,118,65,16,115,11,33,1,32,0,32,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,148,2,1,3,127,32,1,65,252,255,255,255,3,75,4,64,65,176,14,65,176,15,65,205,3,65,29,16,0,0,11,32,0,65,12,32,1,65,19,106,65,112,113,65,4,107,32,1,65,12,77,27,34,1,16,8,34,2,69,4,64,32,1,65,128,2,79,4,127,32,1,16,7,5,32,1,11,33,2,63,0,34,3,32,2,65,4,32,0,40,2,160,12,32,3,65,16,116,65,4,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,2,32,2,32,3,72,27,64,0,65,0,72,4,64,32,2,64,0,65,0,72,4,64,0,11,11,32,0,32,3,65,16,116,63,0,172,66,16,134,16,6,32,0,32,1,16,8,33,2,11,32,2,40,2,0,26,32,0,32,2,16,4,32,2,40,2,0,34,3,65,124,113,32,1,107,34,4,65,16,79,4,64,32,2,32,1,32,3,65,2,113,114,16,1,32,2,65,4,106,32,1,106,34,1,32,4,65,4,107,65,1,114,16,1,32,0,32,1,16,5,5,32,2,32,3,65,126,113,16,1,32,2,65,4,106,32,2,40,2,0,65,124,113,106,34,0,32,0,40,2,0,65,125,113,16,1,11,32,2,11,169,2,1,3,127,32,0,65,252,255,255,255,3,75,4,64,65,192,13,65,240,13,65,52,65,43,16,0,0,11,32,0,65,236,255,255,255,3,75,4,64,65,176,14,65,240,14,65,253,0,65,30,16,0,0,11,35,23,69,4,64,63,0,34,2,65,0,76,4,127,65,1,32,2,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,128,16,65,0,16,1,65,160,28,65,0,54,2,0,3,64,32,1,65,23,73,4,64,32,1,65,2,116,65,128,16,106,65,0,54,2,4,65,0,33,2,3,64,32,2,65,16,73,4,64,32,1,65,4,116,32,2,106,65,2,116,65,128,16,106,65,0,54,2,96,32,2,65,1,106,33,2,12,1,11,11,32,1,65,1,106,33,1,12,1,11,11,65,128,16,65,164,28,63,0,172,66,16,134,16,6,65,128,16,36,23,11,35,23,32,0,65,16,106,16,9,34,2,65,1,54,2,12,32,2,32,0,54,2,16,35,24,34,3,40,2,8,33,1,32,2,32,3,16,2,32,2,32,1,16,3,32,1,32,2,32,1,40,2,4,65,3,113,114,16,2,32,3,32,2,16,3,35,25,32,2,40,2,0,65,124,113,65,4,106,106,36,25,32,2,65,20,106,34,1,65,0,32,0,252,11,0,32,1,11,74,0,65,231,204,167,208,6,36,4,65,133,221,158,219,123,36,5,65,242,230,187,227,3,36,6,65,186,234,191,170,122,36,7,65,255,164,185,136,5,36,8,65,140,209,149,216,121,36,9,65,171,179,143,252,1,36,10,65,153,154,131,223,5,36,11,65,0,36,34,65,0,36,35,11,233,3,1,1,127,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,35,8,36,16,35,9,36,17,35,10,36,18,35,11,36,19,65,0,36,20,3,64,35,20,65,16,73,4,64,32,0,35,20,65,2,116,106,32,1,35,20,32,2,108,65,2,116,34,3,65,3,106,106,45,0,0,32,1,32,3,106,45,0,0,65,24,116,32,1,32,3,65,1,106,106,45,0,0,65,16,116,114,32,1,32,3,65,2,106,106,45,0,0,65,8,116,114,114,54,2,0,35,20,65,1,106,36,20,12,1,11,11,65,16,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,106,32,0,35,20,65,16,107,65,2,116,106,40,2,0,32,0,35,20,65,7,107,65,2,116,106,40,2,0,32,0,35,20,65,2,107,65,2,116,106,40,2,0,34,1,65,17,120,32,1,65,19,120,115,32,1,65,10,118,115,106,32,0,35,20,65,15,107,65,2,116,106,40,2,0,34,1,65,7,120,32,1,65,18,120,115,32,1,65,3,118,115,106,106,54,2,0,35,20,65,1,106,36,20,12,1,11,11,65,0,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,34,1,106,40,2,0,32,1,35,2,106,40,2,0,35,19,35,16,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,16,34,1,35,17,113,35,18,32,1,65,127,115,113,115,106,106,106,36,21,35,12,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,13,34,1,35,14,34,2,113,32,1,35,12,34,1,113,32,1,32,2,113,115,115,106,36,22,35,18,36,19,35,17,36,18,35,16,36,17,35,15,35,21,106,36,16,35,14,36,15,35,13,36,14,35,12,36,13,35,21,35,22,106,36,12,35,20,65,1,106,36,20,12,1,11,11,35,4,35,12,106,36,4,35,5,35,13,106,36,5,35,6,35,14,106,36,6,35,7,35,15,106,36,7,35,8,35,16,106,36,8,35,9,35,17,106,36,9,35,10,35,18,106,36,10,35,11,35,19,106,36,11,11,253,1,1,2,127,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,35,8,36,16,35,9,36,17,35,10,36,18,35,11,36,19,65,0,36,20,3,64,35,20,65,192,0,73,4,64,32,0,35,20,65,2,116,106,40,2,0,35,19,35,16,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,16,34,1,35,17,113,35,18,32,1,65,127,115,113,115,106,106,36,21,35,12,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,13,34,2,35,14,34,1,113,32,2,35,12,34,2,113,32,1,32,2,113,115,115,106,36,22,35,18,36,19,35,17,36,18,35,16,36,17,35,15,35,21,106,36,16,35,14,36,15,35,13,36,14,35,12,36,13,35,21,35,22,106,36,12,35,20,65,1,106,36,20,12,1,11,11,35,4,35,12,106,36,4,35,5,35,13,106,36,5,35,6,35,14,106,36,6,35,7,35,15,106,36,7,35,8,35,16,106,36,8,35,9,35,17,106,36,9,35,10,35,18,106,36,10,35,11,35,19,106,36,11,11,25,0,32,0,65,128,254,131,120,113,65,8,119,32,0,65,255,129,252,7,113,65,8,120,114,11,88,0,16,11,35,29,32,0,32,2,16,12,35,3,16,13,32,1,35,4,16,14,54,2,0,32,1,35,5,16,14,54,2,4,32,1,35,6,16,14,54,2,8,32,1,35,7,16,14,54,2,12,32,1,35,8,16,14,54,2,16,32,1,35,9,16,14,54,2,20,32,1,35,10,16,14,54,2,24,32,1,35,11,16,14,54,2,28,11,10,0,32,0,32,1,65,1,16,15,11,42,1,1,127,3,64,32,1,65,4,72,4,64,35,31,32,1,65,6,116,106,32,0,32,1,65,5,116,106,16,16,32,1,65,1,106,33,1,12,1,11,11,11,44,1,1,127,3,64,32,1,65,4,72,4,64,35,31,32,1,65,2,116,106,32,0,32,1,65,5,116,106,65,4,16,15,32,1,65,1,106,33,1,12,1,11,11,11,178,1,1,2,127,35,35,32,1,106,36,35,35,34,4,64,65,192,0,35,34,107,34,2,32,1,76,4,64,35,27,35,34,106,32,0,32,2,252,10,0,0,35,34,32,2,106,36,34,65,192,0,35,34,107,33,2,32,1,65,192,0,35,34,107,107,33,1,35,29,35,27,65,1,16,12,65,0,36,34,5,35,27,35,34,106,32,0,32,1,252,10,0,0,35,34,32,1,106,36,34,15,11,11,3,64,32,3,32,1,65,192,0,109,72,4,64,35,29,32,0,32,2,106,65,1,16,12,32,3,65,1,106,33,3,32,2,65,64,107,33,2,12,1,11,11,32,1,65,63,113,34,1,4,64,35,27,35,34,106,32,0,32,2,106,32,1,252,10,0,0,35,34,32,1,106,36,34,11,11,235,1,1,2,127,35,27,35,34,106,65,128,1,58,0,0,35,34,65,1,106,36,34,35,34,65,56,74,4,64,35,27,35,34,106,34,1,65,192,0,35,34,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,29,35,27,65,1,16,12,65,0,36,34,11,35,27,35,34,106,34,1,65,56,35,34,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,27,35,35,65,128,128,128,128,2,109,16,14,54,2,56,35,27,35,35,65,3,116,16,14,54,2,60,35,29,35,27,65,1,16,12,32,0,35,4,16,14,54,2,0,32,0,35,5,16,14,54,2,4,32,0,35,6,16,14,54,2,8,32,0,35,7,16,14,54,2,12,32,0,35,8,16,14,54,2,16,32,0,35,9,16,14,54,2,20,32,0,35,10,16,14,54,2,24,32,0,35,11,16,14,54,2,28,11,14,0,16,11,35,31,32,0,16,19,35,33,16,20,11,82,0,65,196,10,40,2,0,36,2,65,148,13,40,2,0,36,3,65,224,15,65,224,15,16,2,65,224,15,65,224,15,16,3,65,224,15,36,24,65,192,0,16,10,36,26,35,26,36,27,65,128,8,16,10,36,28,35,28,36,29,65,128,4,16,10,36,30,35,30,36,31,65,32,16,10,36,32,35,32,36,33,11,11,253,6,18,0,65,140,8,11,2,28,1,0,65,152,8,11,136,2,1,0,0,0,0,1,0,0,152,47,138,66,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,241,155,193,193,105,155,228,134,71,190,239,198,157,193,15,204,161,12,36,111,44,233,45,170,132,116,74,220,169,176,92,218,136,249,118,82,81,62,152,109,198,49,168,200,39,3,176,199,127,89,191,243,11,224,198,71,145,167,213,81,99,202,6,103,41,41,20,133,10,183,39,56,33,27,46,252,109,44,77,19,13,56,83,84,115,10,101,187,10,106,118,46,201,194,129,133,44,114,146,161,232,191,162,75,102,26,168,112,139,75,194,163,81,108,199,25,232,146,209,36,6,153,214,133,53,14,244,112,160,106,16,22,193,164,25,8,108,55,30,76,119,72,39,181,188,176,52,179,12,28,57,74,170,216,78,79,202,156,91,243,111,46,104,238,130,143,116,111,99,165,120,20,120,200,132,8,2,199,140,250,255,190,144,235,108,80,164,247,163,249,190,242,120,113,198,0,65,172,10,11,1,44,0,65,184,10,11,21,4,0,0,0,16,0,0,0,32,4,0,0,32,4,0,0,0,1,0,0,64,0,65,220,10,11,2,28,1,0,65,232,10,11,136,2,1,0,0,0,0,1,0,0,152,47,138,194,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,243,155,193,193,105,155,100,134,71,254,240,198,237,225,15,84,242,12,36,111,52,233,79,190,132,201,108,30,65,185,97,250,136,249,22,82,81,198,242,109,90,142,168,101,252,25,176,199,158,217,185,195,49,18,154,160,234,14,231,43,35,177,253,176,62,53,199,213,186,105,48,95,109,151,203,143,17,15,90,253,238,30,220,137,182,53,10,4,122,11,222,157,202,244,88,22,91,93,225,134,62,127,0,128,137,8,55,50,234,7,165,55,149,171,111,16,97,64,23,241,214,140,13,109,59,170,205,55,190,187,192,218,59,97,131,99,163,72,219,49,233,2,11,167,92,209,111,202,250,26,82,49,132,51,49,149,26,212,110,144,120,67,109,242,145,156,195,189,171,204,158,230,160,201,181,60,182,47,83,198,65,199,210,163,126,35,7,104,75,149,164,118,29,25,76,0,65,252,12,11,1,44,0,65,136,13,11,21,4,0,0,0,16,0,0,0,112,5,0,0,112,5,0,0,0,1,0,0,64,0,65,172,13,11,1,44,0,65,184,13,11,35,2,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,220,13,11,1,60,0,65,232,13,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,156,14,11,1,60,0,65,168,14,11,47,2,0,0,0,40,0,0,0,65,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,220,14,11,1,60,0,65,232,14,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,99,0,109,0,115,0,46,0,116,0,115,0,65,156,15,11,1,60,0,65,168,15,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115]);var cm=Uint8Array.from([0,97,115,109,1,0,0,0,1,37,7,96,2,127,127,0,96,1,127,1,127,96,2,127,127,1,127,96,1,127,0,96,0,0,96,4,127,127,127,127,0,96,3,127,127,126,0,2,13,1,3,101,110,118,5,97,98,111,114,116,0,5,3,30,29,0,0,0,0,0,6,1,2,2,2,1,2,1,1,2,4,4,1,0,3,3,4,0,0,3,3,3,0,4,5,3,1,0,1,6,227,4,61,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,127,1,65,0,11,123,1,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,4,11,127,0,65,128,4,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,1,65,0,11,127,0,65,1,11,7,169,1,13,8,72,65,83,95,83,73,77,68,3,60,22,98,97,116,99,104,72,97,115,104,52,85,105,110,116,65,114,114,97,121,54,52,115,0,20,26,98,97,116,99,104,72,97,115,104,52,72,97,115,104,79,98,106,101,99,116,73,110,112,117,116,115,0,21,12,73,78,80,85,84,95,76,69,78,71,84,72,3,28,15,80,65,82,65,76,76,69,76,95,70,65,67,84,79,82,3,27,5,105,110,112,117,116,3,54,6,111,117,116,112,117,116,3,56,4,105,110,105,116,0,22,6,117,112,100,97,116,101,0,24,5,102,105,110,97,108,0,25,6,100,105,103,101,115,116,0,26,8,100,105,103,101,115,116,54,52,0,28,6,109,101,109,111,114,121,2,0,8,1,29,12,1,38,10,243,111,29,9,0,32,0,32,1,54,2,0,11,9,0,32,0,32,1,54,2,4,11,9,0,32,0,32,1,54,2,8,11,192,1,1,4,127,32,1,40,2,0,65,124,113,34,3,65,128,2,73,4,127,32,3,65,4,118,5,65,31,65,252,255,255,255,3,32,3,32,3,65,252,255,255,255,3,79,27,34,3,103,107,34,4,65,7,107,33,2,32,3,32,4,65,4,107,118,65,16,115,11,33,3,32,1,40,2,8,33,5,32,1,40,2,4,34,4,4,64,32,4,32,5,16,3,11,32,5,4,64,32,5,32,4,16,2,11,32,1,32,0,32,2,65,4,116,32,3,106,65,2,116,106,34,1,40,2,96,70,4,64,32,1,32,5,54,2,96,32,5,69,4,64,32,0,32,2,65,2,116,106,34,1,40,2,4,65,126,32,3,119,113,33,3,32,1,32,3,54,2,4,32,3,69,4,64,32,0,32,0,40,2,0,65,126,32,2,119,113,16,1,11,11,11,11,181,2,1,5,127,32,1,40,2,0,33,3,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,34,2,65,1,113,4,64,32,0,32,4,16,4,32,1,32,3,65,4,106,32,2,65,124,113,106,34,3,16,1,32,1,65,4,106,32,1,40,2,0,65,124,113,106,34,4,40,2,0,33,2,11,32,3,65,2,113,4,64,32,1,65,4,107,40,2,0,34,1,40,2,0,33,6,32,0,32,1,16,4,32,1,32,6,65,4,106,32,3,65,124,113,106,34,3,16,1,11,32,4,32,2,65,2,114,16,1,32,4,65,4,107,32,1,54,2,0,32,0,32,3,65,124,113,34,2,65,128,2,73,4,127,32,2,65,4,118,5,65,31,65,252,255,255,255,3,32,2,32,2,65,252,255,255,255,3,79,27,34,2,103,107,34,3,65,7,107,33,5,32,2,32,3,65,4,107,118,65,16,115,11,34,2,32,5,65,4,116,106,65,2,116,106,40,2,96,33,3,32,1,65,0,16,2,32,1,32,3,16,3,32,3,4,64,32,3,32,1,16,2,11,32,0,32,5,65,4,116,32,2,106,65,2,116,106,32,1,54,2,96,32,0,32,0,40,2,0,65,1,32,5,116,114,16,1,32,0,32,5,65,2,116,106,34,0,32,0,40,2,4,65,1,32,2,116,114,54,2,4,11,130,1,1,3,127,32,1,65,19,106,65,112,113,65,4,107,33,1,32,0,40,2,160,12,34,3,4,64,32,3,32,1,65,16,107,34,5,70,4,64,32,3,40,2,0,33,4,32,5,33,1,11,11,32,2,167,65,112,113,32,1,107,34,3,65,20,73,4,64,15,11,32,1,32,4,65,2,113,32,3,65,8,107,34,3,65,1,114,114,16,1,32,1,65,0,16,2,32,1,65,0,16,3,32,1,65,4,106,32,3,106,34,3,65,2,16,1,32,0,32,3,54,2,160,12,32,0,32,1,16,5,11,29,0,32,0,65,1,65,27,32,0,103,107,116,106,65,1,107,32,0,32,0,65,254,255,255,255,1,73,27,11,142,1,1,2,127,32,1,65,128,2,73,4,127,32,1,65,4,118,5,65,31,32,1,16,7,34,1,103,107,34,3,65,7,107,33,2,32,1,32,3,65,4,107,118,65,16,115,11,33,1,32,0,32,2,65,2,116,106,40,2,4,65,127,32,1,116,113,34,1,4,127,32,0,32,1,104,32,2,65,4,116,106,65,2,116,106,40,2,96,5,32,0,40,2,0,65,127,32,2,65,1,106,116,113,34,1,4,127,32,0,32,0,32,1,104,34,0,65,2,116,106,40,2,4,104,32,0,65,4,116,106,65,2,116,106,40,2,96,5,65,0,11,11,11,148,2,1,3,127,32,1,65,252,255,255,255,3,75,4,64,65,176,14,65,176,15,65,205,3,65,29,16,0,0,11,32,0,65,12,32,1,65,19,106,65,112,113,65,4,107,32,1,65,12,77,27,34,1,16,8,34,2,69,4,64,32,1,65,128,2,79,4,127,32,1,16,7,5,32,1,11,33,2,63,0,34,3,32,2,65,4,32,0,40,2,160,12,32,3,65,16,116,65,4,107,71,116,106,65,255,255,3,106,65,128,128,124,113,65,16,118,34,2,32,2,32,3,72,27,64,0,65,0,72,4,64,32,2,64,0,65,0,72,4,64,0,11,11,32,0,32,3,65,16,116,63,0,172,66,16,134,16,6,32,0,32,1,16,8,33,2,11,32,2,40,2,0,26,32,0,32,2,16,4,32,2,40,2,0,34,3,65,124,113,32,1,107,34,4,65,16,79,4,64,32,2,32,1,32,3,65,2,113,114,16,1,32,2,65,4,106,32,1,106,34,1,32,4,65,4,107,65,1,114,16,1,32,0,32,1,16,5,5,32,2,32,3,65,126,113,16,1,32,2,65,4,106,32,2,40,2,0,65,124,113,106,34,0,32,0,40,2,0,65,125,113,16,1,11,32,2,11,133,2,1,2,127,32,0,65,236,255,255,255,3,75,4,64,65,176,14,65,240,14,65,253,0,65,30,16,0,0,11,35,20,69,4,64,63,0,34,3,65,0,76,4,127,65,1,32,3,107,64,0,65,0,72,5,65,0,11,4,64,0,11,65,208,21,65,0,16,1,65,240,33,65,0,54,2,0,3,64,32,2,65,23,73,4,64,32,2,65,2,116,65,208,21,106,65,0,54,2,4,65,0,33,3,3,64,32,3,65,16,73,4,64,32,2,65,4,116,32,3,106,65,2,116,65,208,21,106,65,0,54,2,96,32,3,65,1,106,33,3,12,1,11,11,32,2,65,1,106,33,2,12,1,11,11,65,208,21,65,244,33,63,0,172,66,16,134,16,6,65,208,21,36,20,11,35,20,32,0,65,16,106,16,9,34,2,32,1,54,2,12,32,2,32,0,54,2,16,35,21,34,0,40,2,8,33,1,32,2,32,0,16,2,32,2,32,1,16,3,32,1,32,2,32,1,40,2,4,65,3,113,114,16,2,32,0,32,2,16,3,35,22,32,2,40,2,0,65,124,113,65,4,106,106,36,22,32,2,65,20,106,11,46,1,1,127,32,0,65,252,255,255,255,3,75,4,64,65,192,13,65,240,13,65,52,65,43,16,0,0,11,32,0,65,1,16,10,34,1,65,0,32,0,252,11,0,32,1,11,41,0,32,1,32,0,40,2,12,79,4,64,65,144,16,65,208,16,65,242,0,65,42,16,0,0,11,32,0,40,2,4,32,1,65,2,116,106,40,2,0,11,181,1,1,4,127,32,0,69,4,64,65,192,18,15,11,65,0,32,0,107,32,0,32,0,65,31,118,65,1,116,34,1,27,34,0,65,10,79,65,1,106,32,0,65,144,206,0,79,65,3,106,32,0,65,232,7,79,106,32,0,65,228,0,73,27,32,0,65,192,132,61,79,65,6,106,32,0,65,128,148,235,220,3,79,65,8,106,32,0,65,128,194,215,47,79,106,32,0,65,128,173,226,4,73,27,32,0,65,160,141,6,73,27,34,2,65,1,116,32,1,106,65,2,16,10,34,3,32,1,106,33,4,3,64,32,4,32,2,65,1,107,34,2,65,1,116,106,32,0,65,10,112,65,48,106,59,1,0,32,0,65,10,110,34,0,13,0,11,32,1,4,64,32,3,65,45,59,1,0,11,32,3,11,13,0,32,0,65,20,107,40,2,16,65,1,118,11,64,1,3,127,32,0,16,14,65,1,116,34,2,32,1,16,14,65,1,116,34,3,106,34,4,69,4,64,65,160,20,15,11,32,4,65,2,16,10,34,4,32,0,32,2,252,10,0,0,32,2,32,4,106,32,1,32,3,252,10,0,0,32,4,11,145,16,2,2,127,1,123,65,224,15,65,224,15,16,2,65,224,15,65,224,15,16,3,65,224,15,36,21,65,128,8,16,11,36,23,35,23,36,24,2,64,3,64,32,0,65,192,0,72,4,64,35,24,33,1,65,192,10,32,0,16,12,253,17,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,32,0,14,64,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,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,52,53,54,55,56,57,58,59,60,61,62,63,67,11,32,1,32,2,253,11,4,0,12,63,11,32,1,32,2,253,11,4,16,12,62,11,32,1,32,2,253,11,4,32,12,61,11,32,1,32,2,253,11,4,48,12,60,11,32,1,32,2,253,11,4,64,12,59,11,32,1,32,2,253,11,4,80,12,58,11,32,1,32,2,253,11,4,96,12,57,11,32,1,32,2,253,11,4,112,12,56,11,32,1,32,2,253,11,4,128,1,12,55,11,32,1,32,2,253,11,4,144,1,12,54,11,32,1,32,2,253,11,4,160,1,12,53,11,32,1,32,2,253,11,4,176,1,12,52,11,32,1,32,2,253,11,4,192,1,12,51,11,32,1,32,2,253,11,4,208,1,12,50,11,32,1,32,2,253,11,4,224,1,12,49,11,32,1,32,2,253,11,4,240,1,12,48,11,32,1,32,2,253,11,4,128,2,12,47,11,32,1,32,2,253,11,4,144,2,12,46,11,32,1,32,2,253,11,4,160,2,12,45,11,32,1,32,2,253,11,4,176,2,12,44,11,32,1,32,2,253,11,4,192,2,12,43,11,32,1,32,2,253,11,4,208,2,12,42,11,32,1,32,2,253,11,4,224,2,12,41,11,32,1,32,2,253,11,4,240,2,12,40,11,32,1,32,2,253,11,4,128,3,12,39,11,32,1,32,2,253,11,4,144,3,12,38,11,32,1,32,2,253,11,4,160,3,12,37,11,32,1,32,2,253,11,4,176,3,12,36,11,32,1,32,2,253,11,4,192,3,12,35,11,32,1,32,2,253,11,4,208,3,12,34,11,32,1,32,2,253,11,4,224,3,12,33,11,32,1,32,2,253,11,4,240,3,12,32,11,32,1,32,2,253,11,4,128,4,12,31,11,32,1,32,2,253,11,4,144,4,12,30,11,32,1,32,2,253,11,4,160,4,12,29,11,32,1,32,2,253,11,4,176,4,12,28,11,32,1,32,2,253,11,4,192,4,12,27,11,32,1,32,2,253,11,4,208,4,12,26,11,32,1,32,2,253,11,4,224,4,12,25,11,32,1,32,2,253,11,4,240,4,12,24,11,32,1,32,2,253,11,4,128,5,12,23,11,32,1,32,2,253,11,4,144,5,12,22,11,32,1,32,2,253,11,4,160,5,12,21,11,32,1,32,2,253,11,4,176,5,12,20,11,32,1,32,2,253,11,4,192,5,12,19,11,32,1,32,2,253,11,4,208,5,12,18,11,32,1,32,2,253,11,4,224,5,12,17,11,32,1,32,2,253,11,4,240,5,12,16,11,32,1,32,2,253,11,4,128,6,12,15,11,32,1,32,2,253,11,4,144,6,12,14,11,32,1,32,2,253,11,4,160,6,12,13,11,32,1,32,2,253,11,4,176,6,12,12,11,32,1,32,2,253,11,4,192,6,12,11,11,32,1,32,2,253,11,4,208,6,12,10,11,32,1,32,2,253,11,4,224,6,12,9,11,32,1,32,2,253,11,4,240,6,12,8,11,32,1,32,2,253,11,4,128,7,12,7,11,32,1,32,2,253,11,4,144,7,12,6,11,32,1,32,2,253,11,4,160,7,12,5,11,32,1,32,2,253,11,4,176,7,12,4,11,32,1,32,2,253,11,4,192,7,12,3,11,32,1,32,2,253,11,4,208,7,12,2,11,32,1,32,2,253,11,4,224,7,12,1,11,32,1,32,2,253,11,4,240,7,11,32,0,65,1,106,33,0,12,1,11,11,65,128,8,16,11,36,25,35,25,36,26,65,0,33,0,3,64,32,0,65,192,0,72,4,64,35,26,33,1,65,144,13,32,0,16,12,253,17,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,32,0,14,64,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,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,52,53,54,55,56,57,58,59,60,61,62,63,67,11,32,1,32,2,253,11,4,0,12,63,11,32,1,32,2,253,11,4,16,12,62,11,32,1,32,2,253,11,4,32,12,61,11,32,1,32,2,253,11,4,48,12,60,11,32,1,32,2,253,11,4,64,12,59,11,32,1,32,2,253,11,4,80,12,58,11,32,1,32,2,253,11,4,96,12,57,11,32,1,32,2,253,11,4,112,12,56,11,32,1,32,2,253,11,4,128,1,12,55,11,32,1,32,2,253,11,4,144,1,12,54,11,32,1,32,2,253,11,4,160,1,12,53,11,32,1,32,2,253,11,4,176,1,12,52,11,32,1,32,2,253,11,4,192,1,12,51,11,32,1,32,2,253,11,4,208,1,12,50,11,32,1,32,2,253,11,4,224,1,12,49,11,32,1,32,2,253,11,4,240,1,12,48,11,32,1,32,2,253,11,4,128,2,12,47,11,32,1,32,2,253,11,4,144,2,12,46,11,32,1,32,2,253,11,4,160,2,12,45,11,32,1,32,2,253,11,4,176,2,12,44,11,32,1,32,2,253,11,4,192,2,12,43,11,32,1,32,2,253,11,4,208,2,12,42,11,32,1,32,2,253,11,4,224,2,12,41,11,32,1,32,2,253,11,4,240,2,12,40,11,32,1,32,2,253,11,4,128,3,12,39,11,32,1,32,2,253,11,4,144,3,12,38,11,32,1,32,2,253,11,4,160,3,12,37,11,32,1,32,2,253,11,4,176,3,12,36,11,32,1,32,2,253,11,4,192,3,12,35,11,32,1,32,2,253,11,4,208,3,12,34,11,32,1,32,2,253,11,4,224,3,12,33,11,32,1,32,2,253,11,4,240,3,12,32,11,32,1,32,2,253,11,4,128,4,12,31,11,32,1,32,2,253,11,4,144,4,12,30,11,32,1,32,2,253,11,4,160,4,12,29,11,32,1,32,2,253,11,4,176,4,12,28,11,32,1,32,2,253,11,4,192,4,12,27,11,32,1,32,2,253,11,4,208,4,12,26,11,32,1,32,2,253,11,4,224,4,12,25,11,32,1,32,2,253,11,4,240,4,12,24,11,32,1,32,2,253,11,4,128,5,12,23,11,32,1,32,2,253,11,4,144,5,12,22,11,32,1,32,2,253,11,4,160,5,12,21,11,32,1,32,2,253,11,4,176,5,12,20,11,32,1,32,2,253,11,4,192,5,12,19,11,32,1,32,2,253,11,4,208,5,12,18,11,32,1,32,2,253,11,4,224,5,12,17,11,32,1,32,2,253,11,4,240,5,12,16,11,32,1,32,2,253,11,4,128,6,12,15,11,32,1,32,2,253,11,4,144,6,12,14,11,32,1,32,2,253,11,4,160,6,12,13,11,32,1,32,2,253,11,4,176,6,12,12,11,32,1,32,2,253,11,4,192,6,12,11,11,32,1,32,2,253,11,4,208,6,12,10,11,32,1,32,2,253,11,4,224,6,12,9,11,32,1,32,2,253,11,4,240,6,12,8,11,32,1,32,2,253,11,4,128,7,12,7,11,32,1,32,2,253,11,4,144,7,12,6,11,32,1,32,2,253,11,4,160,7,12,5,11,32,1,32,2,253,11,4,176,7,12,4,11,32,1,32,2,253,11,4,192,7,12,3,11,32,1,32,2,253,11,4,208,7,12,2,11,32,1,32,2,253,11,4,224,7,12,1,11,32,1,32,2,253,11,4,240,7,11,32,0,65,1,106,33,0,12,1,11,11,15,11,65,192,19,32,0,16,13,16,15,65,192,20,65,201,1,65,7,16,0,0,11,192,10,2,2,123,2,127,35,0,36,8,35,1,36,9,35,2,36,10,35,3,36,11,35,4,36,12,35,5,36,13,35,6,36,14,35,7,36,15,65,0,36,18,3,64,35,18,65,192,0,72,4,64,35,15,35,12,34,0,65,6,253,173,1,32,0,65,26,253,171,1,253,80,32,0,65,11,253,173,1,32,0,65,21,253,171,1,253,80,253,81,32,0,65,25,253,173,1,32,0,65,7,253,171,1,253,80,253,81,253,174,1,35,12,34,0,35,13,253,78,32,0,253,77,35,14,253,78,253,81,253,174,1,33,1,35,26,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,3,14,64,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,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,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,2,253,0,4,0,33,0,12,64,11,32,2,253,0,4,16,33,0,12,63,11,32,2,253,0,4,32,33,0,12,62,11,32,2,253,0,4,48,33,0,12,61,11,32,2,253,0,4,64,33,0,12,60,11,32,2,253,0,4,80,33,0,12,59,11,32,2,253,0,4,96,33,0,12,58,11,32,2,253,0,4,112,33,0,12,57,11,32,2,253,0,4,128,1,33,0,12,56,11,32,2,253,0,4,144,1,33,0,12,55,11,32,2,253,0,4,160,1,33,0,12,54,11,32,2,253,0,4,176,1,33,0,12,53,11,32,2,253,0,4,192,1,33,0,12,52,11,32,2,253,0,4,208,1,33,0,12,51,11,32,2,253,0,4,224,1,33,0,12,50,11,32,2,253,0,4,240,1,33,0,12,49,11,32,2,253,0,4,128,2,33,0,12,48,11,32,2,253,0,4,144,2,33,0,12,47,11,32,2,253,0,4,160,2,33,0,12,46,11,32,2,253,0,4,176,2,33,0,12,45,11,32,2,253,0,4,192,2,33,0,12,44,11,32,2,253,0,4,208,2,33,0,12,43,11,32,2,253,0,4,224,2,33,0,12,42,11,32,2,253,0,4,240,2,33,0,12,41,11,32,2,253,0,4,128,3,33,0,12,40,11,32,2,253,0,4,144,3,33,0,12,39,11,32,2,253,0,4,160,3,33,0,12,38,11,32,2,253,0,4,176,3,33,0,12,37,11,32,2,253,0,4,192,3,33,0,12,36,11,32,2,253,0,4,208,3,33,0,12,35,11,32,2,253,0,4,224,3,33,0,12,34,11,32,2,253,0,4,240,3,33,0,12,33,11,32,2,253,0,4,128,4,33,0,12,32,11,32,2,253,0,4,144,4,33,0,12,31,11,32,2,253,0,4,160,4,33,0,12,30,11,32,2,253,0,4,176,4,33,0,12,29,11,32,2,253,0,4,192,4,33,0,12,28,11,32,2,253,0,4,208,4,33,0,12,27,11,32,2,253,0,4,224,4,33,0,12,26,11,32,2,253,0,4,240,4,33,0,12,25,11,32,2,253,0,4,128,5,33,0,12,24,11,32,2,253,0,4,144,5,33,0,12,23,11,32,2,253,0,4,160,5,33,0,12,22,11,32,2,253,0,4,176,5,33,0,12,21,11,32,2,253,0,4,192,5,33,0,12,20,11,32,2,253,0,4,208,5,33,0,12,19,11,32,2,253,0,4,224,5,33,0,12,18,11,32,2,253,0,4,240,5,33,0,12,17,11,32,2,253,0,4,128,6,33,0,12,16,11,32,2,253,0,4,144,6,33,0,12,15,11,32,2,253,0,4,160,6,33,0,12,14,11,32,2,253,0,4,176,6,33,0,12,13,11,32,2,253,0,4,192,6,33,0,12,12,11,32,2,253,0,4,208,6,33,0,12,11,11,32,2,253,0,4,224,6,33,0,12,10,11,32,2,253,0,4,240,6,33,0,12,9,11,32,2,253,0,4,128,7,33,0,12,8,11,32,2,253,0,4,144,7,33,0,12,7,11,32,2,253,0,4,160,7,33,0,12,6,11,32,2,253,0,4,176,7,33,0,12,5,11,32,2,253,0,4,192,7,33,0,12,4,11,32,2,253,0,4,208,7,33,0,12,3,11,32,2,253,0,4,224,7,33,0,12,2,11,32,2,253,0,4,240,7,33,0,12,1,11,65,128,21,32,3,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,32,1,32,0,253,174,1,36,16,35,8,34,0,65,2,253,173,1,32,0,65,30,253,171,1,253,80,32,0,65,13,253,173,1,32,0,65,19,253,171,1,253,80,253,81,32,0,65,22,253,173,1,32,0,65,10,253,171,1,253,80,253,81,35,8,34,0,35,9,34,1,253,78,32,0,35,10,34,0,253,78,253,81,32,1,32,0,253,78,253,81,253,174,1,36,17,35,14,36,15,35,13,36,14,35,12,36,13,35,11,35,16,253,174,1,36,12,35,10,36,11,35,9,36,10,35,8,36,9,35,16,35,17,253,174,1,36,8,35,18,65,1,106,36,18,12,1,11,11,35,0,35,8,253,174,1,36,0,35,1,35,9,253,174,1,36,1,35,2,35,10,253,174,1,36,2,35,3,35,11,253,174,1,36,3,35,4,35,12,253,174,1,36,4,35,5,35,13,253,174,1,36,5,35,6,35,14,253,174,1,36,6,35,7,35,15,253,174,1,36,7,11,25,0,32,0,65,128,254,131,120,113,65,8,119,32,0,65,255,129,252,7,113,65,8,120,114,11,157,57,2,2,123,2,127,253,12,103,230,9,106,103,230,9,106,103,230,9,106,103,230,9,106,36,0,253,12,133,174,103,187,133,174,103,187,133,174,103,187,133,174,103,187,36,1,253,12,114,243,110,60,114,243,110,60,114,243,110,60,114,243,110,60,36,2,253,12,58,245,79,165,58,245,79,165,58,245,79,165,58,245,79,165,36,3,253,12,127,82,14,81,127,82,14,81,127,82,14,81,127,82,14,81,36,4,253,12,140,104,5,155,140,104,5,155,140,104,5,155,140,104,5,155,36,5,253,12,171,217,131,31,171,217,131,31,171,217,131,31,171,217,131,31,36,6,253,12,25,205,224,91,25,205,224,91,25,205,224,91,25,205,224,91,36,7,253,12,103,230,9,106,103,230,9,106,103,230,9,106,103,230,9,106,36,8,253,12,133,174,103,187,133,174,103,187,133,174,103,187,133,174,103,187,36,9,253,12,114,243,110,60,114,243,110,60,114,243,110,60,114,243,110,60,36,10,253,12,58,245,79,165,58,245,79,165,58,245,79,165,58,245,79,165,36,11,253,12,127,82,14,81,127,82,14,81,127,82,14,81,127,82,14,81,36,12,253,12,140,104,5,155,140,104,5,155,140,104,5,155,140,104,5,155,36,13,253,12,171,217,131,31,171,217,131,31,171,217,131,31,171,217,131,31,36,14,253,12,25,205,224,91,25,205,224,91,25,205,224,91,25,205,224,91,36,15,65,0,36,18,2,64,3,64,35,18,65,192,0,72,4,64,35,18,65,16,72,4,123,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,4,14,64,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,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,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,5,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,2,107,34,4,14,64,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,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,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,34,2,65,17,253,173,1,32,2,65,15,253,171,1,253,80,32,2,65,19,253,173,1,32,2,65,13,253,171,1,253,80,253,81,32,2,65,10,253,173,1,253,81,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,7,107,34,4,14,64,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,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,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,253,174,1,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,15,107,34,4,14,64,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,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,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,34,2,65,7,253,173,1,32,2,65,25,253,171,1,253,80,32,2,65,18,253,173,1,32,2,65,14,253,171,1,253,80,253,81,32,2,65,3,253,173,1,253,81,253,174,1,2,123,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,65,16,107,34,4,14,64,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,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,52,53,54,55,56,57,58,59,60,61,62,63,68,11,32,0,253,0,4,0,12,63,11,32,0,253,0,4,16,12,62,11,32,0,253,0,4,32,12,61,11,32,0,253,0,4,48,12,60,11,32,0,253,0,4,64,12,59,11,32,0,253,0,4,80,12,58,11,32,0,253,0,4,96,12,57,11,32,0,253,0,4,112,12,56,11,32,0,253,0,4,128,1,12,55,11,32,0,253,0,4,144,1,12,54,11,32,0,253,0,4,160,1,12,53,11,32,0,253,0,4,176,1,12,52,11,32,0,253,0,4,192,1,12,51,11,32,0,253,0,4,208,1,12,50,11,32,0,253,0,4,224,1,12,49,11,32,0,253,0,4,240,1,12,48,11,32,0,253,0,4,128,2,12,47,11,32,0,253,0,4,144,2,12,46,11,32,0,253,0,4,160,2,12,45,11,32,0,253,0,4,176,2,12,44,11,32,0,253,0,4,192,2,12,43,11,32,0,253,0,4,208,2,12,42,11,32,0,253,0,4,224,2,12,41,11,32,0,253,0,4,240,2,12,40,11,32,0,253,0,4,128,3,12,39,11,32,0,253,0,4,144,3,12,38,11,32,0,253,0,4,160,3,12,37,11,32,0,253,0,4,176,3,12,36,11,32,0,253,0,4,192,3,12,35,11,32,0,253,0,4,208,3,12,34,11,32,0,253,0,4,224,3,12,33,11,32,0,253,0,4,240,3,12,32,11,32,0,253,0,4,128,4,12,31,11,32,0,253,0,4,144,4,12,30,11,32,0,253,0,4,160,4,12,29,11,32,0,253,0,4,176,4,12,28,11,32,0,253,0,4,192,4,12,27,11,32,0,253,0,4,208,4,12,26,11,32,0,253,0,4,224,4,12,25,11,32,0,253,0,4,240,4,12,24,11,32,0,253,0,4,128,5,12,23,11,32,0,253,0,4,144,5,12,22,11,32,0,253,0,4,160,5,12,21,11,32,0,253,0,4,176,5,12,20,11,32,0,253,0,4,192,5,12,19,11,32,0,253,0,4,208,5,12,18,11,32,0,253,0,4,224,5,12,17,11,32,0,253,0,4,240,5,12,16,11,32,0,253,0,4,128,6,12,15,11,32,0,253,0,4,144,6,12,14,11,32,0,253,0,4,160,6,12,13,11,32,0,253,0,4,176,6,12,12,11,32,0,253,0,4,192,6,12,11,11,32,0,253,0,4,208,6,12,10,11,32,0,253,0,4,224,6,12,9,11,32,0,253,0,4,240,6,12,8,11,32,0,253,0,4,128,7,12,7,11,32,0,253,0,4,144,7,12,6,11,32,0,253,0,4,160,7,12,5,11,32,0,253,0,4,176,7,12,4,11,32,0,253,0,4,192,7,12,3,11,32,0,253,0,4,208,7,12,2,11,32,0,253,0,4,224,7,12,1,11,32,0,253,0,4,240,7,11,253,174,1,11,36,19,35,18,65,16,78,4,64,35,19,33,2,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,4,14,64,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,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,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,0,32,2,253,11,4,0,12,64,11,32,0,32,2,253,11,4,16,12,63,11,32,0,32,2,253,11,4,32,12,62,11,32,0,32,2,253,11,4,48,12,61,11,32,0,32,2,253,11,4,64,12,60,11,32,0,32,2,253,11,4,80,12,59,11,32,0,32,2,253,11,4,96,12,58,11,32,0,32,2,253,11,4,112,12,57,11,32,0,32,2,253,11,4,128,1,12,56,11,32,0,32,2,253,11,4,144,1,12,55,11,32,0,32,2,253,11,4,160,1,12,54,11,32,0,32,2,253,11,4,176,1,12,53,11,32,0,32,2,253,11,4,192,1,12,52,11,32,0,32,2,253,11,4,208,1,12,51,11,32,0,32,2,253,11,4,224,1,12,50,11,32,0,32,2,253,11,4,240,1,12,49,11,32,0,32,2,253,11,4,128,2,12,48,11,32,0,32,2,253,11,4,144,2,12,47,11,32,0,32,2,253,11,4,160,2,12,46,11,32,0,32,2,253,11,4,176,2,12,45,11,32,0,32,2,253,11,4,192,2,12,44,11,32,0,32,2,253,11,4,208,2,12,43,11,32,0,32,2,253,11,4,224,2,12,42,11,32,0,32,2,253,11,4,240,2,12,41,11,32,0,32,2,253,11,4,128,3,12,40,11,32,0,32,2,253,11,4,144,3,12,39,11,32,0,32,2,253,11,4,160,3,12,38,11,32,0,32,2,253,11,4,176,3,12,37,11,32,0,32,2,253,11,4,192,3,12,36,11,32,0,32,2,253,11,4,208,3,12,35,11,32,0,32,2,253,11,4,224,3,12,34,11,32,0,32,2,253,11,4,240,3,12,33,11,32,0,32,2,253,11,4,128,4,12,32,11,32,0,32,2,253,11,4,144,4,12,31,11,32,0,32,2,253,11,4,160,4,12,30,11,32,0,32,2,253,11,4,176,4,12,29,11,32,0,32,2,253,11,4,192,4,12,28,11,32,0,32,2,253,11,4,208,4,12,27,11,32,0,32,2,253,11,4,224,4,12,26,11,32,0,32,2,253,11,4,240,4,12,25,11,32,0,32,2,253,11,4,128,5,12,24,11,32,0,32,2,253,11,4,144,5,12,23,11,32,0,32,2,253,11,4,160,5,12,22,11,32,0,32,2,253,11,4,176,5,12,21,11,32,0,32,2,253,11,4,192,5,12,20,11,32,0,32,2,253,11,4,208,5,12,19,11,32,0,32,2,253,11,4,224,5,12,18,11,32,0,32,2,253,11,4,240,5,12,17,11,32,0,32,2,253,11,4,128,6,12,16,11,32,0,32,2,253,11,4,144,6,12,15,11,32,0,32,2,253,11,4,160,6,12,14,11,32,0,32,2,253,11,4,176,6,12,13,11,32,0,32,2,253,11,4,192,6,12,12,11,32,0,32,2,253,11,4,208,6,12,11,11,32,0,32,2,253,11,4,224,6,12,10,11,32,0,32,2,253,11,4,240,6,12,9,11,32,0,32,2,253,11,4,128,7,12,8,11,32,0,32,2,253,11,4,144,7,12,7,11,32,0,32,2,253,11,4,160,7,12,6,11,32,0,32,2,253,11,4,176,7,12,5,11,32,0,32,2,253,11,4,192,7,12,4,11,32,0,32,2,253,11,4,208,7,12,3,11,32,0,32,2,253,11,4,224,7,12,2,11,32,0,32,2,253,11,4,240,7,12,1,11,65,192,19,32,4,16,13,16,15,65,192,20,65,201,1,65,7,16,0,0,11,11,35,15,35,12,34,2,65,6,253,173,1,32,2,65,26,253,171,1,253,80,32,2,65,11,253,173,1,32,2,65,21,253,171,1,253,80,253,81,32,2,65,25,253,173,1,32,2,65,7,253,171,1,253,80,253,81,253,174,1,35,12,34,2,35,13,253,78,32,2,253,77,35,14,253,78,253,81,253,174,1,33,3,35,24,33,4,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,2,64,35,18,34,5,14,64,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,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,52,53,54,55,56,57,58,59,60,61,62,63,64,11,32,4,253,0,4,0,33,2,12,64,11,32,4,253,0,4,16,33,2,12,63,11,32,4,253,0,4,32,33,2,12,62,11,32,4,253,0,4,48,33,2,12,61,11,32,4,253,0,4,64,33,2,12,60,11,32,4,253,0,4,80,33,2,12,59,11,32,4,253,0,4,96,33,2,12,58,11,32,4,253,0,4,112,33,2,12,57,11,32,4,253,0,4,128,1,33,2,12,56,11,32,4,253,0,4,144,1,33,2,12,55,11,32,4,253,0,4,160,1,33,2,12,54,11,32,4,253,0,4,176,1,33,2,12,53,11,32,4,253,0,4,192,1,33,2,12,52,11,32,4,253,0,4,208,1,33,2,12,51,11,32,4,253,0,4,224,1,33,2,12,50,11,32,4,253,0,4,240,1,33,2,12,49,11,32,4,253,0,4,128,2,33,2,12,48,11,32,4,253,0,4,144,2,33,2,12,47,11,32,4,253,0,4,160,2,33,2,12,46,11,32,4,253,0,4,176,2,33,2,12,45,11,32,4,253,0,4,192,2,33,2,12,44,11,32,4,253,0,4,208,2,33,2,12,43,11,32,4,253,0,4,224,2,33,2,12,42,11,32,4,253,0,4,240,2,33,2,12,41,11,32,4,253,0,4,128,3,33,2,12,40,11,32,4,253,0,4,144,3,33,2,12,39,11,32,4,253,0,4,160,3,33,2,12,38,11,32,4,253,0,4,176,3,33,2,12,37,11,32,4,253,0,4,192,3,33,2,12,36,11,32,4,253,0,4,208,3,33,2,12,35,11,32,4,253,0,4,224,3,33,2,12,34,11,32,4,253,0,4,240,3,33,2,12,33,11,32,4,253,0,4,128,4,33,2,12,32,11,32,4,253,0,4,144,4,33,2,12,31,11,32,4,253,0,4,160,4,33,2,12,30,11,32,4,253,0,4,176,4,33,2,12,29,11,32,4,253,0,4,192,4,33,2,12,28,11,32,4,253,0,4,208,4,33,2,12,27,11,32,4,253,0,4,224,4,33,2,12,26,11,32,4,253,0,4,240,4,33,2,12,25,11,32,4,253,0,4,128,5,33,2,12,24,11,32,4,253,0,4,144,5,33,2,12,23,11,32,4,253,0,4,160,5,33,2,12,22,11,32,4,253,0,4,176,5,33,2,12,21,11,32,4,253,0,4,192,5,33,2,12,20,11,32,4,253,0,4,208,5,33,2,12,19,11,32,4,253,0,4,224,5,33,2,12,18,11,32,4,253,0,4,240,5,33,2,12,17,11,32,4,253,0,4,128,6,33,2,12,16,11,32,4,253,0,4,144,6,33,2,12,15,11,32,4,253,0,4,160,6,33,2,12,14,11,32,4,253,0,4,176,6,33,2,12,13,11,32,4,253,0,4,192,6,33,2,12,12,11,32,4,253,0,4,208,6,33,2,12,11,11,32,4,253,0,4,224,6,33,2,12,10,11,32,4,253,0,4,240,6,33,2,12,9,11,32,4,253,0,4,128,7,33,2,12,8,11,32,4,253,0,4,144,7,33,2,12,7,11,32,4,253,0,4,160,7,33,2,12,6,11,32,4,253,0,4,176,7,33,2,12,5,11,32,4,253,0,4,192,7,33,2,12,4,11,32,4,253,0,4,208,7,33,2,12,3,11,32,4,253,0,4,224,7,33,2,12,2,11,32,4,253,0,4,240,7,33,2,12,1,11,65,128,21,32,5,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,32,3,32,2,253,174,1,35,19,253,174,1,36,16,35,8,34,2,65,2,253,173,1,32,2,65,30,253,171,1,253,80,32,2,65,13,253,173,1,32,2,65,19,253,171,1,253,80,253,81,32,2,65,22,253,173,1,32,2,65,10,253,171,1,253,80,253,81,35,8,34,2,35,9,34,3,253,78,32,2,35,10,34,2,253,78,253,81,32,3,32,2,253,78,253,81,253,174,1,36,17,35,14,36,15,35,13,36,14,35,12,36,13,35,11,35,16,253,174,1,36,12,35,10,36,11,35,9,36,10,35,8,36,9,35,16,35,17,253,174,1,36,8,35,18,65,1,106,36,18,12,1,11,11,35,0,35,8,253,174,1,36,0,35,1,35,9,253,174,1,36,1,35,2,35,10,253,174,1,36,2,35,3,35,11,253,174,1,36,3,35,4,35,12,253,174,1,36,4,35,5,35,13,253,174,1,36,5,35,6,35,14,253,174,1,36,6,35,7,35,15,253,174,1,36,7,16,17,32,1,35,0,253,27,0,16,18,54,2,0,32,1,35,1,253,27,0,16,18,54,2,4,32,1,35,2,253,27,0,16,18,54,2,8,32,1,35,3,253,27,0,16,18,54,2,12,32,1,35,4,253,27,0,16,18,54,2,16,32,1,35,5,253,27,0,16,18,54,2,20,32,1,35,6,253,27,0,16,18,54,2,24,32,1,35,7,253,27,0,16,18,54,2,28,32,1,35,0,253,27,1,16,18,54,2,32,32,1,35,1,253,27,1,16,18,54,2,36,32,1,35,2,253,27,1,16,18,54,2,40,32,1,35,3,253,27,1,16,18,54,2,44,32,1,35,4,253,27,1,16,18,54,2,48,32,1,35,5,253,27,1,16,18,54,2,52,32,1,35,6,253,27,1,16,18,54,2,56,32,1,35,7,253,27,1,16,18,54,2,60,32,1,65,64,107,35,0,253,27,2,16,18,54,2,0,32,1,35,1,253,27,2,16,18,54,2,68,32,1,35,2,253,27,2,16,18,54,2,72,32,1,35,3,253,27,2,16,18,54,2,76,32,1,35,4,253,27,2,16,18,54,2,80,32,1,35,5,253,27,2,16,18,54,2,84,32,1,35,6,253,27,2,16,18,54,2,88,32,1,35,7,253,27,2,16,18,54,2,92,32,1,35,0,253,27,3,16,18,54,2,96,32,1,35,1,253,27,3,16,18,54,2,100,32,1,35,2,253,27,3,16,18,54,2,104,32,1,35,3,253,27,3,16,18,54,2,108,32,1,35,4,253,27,3,16,18,54,2,112,32,1,35,5,253,27,3,16,18,54,2,116,32,1,35,6,253,27,3,16,18,54,2,120,32,1,35,7,253,27,3,16,18,54,2,124,15,11,65,128,21,32,4,16,13,16,15,65,192,20,65,213,2,65,7,16,0,0,11,203,2,1,5,127,3,64,32,1,65,16,72,4,64,32,1,65,2,116,34,2,65,1,106,33,3,35,53,32,2,65,2,116,106,32,2,65,3,106,34,4,35,55,34,5,106,45,0,0,32,2,32,5,106,45,0,0,65,24,116,32,3,32,5,106,45,0,0,65,16,116,114,32,2,65,2,106,34,2,32,5,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,3,65,2,116,106,35,55,34,3,32,1,65,16,106,65,2,116,34,5,65,3,106,106,45,0,0,32,3,32,5,106,45,0,0,65,24,116,32,5,65,1,106,32,3,106,45,0,0,65,16,116,114,32,5,65,2,106,32,3,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,2,65,2,116,106,35,55,34,2,32,1,65,32,106,65,2,116,34,3,65,3,106,106,45,0,0,32,2,32,3,106,45,0,0,65,24,116,32,3,65,1,106,32,2,106,45,0,0,65,16,116,114,32,3,65,2,106,32,2,106,45,0,0,65,8,116,114,114,54,2,0,35,53,32,4,65,2,116,106,35,55,34,2,32,1,65,48,106,65,2,116,34,3,65,3,106,106,45,0,0,32,2,32,3,106,45,0,0,65,24,116,32,3,65,1,106,32,2,106,45,0,0,65,16,116,114,32,3,65,2,106,32,2,106,45,0,0,65,8,116,114,114,54,2,0,32,1,65,1,106,33,1,12,1,11,11,35,53,32,0,16,19,11,99,1,3,127,3,64,32,2,65,192,0,72,4,64,32,2,65,2,116,34,1,35,53,106,35,55,34,3,32,1,65,3,106,106,45,0,0,32,1,32,3,106,45,0,0,65,24,116,32,1,65,1,106,32,3,106,45,0,0,65,16,116,114,32,1,65,2,106,32,3,106,45,0,0,65,8,116,114,114,54,2,0,32,2,65,1,106,33,2,12,1,11,11,35,53,32,0,16,19,11,74,0,65,231,204,167,208,6,36,31,65,133,221,158,219,123,36,32,65,242,230,187,227,3,36,33,65,186,234,191,170,122,36,34,65,255,164,185,136,5,36,35,65,140,209,149,216,121,36,36,65,171,179,143,252,1,36,37,65,153,154,131,223,5,36,38,65,0,36,58,65,0,36,59,11,227,3,1,2,127,35,31,36,39,35,32,36,40,35,33,36,41,35,34,36,42,35,35,36,43,35,36,36,44,35,37,36,45,35,38,36,46,65,0,36,47,3,64,35,47,65,16,73,4,64,35,47,65,2,116,34,2,32,0,106,32,1,32,2,65,3,106,106,45,0,0,32,1,32,2,106,45,0,0,65,24,116,32,1,32,2,65,1,106,106,45,0,0,65,16,116,114,32,1,32,2,65,2,106,106,45,0,0,65,8,116,114,114,54,2,0,35,47,65,1,106,36,47,12,1,11,11,65,16,36,47,3,64,35,47,65,192,0,73,4,64,32,0,35,47,65,2,116,106,32,0,35,47,65,16,107,65,2,116,106,40,2,0,32,0,35,47,65,7,107,65,2,116,106,40,2,0,32,0,35,47,65,2,107,65,2,116,106,40,2,0,34,1,65,17,120,32,1,65,19,120,115,32,1,65,10,118,115,106,32,0,35,47,65,15,107,65,2,116,106,40,2,0,34,1,65,7,120,32,1,65,18,120,115,32,1,65,3,118,115,106,106,54,2,0,35,47,65,1,106,36,47,12,1,11,11,65,0,36,47,3,64,35,47,65,192,0,73,4,64,35,47,65,2,116,34,1,32,0,106,40,2,0,32,1,35,29,106,40,2,0,35,46,35,43,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,43,34,1,35,44,113,35,45,32,1,65,127,115,113,115,106,106,106,36,48,35,39,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,40,34,2,35,41,34,3,113,35,39,34,1,32,2,113,32,1,32,3,113,115,115,106,36,49,35,45,36,46,35,44,36,45,35,43,36,44,35,42,35,48,106,36,43,35,41,36,42,35,40,36,41,35,39,36,40,35,48,35,49,106,36,39,35,47,65,1,106,36,47,12,1,11,11,35,31,35,39,106,36,31,35,32,35,40,106,36,32,35,33,35,41,106,36,33,35,34,35,42,106,36,34,35,35,35,43,106,36,35,35,36,35,44,106,36,36,35,37,35,45,106,36,37,35,38,35,46,106,36,38,11,174,1,1,2,127,35,59,32,1,106,36,59,35,58,4,64,65,192,0,35,58,107,34,2,32,1,76,4,64,35,51,35,58,106,32,0,32,2,252,10,0,0,35,58,32,2,106,36,58,65,192,0,35,58,107,33,2,32,1,65,192,0,35,58,107,107,33,1,35,53,35,51,16,23,65,0,36,58,5,35,51,35,58,106,32,0,32,1,252,10,0,0,35,58,32,1,106,36,58,15,11,11,3,64,32,3,32,1,65,192,0,109,72,4,64,35,53,32,0,32,2,106,16,23,32,3,65,1,106,33,3,32,2,65,64,107,33,2,12,1,11,11,32,1,65,63,113,34,1,4,64,35,51,35,58,106,32,0,32,2,106,32,1,252,10,0,0,35,58,32,1,106,36,58,11,11,231,1,1,2,127,35,51,35,58,106,65,128,1,58,0,0,35,58,65,1,106,36,58,35,58,65,56,74,4,64,35,51,35,58,106,34,1,65,192,0,35,58,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,53,35,51,16,23,65,0,36,58,11,35,51,35,58,106,34,1,65,56,35,58,107,106,33,2,3,64,32,1,32,2,73,4,64,32,1,65,0,58,0,0,32,1,65,1,106,33,1,12,1,11,11,35,51,35,59,65,128,128,128,128,2,109,16,18,54,2,56,35,51,35,59,65,3,116,16,18,54,2,60,35,53,35,51,16,23,32,0,35,31,16,18,54,2,0,32,0,35,32,16,18,54,2,4,32,0,35,33,16,18,54,2,8,32,0,35,34,16,18,54,2,12,32,0,35,35,16,18,54,2,16,32,0,35,36,16,18,54,2,20,32,0,35,37,16,18,54,2,24,32,0,35,38,16,18,54,2,28,11,14,0,16,22,35,55,32,0,16,24,35,57,16,25,11,253,1,1,2,127,35,31,36,39,35,32,36,40,35,33,36,41,35,34,36,42,35,35,36,43,35,36,36,44,35,37,36,45,35,38,36,46,65,0,36,47,3,64,35,47,65,192,0,73,4,64,32,0,35,47,65,2,116,106,40,2,0,35,46,35,43,34,1,65,6,120,32,1,65,11,120,115,32,1,65,25,120,115,106,35,43,34,1,35,44,113,35,45,32,1,65,127,115,113,115,106,106,36,48,35,39,34,1,65,2,120,32,1,65,13,120,115,32,1,65,22,120,115,35,40,34,2,35,41,34,1,113,32,2,35,39,34,2,113,32,1,32,2,113,115,115,106,36,49,35,45,36,46,35,44,36,45,35,43,36,44,35,42,35,48,106,36,43,35,41,36,42,35,40,36,41,35,39,36,40,35,48,35,49,106,36,39,35,47,65,1,106,36,47,12,1,11,11,35,31,35,39,106,36,31,35,32,35,40,106,36,32,35,33,35,41,106,36,33,35,34,35,42,106,36,34,35,35,35,43,106,36,35,35,36,35,44,106,36,36,35,37,35,45,106,36,37,35,38,35,46,106,36,38,11,86,0,16,22,35,53,32,0,16,23,35,30,16,27,32,1,35,31,16,18,54,2,0,32,1,35,32,16,18,54,2,4,32,1,35,33,16,18,54,2,8,32,1,35,34,16,18,54,2,12,32,1,35,35,16,18,54,2,16,32,1,35,36,16,18,54,2,20,32,1,35,37,16,18,54,2,24,32,1,35,38,16,18,54,2,28,11,63,0,16,16,65,196,10,40,2,0,36,29,65,148,13,40,2,0,36,30,65,192,0,16,11,36,50,35,50,36,51,65,128,8,16,11,36,52,35,52,36,53,65,128,4,16,11,36,54,35,54,36,55,65,32,16,11,36,56,35,56,36,57,11,11,141,12,38,0,65,140,8,11,2,28,1,0,65,152,8,11,136,2,1,0,0,0,0,1,0,0,152,47,138,66,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,241,155,193,193,105,155,228,134,71,190,239,198,157,193,15,204,161,12,36,111,44,233,45,170,132,116,74,220,169,176,92,218,136,249,118,82,81,62,152,109,198,49,168,200,39,3,176,199,127,89,191,243,11,224,198,71,145,167,213,81,99,202,6,103,41,41,20,133,10,183,39,56,33,27,46,252,109,44,77,19,13,56,83,84,115,10,101,187,10,106,118,46,201,194,129,133,44,114,146,161,232,191,162,75,102,26,168,112,139,75,194,163,81,108,199,25,232,146,209,36,6,153,214,133,53,14,244,112,160,106,16,22,193,164,25,8,108,55,30,76,119,72,39,181,188,176,52,179,12,28,57,74,170,216,78,79,202,156,91,243,111,46,104,238,130,143,116,111,99,165,120,20,120,200,132,8,2,199,140,250,255,190,144,235,108,80,164,247,163,249,190,242,120,113,198,0,65,172,10,11,1,44,0,65,184,10,11,21,4,0,0,0,16,0,0,0,32,4,0,0,32,4,0,0,0,1,0,0,64,0,65,220,10,11,2,28,1,0,65,232,10,11,136,2,1,0,0,0,0,1,0,0,152,47,138,194,145,68,55,113,207,251,192,181,165,219,181,233,91,194,86,57,241,17,241,89,164,130,63,146,213,94,28,171,152,170,7,216,1,91,131,18,190,133,49,36,195,125,12,85,116,93,190,114,254,177,222,128,167,6,220,155,116,243,155,193,193,105,155,100,134,71,254,240,198,237,225,15,84,242,12,36,111,52,233,79,190,132,201,108,30,65,185,97,250,136,249,22,82,81,198,242,109,90,142,168,101,252,25,176,199,158,217,185,195,49,18,154,160,234,14,231,43,35,177,253,176,62,53,199,213,186,105,48,95,109,151,203,143,17,15,90,253,238,30,220,137,182,53,10,4,122,11,222,157,202,244,88,22,91,93,225,134,62,127,0,128,137,8,55,50,234,7,165,55,149,171,111,16,97,64,23,241,214,140,13,109,59,170,205,55,190,187,192,218,59,97,131,99,163,72,219,49,233,2,11,167,92,209,111,202,250,26,82,49,132,51,49,149,26,212,110,144,120,67,109,242,145,156,195,189,171,204,158,230,160,201,181,60,182,47,83,198,65,199,210,163,126,35,7,104,75,149,164,118,29,25,76,0,65,252,12,11,1,44,0,65,136,13,11,21,4,0,0,0,16,0,0,0,112,5,0,0,112,5,0,0,0,1,0,0,64,0,65,172,13,11,1,44,0,65,184,13,11,35,2,0,0,0,28,0,0,0,73,0,110,0,118,0,97,0,108,0,105,0,100,0,32,0,108,0,101,0,110,0,103,0,116,0,104,0,65,220,13,11,1,60,0,65,232,13,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,98,0,117,0,102,0,102,0,101,0,114,0,46,0,116,0,115,0,65,156,14,11,1,60,0,65,168,14,11,47,2,0,0,0,40,0,0,0,65,0,108,0,108,0,111,0,99,0,97,0,116,0,105,0,111,0,110,0,32,0,116,0,111,0,111,0,32,0,108,0,97,0,114,0,103,0,101,0,65,220,14,11,1,60,0,65,232,14,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,99,0,109,0,115,0,46,0,116,0,115,0,65,156,15,11,1,60,0,65,168,15,11,37,2,0,0,0,30,0,0,0,126,0,108,0,105,0,98,0,47,0,114,0,116,0,47,0,116,0,108,0,115,0,102,0,46,0,116,0,115,0,65,252,15,11,1,60,0,65,136,16,11,43,2,0,0,0,36,0,0,0,73,0,110,0,100,0,101,0,120,0,32,0,111,0,117,0,116,0,32,0,111,0,102,0,32,0,114,0,97,0,110,0,103,0,101,0,65,188,16,11,1,44,0,65,200,16,11,33,2,0,0,0,26,0,0,0,126,0,108,0,105,0,98,0,47,0,97,0,114,0,114,0,97,0,121,0,46,0,116,0,115,0,65,236,16,11,1,124,0,65,248,16,11,107,2,0,0,0,100,0,0,0,116,0,111,0,83,0,116,0,114,0,105,0,110,0,103,0,40,0,41,0,32,0,114,0,97,0,100,0,105,0,120,0,32,0,97,0,114,0,103,0,117,0,109,0,101,0,110,0,116,0,32,0,109,0,117,0,115,0,116,0,32,0,98,0,101,0,32,0,98,0,101,0,116,0,119,0,101,0,101,0,110,0,32,0,50,0,32,0,97,0,110,0,100,0,32,0,51,0,54,0,65,236,17,11,1,60,0,65,248,17,11,45,2,0,0,0,38,0,0,0,126,0,108,0,105,0,98,0,47,0,117,0,116,0,105,0,108,0,47,0,110,0,117,0,109,0,98,0,101,0,114,0,46,0,116,0,115,0,65,172,18,11,1,28,0,65,184,18,11,9,2,0,0,0,2,0,0,0,48,0,65,204,18,11,1,92,0,65,216,18,11,79,2,0,0,0,72,0,0,0,48,0,49,0,50,0,51,0,52,0,53,0,54,0,55,0,56,0,57,0,97,0,98,0,99,0,100,0,101,0,102,0,103,0,104,0,105,0,106,0,107,0,108,0,109,0,110,0,111,0,112,0,113,0,114,0,115,0,116,0,117,0,118,0,119,0,120,0,121,0,122,0,65,172,19,11,1,92,0,65,184,19,11,79,2,0,0,0,72,0,0,0,115,0,101,0,116,0,86,0,49,0,50,0,56,0,58,0,32,0,101,0,120,0,112,0,101,0,99,0,116,0,32,0,105,0,32,0,102,0,114,0,111,0,109,0,32,0,48,0,32,0,116,0,111,0,32,0,54,0,51,0,44,0,32,0,103,0,111,0,116,0,32,0,65,140,20,11,1,28,0,65,152,20,11,1,2,0,65,172,20,11,1,60,0,65,184,20,11,51,2,0,0,0,44,0,0,0,97,0,115,0,115,0,101,0,109,0,98,0,108,0,121,0,47,0,117,0,116,0,105,0,108,0,115,0,47,0,118,0,49,0,50,0,56,0,46,0,116,0,115,0,65,236,20,11,1,92,0,65,248,20,11,79,2,0,0,0,72,0,0,0,103,0,101,0,116,0,86,0,49,0,50,0,56,0,58,0,32,0,101,0,120,0,112,0,101,0,99,0,116,0,32,0,105,0,32,0,102,0,114,0,111,0,109,0,32,0,48,0,32,0,116,0,111,0,32,0,54,0,51,0,44,0,32,0,103,0,111,0,116,0,32]);var Sw={env:{abort:(r,e,t,s)=>{throw Error(`abort: ${r}:${e}:${t}:${s}`)}}};function lm(r){return(r!==void 0?r:WebAssembly.validate(cm))?new WebAssembly.Instance(new WebAssembly.Module(cm),Sw).exports:new WebAssembly.Instance(new WebAssembly.Module(Ew),Sw).exports}var tt,hT,Oi,Tc,Pc,dT,Iw,fT;function pT(r){tt=lm(r),hT=!!tt.HAS_SIMD.valueOf(),Oi=tt.input.value,Tc=tt.output.value,Pc=new Uint8Array(tt.memory.buffer,Oi,tt.INPUT_LENGTH),dT=new Uint8Array(tt.memory.buffer,Tc,tt.PARALLEL_FACTOR*32),Iw=new Uint8Array(tt.memory.buffer,Tc,32),fT=new Uint32Array(tt.memory.buffer,Oi,tt.INPUT_LENGTH)}pT();function _w(r){return r.length===64?mT(r):r.length<=tt.INPUT_LENGTH?(Pc.set(r),tt.digest(r.length),um()):(tt.init(),gT(r),yT())}function mT(r){if(r.length===64)return Pc.set(r),tt.digest64(Oi,Tc),um();throw new Error("InvalidLengthForDigest64")}function gT(r){let e=tt.INPUT_LENGTH;if(r.length>e)for(let t=0;t<r.length;t+=e){let s=r.subarray(t,t+e);Pc.set(s),tt.update(Oi,s.length)}else Pc.set(r),tt.update(Oi,r.length)}function yT(){return tt.final(Tc),um()}function um(){let r=vw(32);return r.set(Iw),r}ot();var Tw=we(Cw(),1),wT=typeof window=="object"&&typeof document=="object"&&document.nodeType===9,Pw=(0,Tw.default)();var kw=Pw&&!wT;var ate=typeof globalThis.process<"u"&&typeof globalThis.process.release<"u"&&globalThis.process.release.name==="node"&&!Pw,cte=typeof importScripts=="function"&&typeof self<"u"&&typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,lte=typeof globalThis.process<"u"&&typeof globalThis.process.env<"u"&&globalThis.process.env["NODE"+"_"+"ENV"]==="test",ute=typeof navigator<"u"&&navigator.product==="ReactNative";function Mw(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ih(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function ah(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function _t(r,...e){if(!Mw(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function hm(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Ow(r,e){_t(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function As(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Cs(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function xT(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var vT=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ET(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function ch(r){if(typeof r=="string")r=ET(r);else if(Mw(r))r=lh(r);else throw new Error("Uint8Array expected, got "+typeof r);return r}function Lw(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function Rw(r,e){if(r.length!==e.length)return!1;let t=0;for(let s=0;s<r.length;s++)t|=r[s]^e[s];return t===0}var dm=(r,e)=>{function t(s,...n){if(_t(s),!vT)throw new Error("Non little-endian hardware is not yet supported");if(r.nonceLength!==void 0){let u=n[0];if(!u)throw new Error("nonce / iv required");r.varSizeNonce?_t(u):_t(u,r.nonceLength)}let o=r.tagLength;o&&n[1]!==void 0&&_t(n[1]);let i=e(s,...n),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");_t(h)}},c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,_t(u),a(i.encrypt.length,h),i.encrypt(u,h)},decrypt(u,h){if(_t(u),o&&u.length<o)throw new Error("invalid ciphertext length: smaller than tagLength="+o);return a(i.decrypt.length,h),i.decrypt(u,h)}}}return Object.assign(t,r),t};function fm(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error("invalid output length, expected "+r+", got: "+e.length);if(t&&!ST(e))throw new Error("invalid output, must be aligned");return e}function Dw(r,e,t,s){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,s);let n=BigInt(32),o=BigInt(4294967295),i=Number(t>>n&o),a=Number(t&o),c=s?4:0,l=s?0:4;r.setUint32(e+c,i,s),r.setUint32(e+l,a,s)}function Nw(r,e,t){ih(t);let s=new Uint8Array(16),n=xT(s);return Dw(n,0,BigInt(e),t),Dw(n,8,BigInt(r),t),s}function ST(r){return r.byteOffset%4===0}function lh(r){return Uint8Array.from(r)}var Fw=r=>Uint8Array.from(r.split("").map(e=>e.charCodeAt(0))),IT=Fw("expand 16-byte k"),_T=Fw("expand 32-byte k"),AT=As(IT),CT=As(_T);function q(r,e){return r<<e|r>>>32-e}function pm(r){return r.byteOffset%4===0}var uh=64,TT=16,Uw=2**32-1,Bw=new Uint32Array;function PT(r,e,t,s,n,o,i,a){let c=n.length,l=new Uint8Array(uh),u=As(l),h=pm(n)&&pm(o),d=h?As(n):Bw,f=h?As(o):Bw;for(let p=0;p<c;i++){if(r(e,t,s,u,i,a),i>=Uw)throw new Error("arx: counter overflow");let m=Math.min(uh,c-p);if(h&&m===uh){let g=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let y=0,w;y<TT;y++)w=g+y,f[w]=d[w]^u[y];p+=uh;continue}for(let g=0,y;g<m;g++)y=p+g,o[y]=n[y]^l[g];p+=m}}function mm(r,e){let{allowShortKeys:t,extendNonceFn:s,counterLength:n,counterRight:o,rounds:i}=Lw({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return ah(n),ah(i),ih(o),ih(t),(a,c,l,u,h=0)=>{_t(a),_t(c),_t(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),_t(u),ah(h),h<0||h>=Uw)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let f=[],p=a.length,m,g;if(p===32)f.push(m=lh(a)),g=CT;else if(p===16&&t)m=new Uint8Array(32),m.set(a),m.set(a,16),g=AT,f.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);pm(c)||f.push(c=lh(c));let y=As(m);if(s){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");s(g,y,As(c.subarray(0,16)),y),c=c.subarray(16)}let w=16-n;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){let x=new Uint8Array(12);x.set(c,o?0:12-c.length),c=x,f.push(c)}let b=As(c);return PT(r,g,y,b,l,u,h,i),Cs(...f),u}}var gt=(r,e)=>r[e++]&255|(r[e++]&255)<<8,gm=class{constructor(e){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,e=ch(e),_t(e,32);let t=gt(e,0),s=gt(e,2),n=gt(e,4),o=gt(e,6),i=gt(e,8),a=gt(e,10),c=gt(e,12),l=gt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|s<<3)&8191,this.r[2]=(s>>>10|n<<6)&7939,this.r[3]=(n>>>7|o<<9)&8191,this.r[4]=(o>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=gt(e,16+2*u)}process(e,t,s=!1){let n=s?0:2048,{h:o,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],h=i[4],d=i[5],f=i[6],p=i[7],m=i[8],g=i[9],y=gt(e,t+0),w=gt(e,t+2),b=gt(e,t+4),x=gt(e,t+6),E=gt(e,t+8),P=gt(e,t+10),T=gt(e,t+12),D=gt(e,t+14),v=o[0]+(y&8191),M=o[1]+((y>>>13|w<<3)&8191),F=o[2]+((w>>>10|b<<6)&8191),B=o[3]+((b>>>7|x<<9)&8191),I=o[4]+((x>>>4|E<<12)&8191),S=o[5]+(E>>>1&8191),_=o[6]+((E>>>14|P<<2)&8191),k=o[7]+((P>>>11|T<<5)&8191),O=o[8]+((T>>>8|D<<8)&8191),N=o[9]+(D>>>5|n),C=0,R=C+v*a+M*(5*g)+F*(5*m)+B*(5*p)+I*(5*f);C=R>>>13,R&=8191,R+=S*(5*d)+_*(5*h)+k*(5*u)+O*(5*l)+N*(5*c),C+=R>>>13,R&=8191;let U=C+v*c+M*a+F*(5*g)+B*(5*m)+I*(5*p);C=U>>>13,U&=8191,U+=S*(5*f)+_*(5*d)+k*(5*h)+O*(5*u)+N*(5*l),C+=U>>>13,U&=8191;let z=C+v*l+M*c+F*a+B*(5*g)+I*(5*m);C=z>>>13,z&=8191,z+=S*(5*p)+_*(5*f)+k*(5*d)+O*(5*h)+N*(5*u),C+=z>>>13,z&=8191;let ee=C+v*u+M*l+F*c+B*a+I*(5*g);C=ee>>>13,ee&=8191,ee+=S*(5*m)+_*(5*p)+k*(5*f)+O*(5*d)+N*(5*h),C+=ee>>>13,ee&=8191;let te=C+v*h+M*u+F*l+B*c+I*a;C=te>>>13,te&=8191,te+=S*(5*g)+_*(5*m)+k*(5*p)+O*(5*f)+N*(5*d),C+=te>>>13,te&=8191;let Z=C+v*d+M*h+F*u+B*l+I*c;C=Z>>>13,Z&=8191,Z+=S*a+_*(5*g)+k*(5*m)+O*(5*p)+N*(5*f),C+=Z>>>13,Z&=8191;let se=C+v*f+M*d+F*h+B*u+I*l;C=se>>>13,se&=8191,se+=S*c+_*a+k*(5*g)+O*(5*m)+N*(5*p),C+=se>>>13,se&=8191;let xe=C+v*p+M*f+F*d+B*h+I*u;C=xe>>>13,xe&=8191,xe+=S*l+_*c+k*a+O*(5*g)+N*(5*m),C+=xe>>>13,xe&=8191;let $e=C+v*m+M*p+F*f+B*d+I*h;C=$e>>>13,$e&=8191,$e+=S*u+_*l+k*c+O*a+N*(5*g),C+=$e>>>13,$e&=8191;let oe=C+v*g+M*m+F*p+B*f+I*d;C=oe>>>13,oe&=8191,oe+=S*h+_*u+k*l+O*c+N*a,C+=oe>>>13,oe&=8191,C=(C<<2)+C|0,C=C+R|0,R=C&8191,C=C>>>13,U+=C,o[0]=R,o[1]=U,o[2]=z,o[3]=ee,o[4]=te,o[5]=Z,o[6]=se,o[7]=xe,o[8]=$e,o[9]=oe}finalize(){let{h:e,pad:t}=this,s=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=n,n=e[a]>>>13,e[a]&=8191;e[0]+=n*5,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,s[0]=e[0]+5,n=s[0]>>>13,s[0]&=8191;for(let a=1;a<10;a++)s[a]=e[a]+n,n=s[a]>>>13,s[a]&=8191;s[9]-=8192;let o=(n^1)-1;for(let a=0;a<10;a++)s[a]&=o;o=~o;for(let a=0;a<10;a++)e[a]=e[a]&o|s[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;Cs(s)}update(e){hm(this),e=ch(e),_t(e);let{buffer:t,blockLen:s}=this,n=e.length;for(let o=0;o<n;){let i=Math.min(s-this.pos,n-o);if(i===s){for(;s<=n-o;o+=s)this.process(e,o);continue}t.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===s&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Cs(this.h,this.r,this.buffer,this.pad)}digestInto(e){hm(this),Ow(e,this),this.finished=!0;let{buffer:t,h:s}=this,{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let o=0;for(let i=0;i<8;i++)e[o++]=s[i]>>>0,e[o++]=s[i]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}};function kT(r){let e=(s,n)=>r(n).update(ch(s)).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=s=>r(s),e}var Kw=kT(r=>new gm(r));function qw(r,e,t,s,n,o=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],h=e[1],d=e[2],f=e[3],p=e[4],m=e[5],g=e[6],y=e[7],w=n,b=t[0],x=t[1],E=t[2],P=i,T=a,D=c,v=l,M=u,F=h,B=d,I=f,S=p,_=m,k=g,O=y,N=w,C=b,R=x,U=E;for(let ee=0;ee<o;ee+=2)P=P+M|0,N=q(N^P,16),S=S+N|0,M=q(M^S,12),P=P+M|0,N=q(N^P,8),S=S+N|0,M=q(M^S,7),T=T+F|0,C=q(C^T,16),_=_+C|0,F=q(F^_,12),T=T+F|0,C=q(C^T,8),_=_+C|0,F=q(F^_,7),D=D+B|0,R=q(R^D,16),k=k+R|0,B=q(B^k,12),D=D+B|0,R=q(R^D,8),k=k+R|0,B=q(B^k,7),v=v+I|0,U=q(U^v,16),O=O+U|0,I=q(I^O,12),v=v+I|0,U=q(U^v,8),O=O+U|0,I=q(I^O,7),P=P+F|0,U=q(U^P,16),k=k+U|0,F=q(F^k,12),P=P+F|0,U=q(U^P,8),k=k+U|0,F=q(F^k,7),T=T+B|0,N=q(N^T,16),O=O+N|0,B=q(B^O,12),T=T+B|0,N=q(N^T,8),O=O+N|0,B=q(B^O,7),D=D+I|0,C=q(C^D,16),S=S+C|0,I=q(I^S,12),D=D+I|0,C=q(C^D,8),S=S+C|0,I=q(I^S,7),v=v+M|0,R=q(R^v,16),_=_+R|0,M=q(M^_,12),v=v+M|0,R=q(R^v,8),_=_+R|0,M=q(M^_,7);let z=0;s[z++]=i+P|0,s[z++]=a+T|0,s[z++]=c+D|0,s[z++]=l+v|0,s[z++]=u+M|0,s[z++]=h+F|0,s[z++]=d+B|0,s[z++]=f+I|0,s[z++]=p+S|0,s[z++]=m+_|0,s[z++]=g+k|0,s[z++]=y+O|0,s[z++]=w+N|0,s[z++]=b+C|0,s[z++]=x+R|0,s[z++]=E+U|0}function DT(r,e,t,s){let n=r[0],o=r[1],i=r[2],a=r[3],c=e[0],l=e[1],u=e[2],h=e[3],d=e[4],f=e[5],p=e[6],m=e[7],g=t[0],y=t[1],w=t[2],b=t[3];for(let E=0;E<20;E+=2)n=n+c|0,g=q(g^n,16),d=d+g|0,c=q(c^d,12),n=n+c|0,g=q(g^n,8),d=d+g|0,c=q(c^d,7),o=o+l|0,y=q(y^o,16),f=f+y|0,l=q(l^f,12),o=o+l|0,y=q(y^o,8),f=f+y|0,l=q(l^f,7),i=i+u|0,w=q(w^i,16),p=p+w|0,u=q(u^p,12),i=i+u|0,w=q(w^i,8),p=p+w|0,u=q(u^p,7),a=a+h|0,b=q(b^a,16),m=m+b|0,h=q(h^m,12),a=a+h|0,b=q(b^a,8),m=m+b|0,h=q(h^m,7),n=n+l|0,b=q(b^n,16),p=p+b|0,l=q(l^p,12),n=n+l|0,b=q(b^n,8),p=p+b|0,l=q(l^p,7),o=o+u|0,g=q(g^o,16),m=m+g|0,u=q(u^m,12),o=o+u|0,g=q(g^o,8),m=m+g|0,u=q(u^m,7),i=i+h|0,y=q(y^i,16),d=d+y|0,h=q(h^d,12),i=i+h|0,y=q(y^i,8),d=d+y|0,h=q(h^d,7),a=a+c|0,w=q(w^a,16),f=f+w|0,c=q(c^f,12),a=a+c|0,w=q(w^a,8),f=f+w|0,c=q(c^f,7);let x=0;s[x++]=n,s[x++]=o,s[x++]=i,s[x++]=a,s[x++]=g,s[x++]=y,s[x++]=w,s[x++]=b}var MT=mm(qw,{counterRight:!1,counterLength:4,allowShortKeys:!1}),OT=mm(qw,{counterRight:!1,counterLength:8,extendNonceFn:DT,allowShortKeys:!1});var LT=new Uint8Array(16),Hw=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(LT.subarray(t))},RT=new Uint8Array(32);function zw(r,e,t,s,n){let o=r(e,t,RT),i=Kw.create(o);n&&Hw(i,n),Hw(i,s);let a=Nw(s.length,n?n.length:0,!0);i.update(a);let c=i.digest();return Cs(o,a),c}var $w=r=>(e,t,s)=>({encrypt(o,i){let a=o.length;i=fm(a+16,i,!1),i.set(o);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=zw(r,e,t,c,s);return i.set(l,a),Cs(l),i},decrypt(o,i){i=fm(o.length-16,i,!1);let a=o.subarray(0,-16),c=o.subarray(-16),l=zw(r,e,t,a,s);if(!Rw(c,l))throw new Error("invalid tag");return i.set(o.subarray(0,-16)),r(e,t,i,i,1),Cs(l),i}}),ym=dm({blockSize:64,nonceLength:12,tagLength:16},$w(MT)),vte=dm({blockSize:64,nonceLength:24,tagLength:16},$w(OT));var Ts=we(re("node:crypto"),1),po=Ts&&typeof Ts=="object"&&"webcrypto"in Ts?Ts.webcrypto:Ts&&typeof Ts=="object"&&"randomBytes"in Ts?Ts:void 0;function go(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function mo(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function At(r,...e){if(!go(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function kc(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");mo(r.outputLen),mo(r.blockLen)}function Ri(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Vw(r,e){At(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function Lr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function hh(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Rr(r,e){return r<<32-e|r>>>e}var Ww=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",NT=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function yo(r){if(At(r),Ww)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=NT[r[t]];return e}var Ps={_0:48,_9:57,A:65,F:70,a:97,f:102};function Gw(r){if(r>=Ps._0&&r<=Ps._9)return r-Ps._0;if(r>=Ps.A&&r<=Ps.F)return r-(Ps.A-10);if(r>=Ps.a&&r<=Ps.f)return r-(Ps.a-10)}function dh(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ww)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let s=new Uint8Array(t);for(let n=0,o=0;n<t;n++,o+=2){let i=Gw(r.charCodeAt(o)),a=Gw(r.charCodeAt(o+1));if(i===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}s[n]=i*16+a}return s}function bm(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function sn(r){return typeof r=="string"&&(r=bm(r)),At(r),r}function Ni(...r){let e=0;for(let s=0;s<r.length;s++){let n=r[s];At(n),e+=n.length}let t=new Uint8Array(e);for(let s=0,n=0;s<r.length;s++){let o=r[s];t.set(o,n),n+=o.length}return t}var Li=class{};function wm(r){let e=s=>r().update(sn(s)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Dc(r=32){if(po&&typeof po.getRandomValues=="function")return po.getRandomValues(new Uint8Array(r));if(po&&typeof po.randomBytes=="function")return Uint8Array.from(po.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function BT(r,e,t,s){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,s);let n=BigInt(32),o=BigInt(4294967295),i=Number(t>>n&o),a=Number(t&o),c=s?4:0,l=s?0:4;r.setUint32(e+c,i,s),r.setUint32(e+l,a,s)}function jw(r,e,t){return r&e^~r&t}function Yw(r,e,t){return r&e^r&t^e&t}var Mc=class extends Li{constructor(e,t,s,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=hh(this.buffer)}update(e){Ri(this),e=sn(e),At(e);let{view:t,buffer:s,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(n-this.pos,o-i);if(a===n){let c=hh(e);for(;n<=o-i;i+=n)this.process(c,i);continue}s.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ri(this),Vw(e,this),this.finished=!0;let{buffer:t,view:s,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,Lr(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(s,0),i=0);for(let h=i;h<n;h++)t[h]=0;BT(s,n-8,BigInt(this.length*8),o),this.process(s,0);let a=hh(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let s=e.slice(0,t);return this.destroy(),s}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:s,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%t&&e.buffer.set(s),e}clone(){return this._cloneInto()}},ks=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var yt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var fh=BigInt(4294967295),Xw=BigInt(32);function FT(r,e=!1){return e?{h:Number(r&fh),l:Number(r>>Xw&fh)}:{h:Number(r>>Xw&fh)|0,l:Number(r&fh)|0}}function Zw(r,e=!1){let t=r.length,s=new Uint32Array(t),n=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=FT(r[o],e);[s[o],n[o]]=[i,a]}return[s,n]}var xm=(r,e,t)=>r>>>t,vm=(r,e,t)=>r<<32-t|e>>>t,bo=(r,e,t)=>r>>>t|e<<32-t,wo=(r,e,t)=>r<<32-t|e>>>t,Oc=(r,e,t)=>r<<64-t|e>>>t-32,Lc=(r,e,t)=>r>>>t-32|e<<64-t;function ss(r,e,t,s){let n=(e>>>0)+(s>>>0);return{h:r+t+(n/2**32|0)|0,l:n|0}}var Qw=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Jw=(r,e,t,s)=>e+t+s+(r/2**32|0)|0,ex=(r,e,t,s)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0),tx=(r,e,t,s,n)=>e+t+s+n+(r/2**32|0)|0,rx=(r,e,t,s,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(s>>>0)+(n>>>0),sx=(r,e,t,s,n,o)=>e+t+s+n+o+(r/2**32|0)|0;var KT=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),nn=new Uint32Array(64),ph=class extends Mc{constructor(e=32){super(64,e,8,!1),this.A=ks[0]|0,this.B=ks[1]|0,this.C=ks[2]|0,this.D=ks[3]|0,this.E=ks[4]|0,this.F=ks[5]|0,this.G=ks[6]|0,this.H=ks[7]|0}get(){let{A:e,B:t,C:s,D:n,E:o,F:i,G:a,H:c}=this;return[e,t,s,n,o,i,a,c]}set(e,t,s,n,o,i,a,c){this.A=e|0,this.B=t|0,this.C=s|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let h=0;h<16;h++,t+=4)nn[h]=e.getUint32(t,!1);for(let h=16;h<64;h++){let d=nn[h-15],f=nn[h-2],p=Rr(d,7)^Rr(d,18)^d>>>3,m=Rr(f,17)^Rr(f,19)^f>>>10;nn[h]=m+nn[h-7]+p+nn[h-16]|0}let{A:s,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){let d=Rr(a,6)^Rr(a,11)^Rr(a,25),f=u+d+jw(a,c,l)+KT[h]+nn[h]|0,m=(Rr(s,2)^Rr(s,13)^Rr(s,22))+Yw(s,n,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=n,n=s,s=f+m|0}s=s+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(s,n,o,i,a,c,l,u)}roundClean(){Lr(nn)}destroy(){this.set(0,0,0,0,0,0,0,0),Lr(this.buffer)}};var nx=Zw(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),HT=nx[0],zT=nx[1],on=new Uint32Array(80),an=new Uint32Array(80),Em=class extends Mc{constructor(e=64){super(128,e,16,!1),this.Ah=yt[0]|0,this.Al=yt[1]|0,this.Bh=yt[2]|0,this.Bl=yt[3]|0,this.Ch=yt[4]|0,this.Cl=yt[5]|0,this.Dh=yt[6]|0,this.Dl=yt[7]|0,this.Eh=yt[8]|0,this.El=yt[9]|0,this.Fh=yt[10]|0,this.Fl=yt[11]|0,this.Gh=yt[12]|0,this.Gl=yt[13]|0,this.Hh=yt[14]|0,this.Hl=yt[15]|0}get(){let{Ah:e,Al:t,Bh:s,Bl:n,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:d,Gh:f,Gl:p,Hh:m,Hl:g}=this;return[e,t,s,n,o,i,a,c,l,u,h,d,f,p,m,g]}set(e,t,s,n,o,i,a,c,l,u,h,d,f,p,m,g){this.Ah=e|0,this.Al=t|0,this.Bh=s|0,this.Bl=n|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=h|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=g|0}process(e,t){for(let b=0;b<16;b++,t+=4)on[b]=e.getUint32(t),an[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let x=on[b-15]|0,E=an[b-15]|0,P=bo(x,E,1)^bo(x,E,8)^xm(x,E,7),T=wo(x,E,1)^wo(x,E,8)^vm(x,E,7),D=on[b-2]|0,v=an[b-2]|0,M=bo(D,v,19)^Oc(D,v,61)^xm(D,v,6),F=wo(D,v,19)^Lc(D,v,61)^vm(D,v,6),B=ex(T,F,an[b-7],an[b-16]),I=tx(B,P,M,on[b-7],on[b-16]);on[b]=I|0,an[b]=B|0}let{Ah:s,Al:n,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:d,Fh:f,Fl:p,Gh:m,Gl:g,Hh:y,Hl:w}=this;for(let b=0;b<80;b++){let x=bo(h,d,14)^bo(h,d,18)^Oc(h,d,41),E=wo(h,d,14)^wo(h,d,18)^Lc(h,d,41),P=h&f^~h&m,T=d&p^~d&g,D=rx(w,E,T,zT[b],an[b]),v=sx(D,y,x,P,HT[b],on[b]),M=D|0,F=bo(s,n,28)^Oc(s,n,34)^Oc(s,n,39),B=wo(s,n,28)^Lc(s,n,34)^Lc(s,n,39),I=s&o^s&a^o&a,S=n&i^n&c^i&c;y=m|0,w=g|0,m=f|0,g=p|0,f=h|0,p=d|0,{h,l:d}=ss(l|0,u|0,v|0,M|0),l=a|0,u=c|0,a=o|0,c=i|0,o=s|0,i=n|0;let _=Qw(M,B,S);s=Jw(_,v,F,I),n=_|0}({h:s,l:n}=ss(this.Ah|0,this.Al|0,s|0,n|0)),{h:o,l:i}=ss(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=ss(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ss(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:d}=ss(this.Eh|0,this.El|0,h|0,d|0),{h:f,l:p}=ss(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:g}=ss(this.Gh|0,this.Gl|0,m|0,g|0),{h:y,l:w}=ss(this.Hh|0,this.Hl|0,y|0,w|0),this.set(s,n,o,i,a,c,l,u,h,d,f,p,m,g,y,w)}roundClean(){Lr(on,an)}destroy(){Lr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var ox=wm(()=>new ph);var ix=wm(()=>new Em);var _m=BigInt(0),Im=BigInt(1);function mh(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function Rc(r,e,t=""){let s=go(r),n=r?.length,o=e!==void 0;if(!s||o&&n!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",c=s?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function ax(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?_m:BigInt("0x"+r)}function cx(r){return ax(yo(r))}function Nr(r){return At(r),ax(yo(Uint8Array.from(r).reverse()))}function Am(r,e){return dh(r.toString(16).padStart(e*2,"0"))}function gh(r,e){return Am(r,e).reverse()}function Ct(r,e,t){let s;if(typeof e=="string")try{s=dh(e)}catch(o){throw new Error(r+" must be hex string or Uint8Array, cause: "+o)}else if(go(e))s=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let n=s.length;if(typeof t=="number"&&n!==t)throw new Error(r+" of length "+t+" expected, got "+n);return s}function lx(r,e){if(r.length!==e.length)return!1;let t=0;for(let s=0;s<r.length;s++)t|=r[s]^e[s];return t===0}function Cm(r){return Uint8Array.from(r)}var Sm=r=>typeof r=="bigint"&&_m<=r;function qT(r,e,t){return Sm(r)&&Sm(e)&&Sm(t)&&e<=r&&r<t}function Bi(r,e,t,s){if(!qT(e,t,s))throw new Error("expected valid "+r+": "+t+" <= n < "+s+", got "+e)}function ux(r){let e;for(e=0;r>_m;r>>=Im,e+=1);return e}var Nc=r=>(Im<<BigInt(r))-Im;function xo(r,e,t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function s(n,o,i){let a=r[n];if(i&&a===void 0)return;let c=typeof a;if(c!==o||a===null)throw new Error(`param "${n}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([n,o])=>s(n,o,!1)),Object.entries(t).forEach(([n,o])=>s(n,o,!0))}var Tm=()=>{throw new Error("not implemented")};function Pm(r){let e=new WeakMap;return(t,...s)=>{let n=e.get(t);if(n!==void 0)return n;let o=r(t,...s);return e.set(t,o),o}}var Nt=BigInt(0),Tt=BigInt(1),vo=BigInt(2),fx=BigInt(3),px=BigInt(4),mx=BigInt(5),$T=BigInt(7),gx=BigInt(8),GT=BigInt(9),yx=BigInt(16);function Me(r,e){let t=r%e;return t>=Nt?t:e+t}function gr(r,e,t){let s=r;for(;e-- >Nt;)s*=s,s%=t;return s}function hx(r,e){if(r===Nt)throw new Error("invert: expected non-zero number");if(e<=Nt)throw new Error("invert: expected positive modulus, got "+e);let t=Me(r,e),s=e,n=Nt,o=Tt,i=Tt,a=Nt;for(;t!==Nt;){let l=s/t,u=s%t,h=n-i*l,d=o-a*l;s=t,t=u,n=i,o=a,i=h,a=d}if(s!==Tt)throw new Error("invert: does not exist");return Me(n,e)}function km(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function bx(r,e){let t=(r.ORDER+Tt)/px,s=r.pow(e,t);return km(r,s,e),s}function VT(r,e){let t=(r.ORDER-mx)/gx,s=r.mul(e,vo),n=r.pow(s,t),o=r.mul(e,n),i=r.mul(r.mul(o,vo),n),a=r.mul(o,r.sub(i,r.ONE));return km(r,a,e),a}function WT(r){let e=Ms(r),t=wx(r),s=t(e,e.neg(e.ONE)),n=t(e,s),o=t(e,e.neg(s)),i=(r+$T)/yx;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,s),h=a.mul(l,n),d=a.mul(l,o),f=a.eql(a.sqr(u),c),p=a.eql(a.sqr(h),c);l=a.cmov(l,u,f),u=a.cmov(d,h,p);let m=a.eql(a.sqr(u),c),g=a.cmov(l,u,m);return km(a,g,c),g}}function wx(r){if(r<fx)throw new Error("sqrt is not defined for small field");let e=r-Tt,t=0;for(;e%vo===Nt;)e/=vo,t++;let s=vo,n=Ms(r);for(;dx(n,s)===1;)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return bx;let o=n.pow(s,e),i=(e+Tt)/vo;return function(c,l){if(c.is0(l))return l;if(dx(c,l)!==1)throw new Error("Cannot find square root");let u=t,h=c.mul(c.ONE,o),d=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,m=c.sqr(d);for(;!c.eql(m,c.ONE);)if(p++,m=c.sqr(m),p===u)throw new Error("Cannot find square root");let g=Tt<<BigInt(u-p-1),y=c.pow(h,g);u=p,h=c.sqr(y),d=c.mul(d,h),f=c.mul(f,y)}return f}}function jT(r){return r%px===fx?bx:r%gx===mx?VT:r%yx===GT?WT(r):wx(r)}var Ds=(r,e)=>(Me(r,e)&Tt)===Tt,YT=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xx(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=YT.reduce((s,n)=>(s[n]="function",s),e);return xo(r,t),r}function XT(r,e,t){if(t<Nt)throw new Error("invalid exponent, negatives unsupported");if(t===Nt)return r.ONE;if(t===Tt)return e;let s=r.ONE,n=e;for(;t>Nt;)t&Tt&&(s=r.mul(s,n)),n=r.sqr(n),t>>=Tt;return s}function yh(r,e,t=!1){let s=new Array(e.length).fill(t?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(s[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(s[c]=r.mul(i,s[c]),r.mul(i,a)),o),s}function dx(r,e){let t=(r.ORDER-Tt)/vo,s=r.pow(e,t),n=r.eql(s,r.ONE),o=r.eql(s,r.ZERO),i=r.eql(s,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function vx(r,e){e!==void 0&&mo(e);let t=e!==void 0?e:r.toString(2).length,s=Math.ceil(t/8);return{nBitLength:t,nByteLength:s}}function Ms(r,e,t=!1,s={}){if(r<=Nt)throw new Error("invalid field: expected ORDER > 0, got "+r);let n,o,i=!1,a;if(typeof e=="object"&&e!=null){if(s.sqrt||t)throw new Error("cannot specify opts in two arguments");let d=e;d.BITS&&(n=d.BITS),d.sqrt&&(o=d.sqrt),typeof d.isLE=="boolean"&&(t=d.isLE),typeof d.modFromBytes=="boolean"&&(i=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(n=e),s.sqrt&&(o=s.sqrt);let{nBitLength:c,nByteLength:l}=vx(r,n);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,h=Object.freeze({ORDER:r,isLE:t,BITS:c,BYTES:l,MASK:Nc(c),ZERO:Nt,ONE:Tt,allowedLengths:a,create:d=>Me(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return Nt<=d&&d<r},is0:d=>d===Nt,isValidNot0:d=>!h.is0(d)&&h.isValid(d),isOdd:d=>(d&Tt)===Tt,neg:d=>Me(-d,r),eql:(d,f)=>d===f,sqr:d=>Me(d*d,r),add:(d,f)=>Me(d+f,r),sub:(d,f)=>Me(d-f,r),mul:(d,f)=>Me(d*f,r),pow:(d,f)=>XT(h,d,f),div:(d,f)=>Me(d*hx(f,r),r),sqrN:d=>d*d,addN:(d,f)=>d+f,subN:(d,f)=>d-f,mulN:(d,f)=>d*f,inv:d=>hx(d,r),sqrt:o||(d=>(u||(u=jT(r)),u(h,d))),toBytes:d=>t?gh(d,l):Am(d,l),fromBytes:(d,f=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let m=new Uint8Array(l);m.set(d,t?0:m.length-d.length),d=m}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let p=t?Nr(d):cx(d);if(i&&(p=Me(p,r)),!f&&!h.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>yh(h,d),cmov:(d,f,p)=>p?f:d});return Object.freeze(h)}var bh=BigInt(0),Lm=BigInt(1);function Ex(r,e){let t=e.negate();return r?t:e}function Bc(r,e){let t=yh(r.Fp,e.map(s=>s.Z));return e.map((s,n)=>r.fromAffine(s.toAffine(t[n])))}function Ax(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Dm(r,e){Ax(r,e);let t=Math.ceil(e/r)+1,s=2**(r-1),n=2**r,o=Nc(r),i=BigInt(r);return{windows:t,windowSize:s,mask:o,maxNumber:n,shiftBy:i}}function Sx(r,e,t){let{windowSize:s,mask:n,maxNumber:o,shiftBy:i}=t,a=Number(r&n),c=r>>i;a>s&&(a-=o,c+=Lm);let l=e*s,u=l+Math.abs(a)-1,h=a===0,d=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:d,isNegF:f,offsetF:l}}function ZT(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,s)=>{if(!(t instanceof e))throw new Error("invalid point at index "+s)})}function QT(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,s)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+s)})}var Mm=new WeakMap,Cx=new WeakMap;function Om(r){return Cx.get(r)||1}function Ix(r){if(r!==bh)throw new Error("invalid wNAF")}var wh=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,s=this.ZERO){let n=e;for(;t>bh;)t&Lm&&(s=s.add(n)),n=n.double(),t>>=Lm;return s}precomputeWindow(e,t){let{windows:s,windowSize:n}=Dm(t,this.bits),o=[],i=e,a=i;for(let c=0;c<s;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,s){if(!this.Fn.isValid(s))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE,i=Dm(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:d,offsetF:f}=Sx(s,a,i);s=c,u?o=o.add(Ex(d,t[f])):n=n.add(Ex(h,t[l]))}return Ix(s),{p:n,f:o}}wNAFUnsafe(e,t,s,n=this.ZERO){let o=Dm(e,this.bits);for(let i=0;i<o.windows&&s!==bh;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Sx(s,i,o);if(s=a,!l){let h=t[c];n=n.add(u?h.negate():h)}}return Ix(s),n}getPrecomputes(e,t,s){let n=Mm.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof s=="function"&&(n=s(n)),Mm.set(t,n))),n}cached(e,t,s){let n=Om(e);return this.wNAF(n,this.getPrecomputes(n,e,s),t)}unsafe(e,t,s,n){let o=Om(e);return o===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,s),t,n)}createCache(e,t){Ax(t,this.bits),Cx.set(e,t),Mm.delete(e)}hasCache(e){return Om(e)!==1}};function xh(r,e,t,s){ZT(t,r),QT(s,e);let n=t.length,o=s.length;if(n!==o)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=ux(BigInt(n)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Nc(c),u=new Array(Number(l)+1).fill(i),h=Math.floor((e.BITS-1)/c)*c,d=i;for(let f=h;f>=0;f-=c){u.fill(i);for(let m=0;m<o;m++){let g=s[m],y=Number(g>>BigInt(f)&l);u[y]=u[y].add(t[m])}let p=i;for(let m=u.length-1,g=i;m>0;m--)g=g.add(u[m]),p=p.add(g);if(d=d.add(p),f!==0)for(let m=0;m<c;m++)d=d.double()}return d}function _x(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return xx(e),e}else return Ms(r,{isLE:t})}function Tx(r,e,t={},s){if(s===void 0&&(s=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>bh))throw new Error(`CURVE.${c} must be positive bigint`)}let n=_x(e.p,t.Fp,s),o=_x(e.n,t.Fn,s),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:o}}var cn=BigInt(0),ht=BigInt(1),Rm=BigInt(2),JT=BigInt(8);function eP(r,e,t,s){let n=r.sqr(t),o=r.sqr(s),i=r.add(r.mul(e.a,n),o),a=r.add(r.ONE,r.mul(e.d,r.mul(n,o)));return r.eql(i,a)}function tP(r,e={}){let t=Tx("edwards",r,e,e.FpFnLE),{Fp:s,Fn:n}=t,o=t.CURVE,{h:i}=o;xo(e,{},{uvRatio:"function"});let a=Rm<<BigInt(n.BYTES*8)-ht,c=g=>s.create(g),l=e.uvRatio||((g,y)=>{try{return{isValid:!0,value:s.sqrt(s.div(g,y))}}catch{return{isValid:!1,value:cn}}});if(!eP(s,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(g,y,w=!1){let b=w?ht:cn;return Bi("coordinate "+g,y,b,a),y}function h(g){if(!(g instanceof p))throw new Error("ExtendedPoint expected")}let d=Pm((g,y)=>{let{X:w,Y:b,Z:x}=g,E=g.is0();y==null&&(y=E?JT:s.inv(x));let P=c(w*y),T=c(b*y),D=s.mul(x,y);if(E)return{x:cn,y:ht};if(D!==ht)throw new Error("invZ was invalid");return{x:P,y:T}}),f=Pm(g=>{let{a:y,d:w}=o;if(g.is0())throw new Error("bad point: ZERO");let{X:b,Y:x,Z:E,T:P}=g,T=c(b*b),D=c(x*x),v=c(E*E),M=c(v*v),F=c(T*y),B=c(v*c(F+D)),I=c(M+c(w*c(T*D)));if(B!==I)throw new Error("bad point: equation left != right (1)");let S=c(b*x),_=c(E*P);if(S!==_)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,w,b,x){this.X=u("x",y),this.Y=u("y",w),this.Z=u("z",b,!0),this.T=u("t",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:w,y:b}=y||{};return u("x",w),u("y",b),new p(w,b,ht,c(w*b))}static fromBytes(y,w=!1){let b=s.BYTES,{a:x,d:E}=o;y=Cm(Rc(y,b,"point")),mh(w,"zip215");let P=Cm(y),T=y[b-1];P[b-1]=T&-129;let D=Nr(P),v=w?a:s.ORDER;Bi("point.y",D,cn,v);let M=c(D*D),F=c(M-ht),B=c(E*M-x),{isValid:I,value:S}=l(F,B);if(!I)throw new Error("bad point: invalid y coordinate");let _=(S&ht)===ht,k=(T&128)!==0;if(!w&&S===cn&&k)throw new Error("bad point: x=0 and x_0=1");return k!==_&&(S=c(-S)),p.fromAffine({x:S,y:D})}static fromHex(y,w=!1){return p.fromBytes(Ct("point",y),w)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,w=!0){return m.createCache(this,y),w||this.multiply(Rm),this}assertValidity(){f(this)}equals(y){h(y);let{X:w,Y:b,Z:x}=this,{X:E,Y:P,Z:T}=y,D=c(w*T),v=c(E*x),M=c(b*T),F=c(P*x);return D===v&&M===F}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=o,{X:w,Y:b,Z:x}=this,E=c(w*w),P=c(b*b),T=c(Rm*c(x*x)),D=c(y*E),v=w+b,M=c(c(v*v)-E-P),F=D+P,B=F-T,I=D-P,S=c(M*B),_=c(F*I),k=c(M*I),O=c(B*F);return new p(S,_,O,k)}add(y){h(y);let{a:w,d:b}=o,{X:x,Y:E,Z:P,T}=this,{X:D,Y:v,Z:M,T:F}=y,B=c(x*D),I=c(E*v),S=c(T*b*F),_=c(P*M),k=c((x+E)*(D+v)-B-I),O=_-S,N=_+S,C=c(I-w*B),R=c(k*O),U=c(N*C),z=c(k*C),ee=c(O*N);return new p(R,U,ee,z)}subtract(y){return this.add(y.negate())}multiply(y){if(!n.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:w,f:b}=m.cached(this,y,x=>Bc(p,x));return Bc(p,[w,b])[0]}multiplyUnsafe(y,w=p.ZERO){if(!n.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===cn?p.ZERO:this.is0()||y===ht?this:m.unsafe(this,y,b=>Bc(p,b),w)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,o.n).is0()}toAffine(y){return d(this,y)}clearCofactor(){return i===ht?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:w}=this.toAffine(),b=s.toBytes(w);return b[b.length-1]|=y&ht?128:0,b}toHex(){return yo(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(y){return Bc(p,y)}static msm(y,w){return xh(p,n,y,w)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}p.BASE=new p(o.Gx,o.Gy,ht,c(o.Gx*o.Gy)),p.ZERO=new p(cn,ht,ht,cn),p.Fp=s,p.Fn=n;let m=new wh(p,n.BITS);return p.BASE.precompute(8),p}var vh=class{constructor(e){this.ep=e}static fromBytes(e){Tm()}static fromHex(e){Tm()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return yo(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function rP(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');xo(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:s}=t,{BASE:n,Fp:o,Fn:i}=r,a=t.randomBytes||Dc,c=t.adjustScalarBytes||(v=>v),l=t.domain||((v,M,F)=>{if(mh(F,"phflag"),M.length||F)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(Nr(v))}function h(v){let M=b.secretKey;v=Ct("private key",v,M);let F=Ct("hashed private key",e(v),2*M),B=c(F.slice(0,M)),I=F.slice(M,2*M),S=u(B);return{head:B,prefix:I,scalar:S}}function d(v){let{head:M,prefix:F,scalar:B}=h(v),I=n.multiply(B),S=I.toBytes();return{head:M,prefix:F,scalar:B,point:I,pointBytes:S}}function f(v){return d(v).pointBytes}function p(v=Uint8Array.of(),...M){let F=Ni(...M);return u(e(l(F,Ct("context",v),!!s)))}function m(v,M,F={}){v=Ct("message",v),s&&(v=s(v));let{prefix:B,scalar:I,pointBytes:S}=d(M),_=p(F.context,B,v),k=n.multiply(_).toBytes(),O=p(F.context,k,S,v),N=i.create(_+O*I);if(!i.isValid(N))throw new Error("sign failed: invalid s");let C=Ni(k,i.toBytes(N));return Rc(C,b.signature,"result")}let g={zip215:!0};function y(v,M,F,B=g){let{context:I,zip215:S}=B,_=b.signature;v=Ct("signature",v,_),M=Ct("message",M),F=Ct("publicKey",F,b.publicKey),S!==void 0&&mh(S,"zip215"),s&&(M=s(M));let k=_/2,O=v.subarray(0,k),N=Nr(v.subarray(k,_)),C,R,U;try{C=r.fromBytes(F,S),R=r.fromBytes(O,S),U=n.multiplyUnsafe(N)}catch{return!1}if(!S&&C.isSmallOrder())return!1;let z=p(I,R.toBytes(),C.toBytes(),M);return R.add(C.multiplyUnsafe(z)).subtract(U).clearCofactor().is0()}let w=o.BYTES,b={secretKey:w,publicKey:w,signature:2*w,seed:w};function x(v=a(b.seed)){return Rc(v,b.seed,"seed")}function E(v){let M=D.randomSecretKey(v);return{secretKey:M,publicKey:f(M)}}function P(v){return go(v)&&v.length===i.BYTES}function T(v,M){try{return!!r.fromBytes(v,M)}catch{return!1}}let D={getExtendedPublicKey:d,randomSecretKey:x,isValidSecretKey:P,isValidPublicKey:T,toMontgomery(v){let{y:M}=r.fromBytes(v),F=b.publicKey,B=F===32;if(!B&&F!==57)throw new Error("only defined for 25519 and 448");let I=B?o.div(ht+M,ht-M):o.div(M-ht,M+ht);return o.toBytes(I)},toMontgomerySecret(v){let M=b.secretKey;Rc(v,M);let F=e(v.subarray(0,M));return c(F).subarray(0,M)},randomPrivateKey:x,precompute(v=8,M=r.BASE){return M.precompute(v,!1)}};return Object.freeze({keygen:E,getPublicKey:f,sign:m,verify:y,utils:D,Point:r,lengths:b})}function sP(r){let e={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,s=Ms(e.n,r.nBitLength,!0),n={Fp:t,Fn:s,uvRatio:r.uvRatio},o={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:e,curveOpts:n,hash:r.hash,eddsaOpts:o}}function nP(r,e){let t=e.Point;return Object.assign({},e,{ExtendedPoint:t,CURVE:r,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function Px(r){let{CURVE:e,curveOpts:t,hash:s,eddsaOpts:n}=sP(r),o=tP(e,t),i=rP(o,s,n);return nP(r,i)}var Fc=BigInt(0),Fi=BigInt(1),Eh=BigInt(2);function oP(r){return xo(r,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r})}function kx(r){let e=oP(r),{P:t,type:s,adjustScalarBytes:n,powPminus2:o,randomBytes:i}=e,a=s==="x25519";if(!a&&s!=="x448")throw new Error("invalid type");let c=i||Dc,l=a?255:448,u=a?32:56,h=BigInt(a?9:5),d=BigInt(a?121665:39081),f=a?Eh**BigInt(254):Eh**BigInt(447),p=a?BigInt(8)*Eh**BigInt(251)-Fi:BigInt(4)*Eh**BigInt(445)-Fi,m=f+p+Fi,g=I=>Me(I,t),y=w(h);function w(I){return gh(g(I),u)}function b(I){let S=Ct("u coordinate",I,u);return a&&(S[31]&=127),g(Nr(S))}function x(I){return Nr(n(Ct("scalar",I,u)))}function E(I,S){let _=D(b(S),x(I));if(_===Fc)throw new Error("invalid private or public key received");return w(_)}function P(I){return E(I,y)}function T(I,S,_){let k=g(I*(S-_));return S=g(S-k),_=g(_+k),{x_2:S,x_3:_}}function D(I,S){Bi("u",I,Fc,t),Bi("scalar",S,f,m);let _=S,k=I,O=Fi,N=Fc,C=I,R=Fi,U=Fc;for(let ee=BigInt(l-1);ee>=Fc;ee--){let te=_>>ee&Fi;U^=te,{x_2:O,x_3:C}=T(U,O,C),{x_2:N,x_3:R}=T(U,N,R),U=te;let Z=O+N,se=g(Z*Z),xe=O-N,$e=g(xe*xe),oe=se-$e,rt=C+R,To=C-R,ea=g(To*Z),ta=g(rt*xe),pg=ea+ta,mg=ea-ta;C=g(pg*pg),R=g(k*g(mg*mg)),O=g(se*$e),N=g(oe*(se+g(d*oe)))}({x_2:O,x_3:C}=T(U,O,C)),{x_2:N,x_3:R}=T(U,N,R);let z=o(N);return g(O*z)}let v={secretKey:u,publicKey:u,seed:u},M=(I=c(u))=>(At(I,v.seed),I);function F(I){let S=M(I);return{secretKey:S,publicKey:P(S)}}return{keygen:F,getSharedSecret:(I,S)=>E(I,S),getPublicKey:I=>P(I),scalarMult:E,scalarMultBase:P,utils:{randomSecretKey:M,randomPrivateKey:M},GuBytes:y.slice(),lengths:v}}var iP=BigInt(0),Ls=BigInt(1),Dx=BigInt(2),aP=BigInt(3),cP=BigInt(5),lP=BigInt(8),Ui=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Uc={p:Ui,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:lP,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Lx(r){let e=BigInt(10),t=BigInt(20),s=BigInt(40),n=BigInt(80),o=Ui,a=r*r%o*r%o,c=gr(a,Dx,o)*a%o,l=gr(c,Ls,o)*r%o,u=gr(l,cP,o)*l%o,h=gr(u,e,o)*u%o,d=gr(h,t,o)*h%o,f=gr(d,s,o)*d%o,p=gr(f,n,o)*f%o,m=gr(p,n,o)*f%o,g=gr(m,e,o)*u%o;return{pow_p_5_8:gr(g,Dx,o)*r%o,b2:a}}function Rx(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Nm=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Um(r,e){let t=Ui,s=Me(e*e*e,t),n=Me(s*s*e,t),o=Lx(r*n).pow_p_5_8,i=Me(r*s*o,t),a=Me(e*i*i,t),c=i,l=Me(i*Nm,t),u=a===r,h=a===Me(-r,t),d=a===Me(-r*Nm,t);return u&&(i=c),(h||d)&&(i=l),Ds(i,t)&&(i=Me(-i,t)),{isValid:u||h,value:i}}var Os=Ms(Uc.p,{isLE:!0}),uP=Ms(Uc.n,{isLE:!0}),hP={...Uc,Fp:Os,hash:ix,adjustScalarBytes:Rx,uvRatio:Um},Eo=Px(hP);var Kc=(()=>{let r=Os.ORDER;return kx({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:s}=Lx(e);return Me(gr(t,aP,r)*s,r)},adjustScalarBytes:Rx})})();var Bm=Nm,dP=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),fP=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),pP=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),mP=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Mx=r=>Um(Ls,r),gP=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Fm=r=>Eo.Point.Fp.create(Nr(r)&gP);function Ox(r){let{d:e}=Uc,t=Ui,s=y=>Os.create(y),n=s(Bm*r*r),o=s((n+Ls)*pP),i=BigInt(-1),a=s((i-e*n)*s(n+e)),{isValid:c,value:l}=Um(o,a),u=s(l*r);Ds(u,t)||(u=s(-u)),c||(l=u),c||(i=n);let h=s(i*(n-Ls)*mP-a),d=l*l,f=s((l+l)*a),p=s(h*dP),m=s(Ls-d),g=s(Ls+d);return new Eo.Point(s(f*g),s(m*p),s(p*g),s(f*m))}function yP(r){At(r,64);let e=Fm(r.subarray(0,32)),t=Ox(e),s=Fm(r.subarray(32,64)),n=Ox(s);return new Rs(t.add(n))}var Rs=class r extends vh{constructor(e){super(e)}static fromAffine(e){return new r(Eo.Point.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static hashToCurve(e){return yP(Ct("ristrettoHash",e,64))}static fromBytes(e){At(e,32);let{a:t,d:s}=Uc,n=Ui,o=x=>Os.create(x),i=Fm(e);if(!lx(Os.toBytes(i),e)||Ds(i,n))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),c=o(Ls+t*a),l=o(Ls-t*a),u=o(c*c),h=o(l*l),d=o(t*s*u-h),{isValid:f,value:p}=Mx(o(d*h)),m=o(p*l),g=o(p*m*d),y=o((i+i)*m);Ds(y,n)&&(y=o(-y));let w=o(c*g),b=o(y*w);if(!f||Ds(b,n)||w===iP)throw new Error("invalid ristretto255 encoding 2");return new r(new Eo.Point(y,w,Ls,b))}static fromHex(e){return r.fromBytes(Ct("ristrettoHex",e,32))}static msm(e,t){return xh(r,Eo.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:s,T:n}=this.ep,o=Ui,i=g=>Os.create(g),a=i(i(s+t)*i(s-t)),c=i(e*t),l=i(c*c),{value:u}=Mx(i(a*l)),h=i(u*a),d=i(u*c),f=i(h*d*n),p;if(Ds(n*f,o)){let g=i(t*Bm),y=i(e*Bm);e=g,t=y,p=i(h*fP)}else p=d;Ds(e*f,o)&&(t=i(-t));let m=i((s-t)*p);return Ds(m,o)&&(m=i(-m)),Os.toBytes(m)}equals(e){this.assertSame(e);let{X:t,Y:s}=this.ep,{X:n,Y:o}=e.ep,i=l=>Os.create(l),a=i(t*o)===i(s*n),c=i(s*o)===i(t*n);return a||c}is0(){return this.equals(r.ZERO)}};Rs.BASE=new Rs(Eo.Point.BASE);Rs.ZERO=new Rs(Eo.Point.ZERO);Rs.Fp=Os;Rs.Fn=uP;var Sh=class extends Li{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,kc(e);let s=sn(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(s.length>n?e.create().update(s).digest():s);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Lr(o)}update(e){return Ri(this),this.iHash.update(e),this}digestInto(e){Ri(this),At(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:s,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=s._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ih=(r,e,t)=>new Sh(r,e).update(t).digest();Ih.create=(r,e)=>new Sh(r,e);function Bx(r,e,t){return kc(r),t===void 0&&(t=new Uint8Array(r.outputLen)),Ih(r,sn(t),sn(e))}var Km=Uint8Array.from([0]),Nx=Uint8Array.of();function Fx(r,e,t,s=32){kc(r),mo(s);let n=r.outputLen;if(s>255*n)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(s/n);t===void 0&&(t=Nx);let i=new Uint8Array(o*n),a=Ih.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)Km[0]=u+1,c.update(u===0?Nx:l).update(t).update(Km).digestInto(l),i.set(l,n*u),a._cloneInto(c);return a.destroy(),c.destroy(),Lr(l,Km),i.slice(0,s)}var _h=ox;var Hm={hashSHA256(r){return _h(r.subarray())},getHKDF(r,e){let t=Bx(_h,e,r),n=Fx(_h,t,void 0,96),o=n.subarray(0,32),i=n.subarray(32,64),a=n.subarray(64,96);return[o,i,a]},generateX25519KeyPair(){let r=Kc.utils.randomPrivateKey();return{publicKey:Kc.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Kc.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return Kc.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,s){return ym(s,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,s,n){return ym(s,e,t).decrypt(r.subarray(),n)}};var bP=(0,Th.newInstance)(),Ux=new Th.ChaCha20Poly1305(bP),Kx="chacha20-poly1305",Ki=Buffer.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Hc=Buffer.from([48,42,48,5,6,3,43,101,110,3,33,0]);var zm={hashSHA256(r){let e=ns.default.createHash("sha256");if(r instanceof Uint8Array)return e.update(r).digest();for(let t of r)e.update(t);return e.digest()},chaCha20Poly1305Encrypt(r,e,t,s){let n=ns.default.createCipheriv(Kx,s,e,{authTagLength:16});if(n.setAAD(t,{plaintextLength:r.byteLength}),r instanceof Uint8Array){let a=n.update(r),c=n.final(),l=n.getAuthTag();return Buffer.concat([a,c,l],a.byteLength+c.byteLength+l.byteLength)}let o=new W;for(let a of r)o.append(n.update(a));let i=n.final();return i.byteLength>0&&o.append(i),o.append(n.getAuthTag()),o},chaCha20Poly1305Decrypt(r,e,t,s,n){let o=r.subarray(r.length-16),i=ns.default.createDecipheriv(Kx,s,e,{authTagLength:16}),a;if(r instanceof Uint8Array?a=r.subarray(0,r.length-16):a=r.sublist(0,r.length-16),i.setAAD(t,{plaintextLength:a.byteLength}),i.setAuthTag(o),a instanceof Uint8Array){let u=i.update(a),h=i.final();return h.byteLength>0?Buffer.concat([u,h],u.byteLength+h.byteLength):u}let c=new W;for(let u of a)c.append(i.update(u));let l=i.final();return l.byteLength>0&&c.append(l),c}},Ah={hashSHA256(r){return _w(r.subarray())},chaCha20Poly1305Encrypt(r,e,t,s){return Ux.seal(s,e,r.subarray(),t)},chaCha20Poly1305Decrypt(r,e,t,s,n){let o=Ux.open(s,e,r.subarray(),t,n);if(!o)throw new Error("Invalid chacha20poly1305 decryption");return o}},Ch={...Hm,hashSHA256(r){return zm.hashSHA256(r)},chaCha20Poly1305Encrypt(r,e,t,s){return r.byteLength<1200?Ah.chaCha20Poly1305Encrypt(r,e,t,s):zm.chaCha20Poly1305Encrypt(r,e,t,s)},chaCha20Poly1305Decrypt(r,e,t,s,n){return r.byteLength<1200?Ah.chaCha20Poly1305Decrypt(r,e,t,s,n):zm.chaCha20Poly1305Decrypt(r,e,t,s,n)},generateX25519KeyPair(){let{publicKey:r,privateKey:e}=ns.default.generateKeyPairSync("x25519",{publicKeyEncoding:{type:"spki",format:"der"},privateKeyEncoding:{type:"pkcs8",format:"der"}});return{publicKey:r.subarray(Hc.length),privateKey:e.subarray(Ki.length)}},generateX25519KeyPairFromSeed(r){let e=ns.default.createPrivateKey({key:Buffer.concat([Ki,r],Ki.byteLength+r.byteLength),type:"pkcs8",format:"der"});return{publicKey:ns.default.createPublicKey(e).export({type:"spki",format:"der"}).subarray(Hc.length),privateKey:r}},generateX25519SharedKey(r,e){return e instanceof Uint8Array?e=Buffer.concat([Hc,e],Hc.byteLength+e.byteLength):e=new W(Hc,e).subarray(),r instanceof Uint8Array?r=Buffer.concat([Ki,r],Ki.byteLength+r.byteLength):r=new W(Ki,r).subarray(),ns.default.diffieHellman({publicKey:ns.default.createPublicKey({key:Buffer.from(e.buffer,e.byteOffset,e.byteLength),type:"spki",format:"der"}),privateKey:ns.default.createPrivateKey({key:Buffer.from(r.buffer,r.byteOffset,r.byteLength),type:"pkcs8",format:"der"})})}};kw&&(Ch.chaCha20Poly1305Encrypt=Ah.chaCha20Poly1305Encrypt,Ch.chaCha20Poly1305Decrypt=Ah.chaCha20Poly1305Decrypt);function Hx(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}nt();var Hi=r=>{let e=je(2);return e[0]=r>>8,e[1]=r,e};Hi.bytes=2;var zc=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};zc.bytes=2;function zx(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}Se();function qm(r,e){!e.enabled||!Di||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${K(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${K(r.privateKey,"hex")}`)):e("Missing local static keys."))}function $m(r,e){!e.enabled||!Di||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${K(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${K(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function qx(r,e){!e.enabled||!Di||e(r?`REMOTE_STATIC_PUBLIC_KEY ${K(r.subarray(),"hex")}`:"Missing remote static public key.")}function Gm(r,e){!e.enabled||!Di||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${K(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Vm(r,e,t){!t.enabled||!Di||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&K(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&K(e.k,"hex")}`))}ot();Kt();nt();ra();Kr();ge();Se();nt();var zi=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};nt();var wP=0,xP=4294967295,vP="Cipherstate has reached maximum n, a new handshake must be performed",Ph=class{n;bytes;view;constructor(e=wP){this.n=e,this.bytes=ie(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>xP)throw new Error(vP)}};var So=ie(0),qi=class{k;n;crypto;constructor(e,t=void 0,s=0){this.crypto=e,this.k=t,this.n=new Ph(s)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let s=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),s}decryptWithAd(e,t,s){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,s);return this.n.increment(),n}},Wm=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let s=L(t,"utf-8");this.h=EP(e,s),this.ck=this.h,this.cs=new qi(e)}mixKey(e){let[t,s]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new qi(this.crypto,s)}mixHash(e){this.h=this.crypto.hash(new W(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,So);return[new qi(this.crypto,e),new qi(this.crypto,t)]}},jm=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:s,prologue:n,initiator:o,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new Wm(t,s),this.ss.mixHash(n),this.initiator=o,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.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(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let s=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+s)throw new Error("message is not long enough");let n=e.sublist(t,t+s);return this.rs=this.ss.decryptAndHash(n),s}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},qc=class extends jm{writeMessageA(e){return new W(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let s=this.writeS();return this.writeES(),new W(t,s,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new W(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new zi(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new zi(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new zi(`handshake stage 2 validation fail: ${t.message}`)}}};function EP(r,e){if(e.length<=32){let t=ie(32);return t.set(e),t}else return r.hash(e)}ft();X();Kr();ge();zs();nt();var kh;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{if(n.lengthDelimited!==!1&&s.fork(),t.webtransportCerthashes!=null)for(let o of t.webtransportCerthashes)s.uint32(10),s.bytes(o);if(t.streamMuxers!=null)for(let o of t.streamMuxers)s.uint32(18),s.string(o);n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={webtransportCerthashes:[],streamMuxers:[]},i=s==null?t.len:t.pos+s;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(n.limits?.webtransportCerthashes!=null&&o.webtransportCerthashes.length===n.limits.webtransportCerthashes)throw new Ie('Decode error - map field "webtransportCerthashes" had too many elements');o.webtransportCerthashes.push(t.bytes());break}case 2:{if(n.limits?.streamMuxers!=null&&o.streamMuxers.length===n.limits.streamMuxers)throw new Ie('Decode error - map field "streamMuxers" had too many elements');o.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})(kh||(kh={}));var $c;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{n.lengthDelimited!==!1&&s.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(s.uint32(10),s.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(s.uint32(18),s.bytes(t.identitySig)),t.extensions!=null&&(s.uint32(34),kh.codec().encode(t.extensions,s)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={identityKey:ie(0),identitySig:ie(0)},i=s==null?t.len:t.pos+s;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{o.identityKey=t.bytes();break}case 2:{o.identitySig=t.bytes();break}case 4:{o.extensions=kh.codec().decode(t,t.uint32(),{limits:n.limits?.extensions});break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})($c||($c={}));async function Ym(r,e,t){let s=await r.sign($x(e));return $c.encode({identityKey:Ve(r.publicKey),identitySig:s,extensions:t})}async function Xm(r,e,t){try{let s=$c.decode(r),n=Je(s.identityKey);if(t?.equals(n)===!1)throw new Error(`Payload identity key ${n} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let o=$x(e);if(!await n.verify(o,s.identitySig))throw new Error("Invalid payload signature");return s}catch(s){throw new Ll(s.message)}}function $x(r){let e=L("noise-libp2p-static-key:");return r instanceof Uint8Array?Ye([e,r],e.length+r.length):(r.prepend(e),r)}async function Gx(r,e){let{log:t,connection:s,crypto:n,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Ym(o,a.publicKey,l),h=new qc({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});qm(h.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await s.write(h.writeMessageA(So),e),t.trace("Stage 0 - Initiator finished sending first message."),$m(h.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=h.readMessageB(await s.read(e));t.trace("Stage 1 - Initiator received the message."),Gm(h.re,t),qx(h.rs,t),t.trace("Initiator going to check remote's signature...");let f=await Xm(d,h.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await s.write(h.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[p,m]=h.ss.split();return Vm(p,m,t),{payload:f,encrypt:g=>p.encryptWithAd(So,g),decrypt:(g,y)=>m.decryptWithAd(So,g,y)}}async function Vx(r,e){let{log:t,connection:s,crypto:n,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Ym(o,a.publicKey,l),h=new qc({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});qm(h.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await s.read(e)),t.trace("Stage 0 - Responder received first message."),Gm(h.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await s.write(h.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),$m(h.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let d=h.readMessageC(await s.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let f=await Xm(d,h.rs,c),[p,m]=h.ss.split();return Vm(p,m,t),{payload:f,encrypt:g=>m.encryptWithAd(So,g),decrypt:(g,y)=>p.decryptWithAd(So,g,y)}}ot();var jx=16;function Yx(r,e){return async function*(t){for await(let s of t)for(let n=0;n<s.length;n+=65519){let o=n+65519;o>s.length&&(o=s.length);let i;s instanceof Uint8Array?i=r.encrypt(s.subarray(n,o)):i=r.encrypt(s.sublist(n,o)),e?.encryptedPackets.increment(),yield new W(Hi(i.byteLength),i)}}}function Xx(r,e){return async function*(t){for await(let s of t)for(let n=0;n<s.length;n+=65535){let o=n+65535;if(o>s.length&&(o=s.length),o-jx<n)throw new Error("Invalid chunk");let i=s.sublist(n,o),a=s.subarray(n,o-jx);try{let c=r.decrypt(i,a);e?.decryptedPackets.increment(),yield c}catch(c){throw e?.decryptErrors.increment(),c}}}}var Dh=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){let{staticNoiseKey:s,extensions:n,crypto:o,prologueBytes:i}=t,{metrics:a}=e;this.components=e;let c=o??Ch;this.crypto=Hx(c),this.extensions={webtransportCerthashes:[],...n},this.metrics=a?zx(a):void 0,s?this.staticKey=c.generateX25519KeyPairFromSeed(s):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ie(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[et]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let s=Jr(e,{lengthEncoder:Hi,lengthDecoder:zc,maxDataLength:65535}),n=await this.performHandshakeInitiator(s,this.components.privateKey,t?.remotePeer?.publicKey,t),o=await this.createSecureConnection(s,n);e.source=o.source,e.sink=o.sink;let i=Je(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:gs(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let s of e){let n=t.get(s);if(n!=null)return n}if(e.length)throw new Rl("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let s=Jr(e,{lengthEncoder:Hi,lengthDecoder:zc,maxDataLength:65535}),n=await this.performHandshakeResponder(s,this.components.privateKey,t?.remotePeer?.publicKey,t),o=await this.createSecureConnection(s,n);e.source=o.source,e.sink=o.sink;let i=Je(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:gs(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,s,n){let o,i=n?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{o=await Gx({connection:e,privateKey:t,remoteIdentityKey:s,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){throw this.metrics?.xxHandshakeErrors.increment(),a}return o}async performHandshakeResponder(e,t,s,n){let o,i=n?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{o=await Vx({connection:e,privateKey:t,remoteIdentityKey:s,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){throw this.metrics?.xxHandshakeErrors.increment(),a}return o}async createSecureConnection(e,t){let[s,n]=fw(),o=e.unwrap();return await st(s,Yx(t,this.metrics),o,i=>Gt(i,{lengthDecoder:zc}),Xx(t,this.metrics),s),n}};function Zx(r={}){return e=>new Dh(e,r)}X();function Mh(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}ot();X();var Br=class extends Error{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e),this.name="InvalidFrameError"}},$i=class extends Error{static name="UnrequestedPingError";constructor(e="Unrequested ping error"){super(e),this.name="UnrequestedPingError"}},Gi=class extends Error{static name="NotMatchingPingError";constructor(e="Unrequested ping error"){super(e),this.name="NotMatchingPingError"}},Oh=class extends Error{static name="InvalidStateError";constructor(e="Invalid state"){super(e),this.name="InvalidStateError"}},Lh=class extends Error{static name="StreamAlreadyExistsError";constructor(e="Strean already exists"){super(e),this.name="StreamAlreadyExistsError"}},Rh=class extends Error{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e),this.name="DecodeInvalidVersionError"}},Nh=class extends Error{static name="BothClientsError";constructor(e="Both clients"){super(e),this.name="BothClientsError"}},Vi=class extends Error{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e),this.name="ReceiveWindowExceededError"}};var Qx=new Set([Br.name,$i.name,Gi.name,Lh.name,Rh.name,Nh.name,Vi.name]),Vc=256*1024,Jx=16*1024*1024;var ev={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,initialStreamWindowSize:Vc,maxStreamWindowSize:Jx,maxMessageSize:64*1024};function tv(r){if(r.keepAliveInterval<=0)throw new V("keep-alive interval must be positive");if(r.maxInboundStreams<0)throw new V("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams<0)throw new V("max outbound streams must be larger or equal 0");if(r.initialStreamWindowSize<Vc)throw new V("InitialStreamWindowSize must be larger or equal 256 kB");if(r.maxStreamWindowSize<r.initialStreamWindowSize)throw new V("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.maxStreamWindowSize>2**32-1)throw new V("MaxStreamWindowSize must be less than equal MAX_UINT32");if(r.maxMessageSize<1024)throw new V("MaxMessageSize must be greater than a kilobyte")}ot();var Ke;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(Ke||(Ke={}));var ke;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(ke||(ke={}));var zse=Object.values(ke).filter(r=>typeof r!="string"),rv=0,yr;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(yr||(yr={}));var ln=12;var sv=2**24;function SP(r){if(r[0]!==rv)throw new Br("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*sv+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*sv+(r[9]<<16)+(r[10]<<8)+r[11]}}var Bh=class{source;buffer;frameInProgress;constructor(e){this.source=IP(e),this.buffer=new W,this.frameInProgress=!1}async*emitFrames(){for await(let e of this.source)for(this.buffer.append(e);;){let t=this.readHeader();if(t===void 0)break;let{type:s,length:n}=t;s===Ke.Data?(this.frameInProgress=!0,yield{header:t,readData:this.readBytes.bind(this,n)}):yield{header:t}}}readHeader(){if(this.frameInProgress)throw new Oh("decoding frame already in progress");if(this.buffer.length<ln)return;let e=SP(this.buffer.subarray(0,ln));return this.buffer.consume(ln),e}async readBytes(e){if(this.buffer.length<e){for await(let s of this.source)if(this.buffer.append(s),this.buffer.length>=e)break}let t=this.buffer.sublist(0,e);return this.buffer.consume(e),this.frameInProgress=!1,t}};function IP(r){if(r[Symbol.iterator]!==void 0){let e=r[Symbol.iterator]();return e.return=void 0,{[Symbol.iterator](){return e}}}else if(r[Symbol.asyncIterator]!==void 0){let e=r[Symbol.asyncIterator]();return e.return=void 0,{[Symbol.asyncIterator](){return e}}}else throw new Error("a source must be either an iterable or an async iterable")}function Zm(r){let e=new Uint8Array(ln);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}X();X();ot();function nv(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function ov(r,e){let t=Mh(r).return?.();nv(t)&&t.catch(s=>{e.error("could not cause iterator to return",s)})}var _P=5e3;function Qm(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Fh=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=fe(),this.closed=fe(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??_P,this.onEnd=e.onEnd,this.onCloseRead=e.onCloseRead,this.onCloseWrite=e.onCloseWrite,this.onReset=e.onReset,this.onAbort=e.onAbort,this.source=this.streamSource=dt({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new Fl(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let n=this.sendNewStream(t);Qm(n)&&await n}let s=()=>{ov(e,this.log)};try{this.sinkController.signal.addEventListener("abort",s),this.log.trace("sink reading from source");for await(let n of e){n=n instanceof Uint8Array?new W(n):n;let o=this.sendData(n,t);Qm(o)&&(this.sendingData=fe(),await o,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",s)}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(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),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(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),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(e){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await Ce(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=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(e)),t==="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(e={}){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 Ce(this.sink([]),e.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Ce(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Ce(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();Qm(t)&&t.catch(s=>{this.log.error("error sending reset message",s)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let e=new Bl("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){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(e))}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(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};function AP(r){return r[Symbol.asyncIterator]!=null}function iv(r){return r?.then!=null}function CP(r,e){let t=0;if(AP(r))return(async function*(){for await(let c of r){let l=e(c,t++);iv(l)&&await l,yield c}})();let s=Zu(r),{value:n,done:o}=s.next();if(o===!0)return(function*(){})();if(typeof e(n,t++)?.then=="function")return(async function*(){yield n;for(let c of s){let l=e(c,t++);iv(l)&&await l,yield c}})();let a=e;return(function*(){yield n;for(let c of s)a(c,t++),yield c})()}var av=CP;var br;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished"})(br||(br={}));var Uh=class extends Fh{name;state;config;_id;sendWindowCapacity;sendWindowCapacityUpdate;recvWindow;recvWindowCapacity;epochStart;getRTT;sendFrame;constructor(e){super({...e,onEnd:t=>{this.state=br.Finished,e.onEnd?.(t)}}),this.config=e.config,this._id=parseInt(e.id,10),this.name=e.name,this.state=e.state,this.sendWindowCapacity=Vc,this.recvWindow=this.config.initialStreamWindowSize,this.recvWindowCapacity=this.recvWindow,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame,this.source=av(this.source,()=>{this.sendWindowUpdate()})}async sendNewStream(){}async sendData(e,t={}){for(e=e.sublist();e.byteLength!==0;){if(this.sendWindowCapacity===0&&(this.log?.trace("wait for send window capacity, status %s",this.status),await this.waitForSendWindowCapacity(t),this.status==="closed"||this.status==="aborted"||this.status==="reset")){this.log?.trace("%s while waiting for send window capacity",this.status);return}let s=Math.min(this.sendWindowCapacity,this.config.maxMessageSize-ln,e.length),n=this.getSendFlags();this.sendFrame({type:Ke.Data,flag:n,streamID:this._id,length:s},e.sublist(0,s)),this.sendWindowCapacity-=s,e.consume(s)}}async sendReset(){this.sendFrame({type:Ke.WindowUpdate,flag:ke.RST,streamID:this._id,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|ke.FIN;this.sendFrame({type:Ke.WindowUpdate,flag:e,streamID:this._id,length:0})}async sendCloseRead(){}async waitForSendWindowCapacity(e={}){if(this.sendWindowCapacity>0)return;let t,s,n=()=>{this.status==="open"||this.status==="closing"?s(new Lt("Stream aborted")):t()};e.signal?.addEventListener("abort",n);try{await new Promise((o,i)=>{this.sendWindowCapacityUpdate=()=>{o()},s=i,t=o})}finally{e.signal?.removeEventListener("abort",n)}}handleWindowUpdate(e){this.log?.trace("stream received window update id=%s",this._id),this.processFlags(e.flag);let t=this.sendWindowCapacity;this.sendWindowCapacity+=e.length,t===0&&e.length>0&&this.sendWindowCapacityUpdate?.()}async handleData(e,t){if(this.log?.trace("stream received data id=%s",this._id),this.processFlags(e.flag),this.recvWindowCapacity<e.length)throw new Vi("Receive window exceeded");let s=await t();this.recvWindowCapacity-=e.length,this.sourcePush(s)}processFlags(e){(e&ke.ACK)===ke.ACK&&this.state===br.SYNSent&&(this.state=br.Established),(e&ke.FIN)===ke.FIN&&this.remoteCloseWrite(),(e&ke.RST)===ke.RST&&this.reset()}getSendFlags(){switch(this.state){case br.Init:return this.state=br.SYNSent,ke.SYN;case br.SYNReceived:return this.state=br.Established,ke.ACK;default:return 0}}sendWindowUpdate(){let e=this.getSendFlags(),t=Date.now(),s=this.getRTT();if(e===0&&s>-1&&t-this.epochStart<s*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.config.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let n=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Ke.WindowUpdate,flag:e,streamID:this._id,length:n})}};var cv="/yamux/1.0.0",TP=500,Kh=class{protocol=cv;_components;_init;constructor(e,t={}){this._components=e,this._init=t}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[et]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new Jm(this._components,{...this._init,...e})}},Jm=class{protocol=cv;source;sink;config;log;logger;closeController;nextStreamID;_streams;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;onIncomingStream;onStreamEnd;constructor(e,t){this.client=t.direction==="outbound",this.config={...ev,...t},this.logger=e.logger,this.log=this.logger.forComponent("libp2p:yamux"),tv(this.config),this.closeController=new AbortController,J(1/0,this.closeController.signal),this.onIncomingStream=t.onIncomingStream,this.onStreamEnd=t.onStreamEnd,this._streams=new Map,this.source=dt({onEnd:()=>{this.log?.trace("muxer source ended"),this._streams.forEach(s=>{s.destroy()})}}),this.sink=async s=>{let n=()=>{let a=Mh(s);if(a.return!=null){let c=a.return();PP(c)&&c.catch(l=>{this.log?.("could not cause sink source to return",l)})}},o,i;try{let a=new Bh(s);try{this.closeController.signal.addEventListener("abort",n);for await(let c of a.emitFrames())await this.handleFrame(c.header,c.readData)}finally{this.closeController.signal.removeEventListener("abort",n)}o=yr.NormalTermination}catch(a){Qx.has(a.name)?(this.log?.error("protocol error in sink",a),o=yr.ProtocolError):(this.log?.error("internal error in sink",a),o=yr.InternalError),i=a}this.log?.trace("muxer sink ended"),i!=null?this.abort(i,o):await this.close({reason:o})},this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log?.trace("muxer created"),this.config.enableKeepAlive&&this.keepAliveLoop().catch(s=>this.log?.error("keepalive error: %s",s)),this.ping().catch(s=>this.log?.error("ping error: %s",s))}get streams(){return Array.from(this._streams.values())}newStream(e){if(this.remoteGoAway!==void 0)throw new Ws("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Ws("Muxer closed locally");let t=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.config.maxOutboundStreams)throw new Qo("max outbound streams exceeded");this.log?.trace("new outgoing stream id=%s",t);let s=this._newStream(t,e,br.Init,"outbound");return this._streams.set(t,s),this.numOutboundStreams++,s.sendWindowUpdate(),s}async ping(){if(this.remoteGoAway!==void 0)throw new Ws("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Ws("Muxer closed locally");if(this.activePing===void 0){let e=()=>{};this.activePing={id:this.nextPingID++,promise:new Promise((n,o)=>{let i=()=>{o(new Ws("Muxer closed locally"))};this.closeController.signal.addEventListener("abort",i,{once:!0}),e=()=>{this.closeController.signal.removeEventListener("abort",i),n()}}),resolve:e};let t=Date.now();this.sendPing(this.activePing.id);try{await this.activePing.promise}finally{delete this.activePing}let s=Date.now();this.rtt=s-t}else await this.activePing.promise;return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.closeController.signal.aborted)return;let t=e?.reason??yr.NormalTermination;if(this.log?.trace("muxer close reason=%s",t),e.signal==null){let s=AbortSignal.timeout(TP);J(1/0,s),e={...e,signal:s}}try{await Promise.all([...this._streams.values()].map(async s=>s.close(e))),this.sendGoAway(t),this._closeMuxer()}catch(s){this.abort(s)}}abort(e,t){if(!this.closeController.signal.aborted){t=t??yr.InternalError,this.log?.error("muxer abort reason=%s error=%s",t,e);for(let s of this._streams.values())s.abort(e);this.sendGoAway(t),this._closeMuxer()}}isClosed(){return this.closeController.signal.aborted}_closeMuxer(){this.closeController.abort(),this.source.end()}_newStream(e,t,s,n){if(this._streams.get(e)!=null)throw new V("Stream already exists with that id");let o=new Uh({id:e.toString(),name:t,state:s,direction:n,sendFrame:this.sendFrame.bind(this),onEnd:()=>{this.closeStream(e),this.onStreamEnd?.(o)},log:this.logger.forComponent(`libp2p:yamux:${n}:${e}`),config:this.config,getRTT:this.getRTT.bind(this)});return o}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--,this._streams.delete(e)}async keepAliveLoop(){for(this.log?.trace("muxer keepalive enabled interval=%s",this.config.keepAliveInterval);;){let e;try{await Ce(new Promise(t=>{e=setTimeout(t,this.config.keepAliveInterval)}),this.closeController.signal),this.ping().catch(t=>this.log?.error("ping error: %s",t))}catch{clearInterval(e);return}}}async handleFrame(e,t){let{streamID:s,type:n,length:o}=e;if(this.log?.trace("received frame %o",e),s===0)switch(n){case Ke.Ping:{this.handlePing(e);return}case Ke.GoAway:{this.handleGoAway(o);return}default:throw new Br("Invalid frame type")}else switch(e.type){case Ke.Data:case Ke.WindowUpdate:{await this.handleStreamMessage(e,t);return}default:throw new Br("Invalid frame type")}}handlePing(e){if(e.flag===ke.SYN)this.log?.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,ke.ACK);else if(e.flag===ke.ACK)this.log?.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new Br("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new $i("ping not requested");if(this.activePing.id!==e)throw new Gi("ping doesn't match our id");this.activePing.resolve()}handleGoAway(e){this.log?.trace("received GoAway reason=%s",yr[e]??"unknown"),this.remoteGoAway=e;for(let t of this._streams.values())t.reset();this._closeMuxer()}async handleStreamMessage(e,t){let{streamID:s,flag:n,type:o}=e;(n&ke.SYN)===ke.SYN&&this.incomingStream(s);let i=this._streams.get(s);if(i===void 0){if(o===Ke.Data){if(this.log?.("discarding data for stream id=%s",s),t===void 0)throw new Error("unreachable");await t()}else this.log?.trace("frame for missing stream id=%s",s);return}switch(o){case Ke.WindowUpdate:{i.handleWindowUpdate(e);return}case Ke.Data:{if(t===void 0)throw new Error("unreachable");await i.handleData(e,t);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new V("Both endpoints are clients");if(this._streams.has(e))return;if(this.log?.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:Ke.WindowUpdate,flag:ke.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.config.maxInboundStreams){this.log?.("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:Ke.WindowUpdate,flag:ke.RST,streamID:e,length:0});return}let t=this._newStream(e,void 0,br.SYNReceived,"inbound");this.numInboundStreams++,this._streams.set(e,t),this.onIncomingStream?.(t)}sendFrame(e,t){if(this.log?.trace("sending frame %o",e),e.type===Ke.Data){if(t===void 0)throw new Br("Invalid frame");this.source.push(new W(Zm(e),t))}else this.source.push(Zm(e))}sendPing(e,t=ke.SYN){t===ke.SYN?this.log?.trace("sending ping request pingId=%s",e):this.log?.trace("sending ping response pingId=%s",e),this.sendFrame({type:Ke.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=yr.NormalTermination){this.log?.("sending GoAway reason=%s",yr[e]),this.localGoAway=e,this.sendFrame({type:Ke.GoAway,flag:0,streamID:0,length:e})}};function PP(r){return r!=null&&typeof r.then=="function"}function lv(r={}){return e=>new Kh(e,r)}function eg(r,e){let t=Jr(r,e),s={read:async(n,o)=>{let i=await t.read(o);return n.decode(i)},write:async(n,o,i)=>{await t.write(o.encode(n),i)},writeV:async(n,o,i)=>{await t.writeV(n.map(a=>o.encode(a)),i)},pb:n=>({read:async o=>s.read(n,o),write:async(o,i)=>s.write(o,n,i),writeV:async(o,i)=>s.writeV(o,n,i),unwrap:()=>s}),unwrap:()=>t.unwrap()};return s}var uv="0.1.0";var hv="1.0.0";zs();var Wc;(function(r){let e;r.codec=()=>(e==null&&(e=he((t,s,n={})=>{if(n.lengthDelimited!==!1&&s.fork(),t.protocolVersion!=null&&(s.uint32(42),s.string(t.protocolVersion)),t.agentVersion!=null&&(s.uint32(50),s.string(t.agentVersion)),t.publicKey!=null&&(s.uint32(10),s.bytes(t.publicKey)),t.listenAddrs!=null)for(let o of t.listenAddrs)s.uint32(18),s.bytes(o);if(t.observedAddr!=null&&(s.uint32(34),s.bytes(t.observedAddr)),t.protocols!=null)for(let o of t.protocols)s.uint32(26),s.string(o);t.signedPeerRecord!=null&&(s.uint32(66),s.bytes(t.signedPeerRecord)),n.lengthDelimited!==!1&&s.ldelim()},(t,s,n={})=>{let o={listenAddrs:[],protocols:[]},i=s==null?t.len:t.pos+s;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 5:{o.protocolVersion=t.string();break}case 6:{o.agentVersion=t.string();break}case 1:{o.publicKey=t.bytes();break}case 2:{if(n.limits?.listenAddrs!=null&&o.listenAddrs.length===n.limits.listenAddrs)throw new Ie('Decode error - map field "listenAddrs" had too many elements');o.listenAddrs.push(t.bytes());break}case 4:{o.observedAddr=t.bytes();break}case 3:{if(n.limits?.protocols!=null&&o.protocols.length===n.limits.protocols)throw new Ie('Decode error - map field "protocols" had too many elements');o.protocols.push(t.string());break}case 8:{o.signedPeerRecord=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>ue(t,r.codec()),r.decode=(t,s)=>le(t,r.codec(),s)})(Wc||(Wc={}));ft();X();ce();ge();var os={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function dv(r){if(r!=null&&r.length>0)try{return G(r)}catch{}}function MP(r,e){return e??r.userAgent}async function fv(r,e,t,s,n){if(t("received identify from %p",s.remotePeer),n==null)throw new Yt("message was null or undefined");let o={};if(n.listenAddrs.length>0&&(o.addresses=n.listenAddrs.map(c=>({isCertified:!1,multiaddr:G(c)}))),n.protocols.length>0&&(o.protocols=n.protocols),n.publicKey!=null){let c=Je(n.publicKey);if(!gs(c).equals(s.remotePeer))throw new Yt("public key did not match remote PeerId");o.publicKey=c}let i;if(n.signedPeerRecord!=null){t.trace("received signedPeerRecord from %p",s.remotePeer);let c=n.signedPeerRecord,l=await Or.openAndCertify(c,Qt.DOMAIN),u=Qt.createFromProtobuf(l.payload),h=Wr(l.publicKey.toCID());if(!u.peerId.equals(h))throw new Yt("signing key does not match PeerId in the PeerRecord");if(!s.remotePeer.equals(u.peerId))throw new Yt("signing key does not match remote PeerId");let d;try{d=await r.get(u.peerId)}catch(f){if(f.name!=="NotFoundError")throw f}if(d!=null&&(o.metadata=d.metadata,d.peerRecordEnvelope!=null)){let f=Or.createFromProtobuf(d.peerRecordEnvelope),p=Qt.createFromProtobuf(f.payload);p.seqNumber>=u.seqNumber&&(t("sequence number was lower or equal to existing sequence number - stored: %d received: %d",p.seqNumber,u.seqNumber),u=p,c=d.peerRecordEnvelope)}o.peerRecordEnvelope=c,o.addresses=u.multiaddrs.map(f=>({isCertified:!0,multiaddr:f})),i={seq:u.seqNumber,addresses:u.multiaddrs}}else t("%p did not send a signed peer record",s.remotePeer);if(t.trace("patching %p with",s.remotePeer,o),await r.patch(s.remotePeer,o),n.agentVersion!=null||n.protocolVersion!=null){let c={};n.agentVersion!=null&&(c.AgentVersion=L(n.agentVersion)),n.protocolVersion!=null&&(c.ProtocolVersion=L(n.protocolVersion)),t.trace("merging %p metadata",s.remotePeer,c),await r.merge(s.remotePeer,{metadata:c})}let a={peerId:s.remotePeer,protocolVersion:n.protocolVersion,agentVersion:n.agentVersion,publicKey:n.publicKey,listenAddrs:n.listenAddrs.map(c=>G(c)),observedAddr:n.observedAddr==null?void 0:G(n.observedAddr),protocols:n.protocols,signedPeerRecord:i,connection:s};return e.safeDispatchEvent("peer:identify",{detail:a}),a}var Hh=class{host;protocol;started;timeout;peerId;privateKey;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.privateKey=e.privateKey,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??os.timeout,this.maxInboundStreams=t.maxInboundStreams??os.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??os.maxOutboundStreams,this.maxMessageSize=t.maxMessageSize??os.maxMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??os.maxObservedAddresses,this.runOnLimitedConnection=t.runOnLimitedConnection??os.runOnLimitedConnection,this.host={protocolVersion:`${t.protocolPrefix??os.protocolPrefix}/${uv}`,agentVersion:MP(e.nodeInfo,t.agentVersion)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:L(this.host.agentVersion),ProtocolVersion:L(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,e=>{this.handleProtocol(e).catch(t=>{this.log.error(t)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}};ft();X();ce();function pv(r){try{for(let{code:e,value:t}of r.getComponents())if(t!=null&&e===41)return u4("2000::/3",t)}catch{}return!1}Ze();var zh=class extends Hh{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??os.protocolPrefix}/${"id"}/${hv}`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??os.runOnConnectionOpen)&&e.events.addEventListener("connection:open",s=>{let n=s.detail;this.identify(n).catch(o=>{o.name!==Cn.name&&this.log.error("error during identify trigged by connection:open",o)})})}[et]=["@libp2p/identify"];async _identify(e,t={}){let s;if(t.signal==null){let n=AbortSignal.timeout(this.timeout);J(1/0,n),t={...t,signal:n}}try{s=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});let o=await eg(s,{maxDataLength:this.maxMessageSize}).pb(Wc).read(t);return await s.close(t),o}catch(n){throw s?.abort(n),n}}async identify(e,t={}){let s=await this._identify(e,t),{publicKey:n,protocols:o,observedAddr:i}=s;if(n==null)throw new Yt("Public key was missing from identify message");let a=Je(n),c=Wr(a.toCID()),l=e.log.newScope("identify");if(!e.remotePeer.equals(c))throw new Yt("Identified peer does not match the expected peer");if(this.peerId.equals(c))throw new Yt("Identified peer is our own peer id?");return this.maybeAddObservedAddress(i,l),l("completed for peer %p and protocols %o",c,o),fv(this.peerStore,this.events,l,e,s)}maybeAddObservedAddress(e,t){let s=dv(e);if(s==null)return;if(t.trace("our observed address was %a",s),Ss(s)){this.log.trace("our observed address was private");return}let n=s.getComponents();if((n[0].code===41||n[0].code===42&&n[1].code===41)&&!pv(s)){t.trace("our observed address was IPv6 but not a global unicast address");return}Es.exactMatch(s)||(t.trace("storing the observed address"),this.addressManager.addObservedAddr(s))}async handleProtocol(e){let{connection:t,stream:s}=e,n=t.log.newScope("identify"),o=AbortSignal.timeout(this.timeout);J(1/0,o);try{let i=await this.peerStore.get(this.peerId),a=this.addressManager.getAddresses().map(h=>h.decapsulateCode(yi("p2p").code)),c=i.peerRecordEnvelope;if(a.length>0&&c==null){let h=new Qt({peerId:this.peerId,multiaddrs:a});c=(await Or.seal(h,this.privateKey)).marshal().subarray()}let l=t.remoteAddr.bytes;mb.matches(t.remoteAddr)||(l=void 0),await eg(s).pb(Wc).write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Ve(this.privateKey.publicKey),listenAddrs:a.map(h=>h.bytes),signedPeerRecord:c,observedAddr:l,protocols:i.protocols},{signal:o}),await s.close({signal:o})}catch(i){n.error("could not respond to identify request",i),s.abort(i)}}};function mv(r={}){return e=>new zh(e,r)}X();Ze();Kt();var gv="1.0.0",yv="ping",bv="ipfs";var qh=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??bv}/${yv}/${gv}`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[et]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){let t=e.connection.log.newScope("ping");t.trace("ping from %p",e.connection.remotePeer);let{stream:s}=e,n=Date.now(),o=ho(s),i=!1;Promise.resolve().then(async()=>{for(;;){let a=AbortSignal.timeout(this.timeout);J(1/0,a),a.addEventListener("abort",()=>{s?.abort(new Vr("ping timeout"))});let c=await o.read({bytes:32,signal:a});await o.write(c,{signal:a}),i=!0}}).catch(a=>{i&&a.name==="UnexpectedEOFError"&&s.readStatus!=="ready"||(t.error("ping from %p failed with error - %e",e.connection.remotePeer,a),s?.abort(a))}).finally(()=>{let a=Date.now()-n;t("ping from %p complete in %dms",e.connection.remotePeer,a);let c=AbortSignal.timeout(this.timeout);J(1/0,c),s.close({signal:c}).catch(l=>{t.error("error closing ping stream from %p - %e",e.connection.remotePeer,l),s?.abort(l)})})}async ping(e,t={}){let s=Date.now(),n=Gr(32),o=await this.components.connectionManager.openConnection(e,t),i=o.log.newScope("ping"),a;if(t.signal==null){let c=AbortSignal.timeout(this.timeout);t={...t,signal:c}}try{a=await o.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});let c=ho(a),[,l]=await Promise.all([c.write(n,t),c.read({...t,bytes:32})]),u=Date.now()-s;if(!ae(n,l.subarray()))throw new Hl(`Received wrong ping ack after ${u}ms`);return i("ping %p complete in %dms",o.remotePeer,u),u}catch(c){throw i.error("error while pinging %p",o.remotePeer,c),a?.abort(c),c}finally{a!=null&&await a.close(t)}}};function wv(r={}){return e=>new qh(e,r)}X();ce();wr();ot();nt();function $h(r){return r[Symbol.asyncIterator]!=null}var Gh=r=>{let e=Le(r),t=je(e);return rr(r,t),Gh.bytes=e,t};Gh.bytes=0;function Wi(r,e){e=e??{};let t=e.lengthEncoder??Gh;function*s(n){let o=t(n.byteLength);o instanceof Uint8Array?yield o:yield*o,n instanceof Uint8Array?yield n:yield*n}return $h(r)?(async function*(){for await(let n of r)yield*s(n)})():(function*(){for(let n of r)yield*s(n)})()}Wi.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Gh;return new W(t(r.byteLength),r)};wr();ot();var Vh=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Wh=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},jh=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},jc=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var BP=8,FP=1024*1024*4,Io;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Io||(Io={}));var rg=r=>{let e=as(r);return rg.bytes=Le(e),e};rg.bytes=0;function Yc(r,e){let t=new W,s=Io.LENGTH,n=-1,o=e?.lengthDecoder??rg,i=e?.maxLengthLength??BP,a=e?.maxDataLength??FP;function*c(){for(;t.byteLength>0;){if(s===Io.LENGTH)try{if(n=o(t),n<0)throw new Vh("Invalid message length");if(n>a)throw new Wh("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(n),s=Io.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new jh("Message length length too long");break}throw l}if(s===Io.DATA){if(t.byteLength<n)break;let l=t.sublist(0,n);t.consume(n),e?.onData!=null&&e.onData(l),yield l,s=Io.LENGTH}}}return $h(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new jc("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new jc("Unexpected end of input")})()}Yc.fromReader=(r,e)=>{let t=1,s=(async function*(){for(;;)try{let{done:o,value:i}=await r.next(t);if(o===!0)return;i!=null&&(yield i)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return Yc(s,{...e??{},onLength:o=>{t=o}})};ir();var sg="/floodsub/1.0.0",ng="/meshsub/1.0.0",xv="/meshsub/1.1.0",Yh="/meshsub/1.2.0";var vv="ERR_TOPIC_VALIDATOR_REJECT",Ev="ERR_TOPIC_VALIDATOR_IGNORE";var Sv={maxSubscriptions:1/0,maxMessages:1/0,maxIhaveMessageIDs:1/0,maxIwantMessageIDs:1/0,maxIdontwantMessageIDs:1/0,maxControlMessages:1/0,maxPeerInfos:1/0};zs();var Ns;(function(r){let e;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.subscribe!=null&&(p.uint32(8),p.bool(f.subscribe)),f.topic!=null&&(p.uint32(18),p.string(f.topic)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>3){case 1:{g.subscribe=f.bool();break}case 2:{g.topic=f.string();break}default:{f.skipType(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(e=r.SubOpts||(r.SubOpts={}));let t;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.from!=null&&(p.uint32(10),p.bytes(f.from)),f.data!=null&&(p.uint32(18),p.bytes(f.data)),f.seqno!=null&&(p.uint32(26),p.bytes(f.seqno)),f.topic!=null&&f.topic!==""&&(p.uint32(34),p.string(f.topic)),f.signature!=null&&(p.uint32(42),p.bytes(f.signature)),f.key!=null&&(p.uint32(50),p.bytes(f.key)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={topic:""},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>3){case 1:{g.from=f.bytes();break}case 2:{g.data=f.bytes();break}case 3:{g.seqno=f.bytes();break}case 4:{g.topic=f.string();break}case 5:{g.signature=f.bytes();break}case 6:{g.key=f.bytes();break}default:{f.skipType(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(t=r.Message||(r.Message={}));let s;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.ihave!=null)for(let g of f.ihave)p.uint32(10),r.ControlIHave.codec().encode(g,p);if(f.iwant!=null)for(let g of f.iwant)p.uint32(18),r.ControlIWant.codec().encode(g,p);if(f.graft!=null)for(let g of f.graft)p.uint32(26),r.ControlGraft.codec().encode(g,p);if(f.prune!=null)for(let g of f.prune)p.uint32(34),r.ControlPrune.codec().encode(g,p);if(f.idontwant!=null)for(let g of f.idontwant)p.uint32(42),r.ControlIDontWant.codec().encode(g,p);m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={ihave:[],iwant:[],graft:[],prune:[],idontwant:[]},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>3){case 1:{if(m.limits?.ihave!=null&&g.ihave.length===m.limits.ihave)throw new Ie('Decode error - map field "ihave" had too many elements');g.ihave.push(r.ControlIHave.codec().decode(f,f.uint32(),{limits:m.limits?.ihave$}));break}case 2:{if(m.limits?.iwant!=null&&g.iwant.length===m.limits.iwant)throw new Ie('Decode error - map field "iwant" had too many elements');g.iwant.push(r.ControlIWant.codec().decode(f,f.uint32(),{limits:m.limits?.iwant$}));break}case 3:{if(m.limits?.graft!=null&&g.graft.length===m.limits.graft)throw new Ie('Decode error - map field "graft" had too many elements');g.graft.push(r.ControlGraft.codec().decode(f,f.uint32(),{limits:m.limits?.graft$}));break}case 4:{if(m.limits?.prune!=null&&g.prune.length===m.limits.prune)throw new Ie('Decode error - map field "prune" had too many elements');g.prune.push(r.ControlPrune.codec().decode(f,f.uint32(),{limits:m.limits?.prune$}));break}case 5:{if(m.limits?.idontwant!=null&&g.idontwant.length===m.limits.idontwant)throw new Ie('Decode error - map field "idontwant" had too many elements');g.idontwant.push(r.ControlIDontWant.codec().decode(f,f.uint32(),{limits:m.limits?.idontwant$}));break}default:{f.skipType(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(s=r.ControlMessage||(r.ControlMessage={}));let n;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.topicID!=null&&(p.uint32(10),p.string(f.topicID)),f.messageIDs!=null)for(let g of f.messageIDs)p.uint32(18),p.bytes(g);m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={messageIDs:[]},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>3){case 1:{g.topicID=f.string();break}case 2:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new Ie('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(n=r.ControlIHave||(r.ControlIHave={}));let o;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.messageIDs!=null)for(let g of f.messageIDs)p.uint32(10),p.bytes(g);m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={messageIDs:[]},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>3){case 1:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new Ie('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(o=r.ControlIWant||(r.ControlIWant={}));let i;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.topicID!=null&&(p.uint32(10),p.string(f.topicID)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>3){case 1:{g.topicID=f.string();break}default:{f.skipType(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(i=r.ControlGraft||(r.ControlGraft={}));let a;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.topicID!=null&&(p.uint32(10),p.string(f.topicID)),f.peers!=null)for(let g of f.peers)p.uint32(18),r.PeerInfo.codec().encode(g,p);f.backoff!=null&&(p.uint32(24),p.uint64Number(f.backoff)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={peers:[]},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>3){case 1:{g.topicID=f.string();break}case 2:{if(m.limits?.peers!=null&&g.peers.length===m.limits.peers)throw new Ie('Decode error - map field "peers" had too many elements');g.peers.push(r.PeerInfo.codec().decode(f,f.uint32(),{limits:m.limits?.peers$}));break}case 3:{g.backoff=f.uint64Number();break}default:{f.skipType(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(a=r.ControlPrune||(r.ControlPrune={}));let c;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{m.lengthDelimited!==!1&&p.fork(),f.peerID!=null&&(p.uint32(10),p.bytes(f.peerID)),f.signedPeerRecord!=null&&(p.uint32(18),p.bytes(f.signedPeerRecord)),m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>3){case 1:{g.peerID=f.bytes();break}case 2:{g.signedPeerRecord=f.bytes();break}default:{f.skipType(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(c=r.PeerInfo||(r.PeerInfo={}));let l;(function(h){let d;h.codec=()=>(d==null&&(d=he((f,p,m={})=>{if(m.lengthDelimited!==!1&&p.fork(),f.messageIDs!=null)for(let g of f.messageIDs)p.uint32(10),p.bytes(g);m.lengthDelimited!==!1&&p.ldelim()},(f,p,m={})=>{let g={messageIDs:[]},y=p==null?f.len:f.pos+p;for(;f.pos<y;){let w=f.uint32();switch(w>>>3){case 1:{if(m.limits?.messageIDs!=null&&g.messageIDs.length===m.limits.messageIDs)throw new Ie('Decode error - map field "messageIDs" had too many elements');g.messageIDs.push(f.bytes());break}default:{f.skipType(w&7);break}}}return g})),d),h.encode=f=>ue(f,h.codec()),h.decode=(f,p)=>le(f,h.codec(),p)})(l=r.ControlIDontWant||(r.ControlIDontWant={}));let u;r.codec=()=>(u==null&&(u=he((h,d,f={})=>{if(f.lengthDelimited!==!1&&d.fork(),h.subscriptions!=null)for(let p of h.subscriptions)d.uint32(10),r.SubOpts.codec().encode(p,d);if(h.messages!=null)for(let p of h.messages)d.uint32(18),r.Message.codec().encode(p,d);h.control!=null&&(d.uint32(26),r.ControlMessage.codec().encode(h.control,d)),f.lengthDelimited!==!1&&d.ldelim()},(h,d,f={})=>{let p={subscriptions:[],messages:[]},m=d==null?h.len:h.pos+d;for(;h.pos<m;){let g=h.uint32();switch(g>>>3){case 1:{if(f.limits?.subscriptions!=null&&p.subscriptions.length===f.limits.subscriptions)throw new Ie('Decode error - map field "subscriptions" had too many elements');p.subscriptions.push(r.SubOpts.codec().decode(h,h.uint32(),{limits:f.limits?.subscriptions$}));break}case 2:{if(f.limits?.messages!=null&&p.messages.length===f.limits.messages)throw new Ie('Decode error - map field "messages" had too many elements');p.messages.push(r.Message.codec().decode(h,h.uint32(),{limits:f.limits?.messages$}));break}case 3:{p.control=r.ControlMessage.codec().decode(h,h.uint32(),{limits:f.limits?.control});break}default:{h.skipType(g&7);break}}}return p})),u),r.encode=h=>ue(h,r.codec()),r.decode=(h,d)=>le(h,r.codec(),d)})(Ns||(Ns={}));var Xh=class{gossip;msgs=new Map;msgIdToStrFn;history=[];notValidatedCount=0;constructor(e,t,s){this.gossip=e,this.msgIdToStrFn=s;for(let n=0;n<t;n++)this.history[n]=[]}get size(){return this.msgs.size}put(e,t,s=!1){let{msgIdStr:n}=e;return this.msgs.has(n)?!1:(this.msgs.set(n,{message:t,validated:s,originatingPeers:new Set,iwantCounts:new Map}),this.history[0].push({...e,topic:t.topic}),s||this.notValidatedCount++,!0)}observeDuplicate(e,t){let s=this.msgs.get(e);s!=null&&!s.validated&&s.originatingPeers.add(t)}get(e){return this.msgs.get(this.msgIdToStrFn(e))?.message}getWithIWantCount(e,t){let s=this.msgs.get(e);if(s==null)return null;let n=(s.iwantCounts.get(t)??0)+1;return s.iwantCounts.set(t,n),{msg:s.message,count:n}}getGossipIDs(e){let t=new Map;for(let s=0;s<this.gossip;s++)this.history[s].forEach(n=>{if((this.msgs.get(n.msgIdStr)?.validated??!1)&&e.has(n.topic)){let i=t.get(n.topic);i==null&&(i=[],t.set(n.topic,i)),i.push(n.msgId)}});return t}validate(e){let t=this.msgs.get(e);if(t==null)return null;t.validated||this.notValidatedCount--;let{message:s,originatingPeers:n}=t;return t.validated=!0,t.originatingPeers=new Set,{message:s,originatingPeers:n}}shift(){this.history[this.history.length-1].forEach(t=>{let s=this.msgs.get(t.msgIdStr);s!=null&&(this.msgs.delete(t.msgIdStr),s.validated||this.notValidatedCount--)}),this.history.pop(),this.history.unshift([])}remove(e){let t=this.msgs.get(e);return t==null?null:(this.msgs.delete(e),t)}};X();X();var Iv;(function(r){r.StrictSign="StrictSign",r.StrictNoSign="StrictNoSign"})(Iv||(Iv={}));var un;(function(r){r[r.Signing=0]="Signing",r[r.Anonymous=1]="Anonymous"})(un||(un={}));var Bt;(function(r){r.Error="error",r.Ignore="ignore",r.Reject="reject",r.Blacklisted="blacklisted"})(Bt||(Bt={}));var Pt;(function(r){r.InvalidSignature="invalid_signature",r.InvalidSeqno="invalid_seqno",r.InvalidPeerId="invalid_peerid",r.SignaturePresent="signature_present",r.SeqnoPresent="seqno_present",r.FromPresent="from_present",r.TransformFailed="transform_failed"})(Pt||(Pt={}));var kt;(function(r){r.duplicate="duplicate",r.invalid="invalid",r.valid="valid"})(kt||(kt={}));function og(r){switch(r){case Ot.Ignore:return Bt.Ignore;case Ot.Reject:return Bt.Reject;default:throw new Error("Unreachable")}}var _v;(function(r){r.forward="forward",r.publish="publish"})(_v||(_v={}));var Ft;(function(r){r.Fanout="fanout",r.Random="random",r.Subscribed="subscribed",r.Outbound="outbound",r.NotEnough="not_enough",r.Opportunistic="opportunistic"})(Ft||(Ft={}));var Fr;(function(r){r.Dc="disconnected",r.BadScore="bad_score",r.Prune="prune",r.Excess="excess"})(Fr||(Fr={}));var Yi;(function(r){r.GraftBackoff="graft_backoff",r.BrokenPromise="broken_promise",r.MessageDeficit="message_deficit",r.IPColocation="IP_colocation"})(Yi||(Yi={}));var Xi;(function(r){r.LowScore="low_score",r.MaxIhave="max_ihave",r.MaxIasked="max_iasked"})(Xi||(Xi={}));var ji;(function(r){r.graylist="graylist",r.publish="publish",r.gossip="gossip",r.mesh="mesh"})(ji||(ji={}));function Av(r,e,t){return{protocolsEnabled:r.gauge({name:"gossipsub_protocol",help:"Status of enabled protocols",labelNames:["protocol"]}),topicSubscriptionStatus:r.gauge({name:"gossipsub_topic_subscription_status",help:"Status of our subscription to this topic",labelNames:["topicStr"]}),topicPeersCount:r.gauge({name:"gossipsub_topic_peer_count",help:"Number of peers subscribed to each topic",labelNames:["topicStr"]}),meshPeerCounts:r.gauge({name:"gossipsub_mesh_peer_count",help:"Number of peers in our mesh",labelNames:["topicStr"]}),meshPeerInclusionEventsFanout:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_fanout_total",help:"Number of times we include peers in a topic mesh for fanout reasons",labelNames:["topic"]}),meshPeerInclusionEventsRandom:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_random_total",help:"Number of times we include peers in a topic mesh for random reasons",labelNames:["topic"]}),meshPeerInclusionEventsSubscribed:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_subscribed_total",help:"Number of times we include peers in a topic mesh for subscribed reasons",labelNames:["topic"]}),meshPeerInclusionEventsOutbound:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_outbound_total",help:"Number of times we include peers in a topic mesh for outbound reasons",labelNames:["topic"]}),meshPeerInclusionEventsNotEnough:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_not_enough_total",help:"Number of times we include peers in a topic mesh for not_enough reasons",labelNames:["topic"]}),meshPeerInclusionEventsOpportunistic:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_opportunistic_total",help:"Number of times we include peers in a topic mesh for opportunistic reasons",labelNames:["topic"]}),meshPeerInclusionEventsUnknown:r.gauge({name:"gossipsub_mesh_peer_inclusion_events_unknown_total",help:"Number of times we include peers in a topic mesh for unknown reasons",labelNames:["topic"]}),meshPeerChurnEventsDisconnected:r.gauge({name:"gossipsub_peer_churn_events_disconnected_total",help:"Number of times we remove peers in a topic mesh for disconnected reasons",labelNames:["topic"]}),meshPeerChurnEventsBadScore:r.gauge({name:"gossipsub_peer_churn_events_bad_score_total",help:"Number of times we remove peers in a topic mesh for bad_score reasons",labelNames:["topic"]}),meshPeerChurnEventsPrune:r.gauge({name:"gossipsub_peer_churn_events_prune_total",help:"Number of times we remove peers in a topic mesh for prune reasons",labelNames:["topic"]}),meshPeerChurnEventsExcess:r.gauge({name:"gossipsub_peer_churn_events_excess_total",help:"Number of times we remove peers in a topic mesh for excess reasons",labelNames:["topic"]}),meshPeerChurnEventsUnknown:r.gauge({name:"gossipsub_peer_churn_events_unknown_total",help:"Number of times we remove peers in a topic mesh for unknown reasons",labelNames:["topic"]}),peersPerProtocol:r.gauge({name:"gossipsub_peers_per_protocol_count",help:"Peers connected for each topic",labelNames:["protocol"]}),heartbeatDuration:r.histogram({name:"gossipsub_heartbeat_duration_seconds",help:"The time it takes to complete one iteration of the heartbeat",buckets:[.01,.1,1]}),heartbeatSkipped:r.gauge({name:"gossipsub_heartbeat_skipped",help:"Heartbeat run took longer than heartbeat interval so next is skipped"}),acceptedMessagesTotal:r.gauge({name:"gossipsub_accepted_messages_total",help:"Total accepted messages for each topic",labelNames:["topic"]}),ignoredMessagesTotal:r.gauge({name:"gossipsub_ignored_messages_total",help:"Total ignored messages for each topic",labelNames:["topic"]}),rejectedMessagesTotal:r.gauge({name:"gossipsub_rejected_messages_total",help:"Total rejected messages for each topic",labelNames:["topic"]}),unknownValidationResultsTotal:r.gauge({name:"gossipsub_unknown_validation_results_total",help:"Total unknown validation results for each topic",labelNames:["topic"]}),asyncValidationMcacheHit:r.gauge({name:"gossipsub_async_validation_mcache_hit_total",help:"Async validation result reported by the user layer",labelNames:["hit"]}),asyncValidationDelayFromFirstSeenSec:r.histogram({name:"gossipsub_async_validation_delay_from_first_seen",help:"Async validation report delay from first seen in second",buckets:[.01,.03,.1,.3,1,3,10]}),asyncValidationUnknownFirstSeen:r.gauge({name:"gossipsub_async_validation_unknown_first_seen_count_total",help:"Async validation report unknown first seen value for message"}),peerReadStreamError:r.gauge({name:"gossipsub_peer_read_stream_err_count_total",help:"Peer read stream error"}),rpcRecvBytes:r.gauge({name:"gossipsub_rpc_recv_bytes_total",help:"RPC recv"}),rpcRecvCount:r.gauge({name:"gossipsub_rpc_recv_count_total",help:"RPC recv"}),rpcRecvSubscription:r.gauge({name:"gossipsub_rpc_recv_subscription_total",help:"RPC recv"}),rpcRecvMessage:r.gauge({name:"gossipsub_rpc_recv_message_total",help:"RPC recv"}),rpcRecvControl:r.gauge({name:"gossipsub_rpc_recv_control_total",help:"RPC recv"}),rpcRecvIHave:r.gauge({name:"gossipsub_rpc_recv_ihave_total",help:"RPC recv"}),rpcRecvIWant:r.gauge({name:"gossipsub_rpc_recv_iwant_total",help:"RPC recv"}),rpcRecvGraft:r.gauge({name:"gossipsub_rpc_recv_graft_total",help:"RPC recv"}),rpcRecvPrune:r.gauge({name:"gossipsub_rpc_recv_prune_total",help:"RPC recv"}),rpcDataError:r.gauge({name:"gossipsub_rpc_data_err_count_total",help:"RPC data error"}),rpcRecvError:r.gauge({name:"gossipsub_rpc_recv_err_count_total",help:"RPC recv error"}),rpcRecvNotAccepted:r.gauge({name:"gossipsub_rpc_rcv_not_accepted_total",help:"Total count of RPC dropped because acceptFrom() == false"}),rpcSentBytes:r.gauge({name:"gossipsub_rpc_sent_bytes_total",help:"RPC sent"}),rpcSentCount:r.gauge({name:"gossipsub_rpc_sent_count_total",help:"RPC sent"}),rpcSentSubscription:r.gauge({name:"gossipsub_rpc_sent_subscription_total",help:"RPC sent"}),rpcSentMessage:r.gauge({name:"gossipsub_rpc_sent_message_total",help:"RPC sent"}),rpcSentControl:r.gauge({name:"gossipsub_rpc_sent_control_total",help:"RPC sent"}),rpcSentIHave:r.gauge({name:"gossipsub_rpc_sent_ihave_total",help:"RPC sent"}),rpcSentIWant:r.gauge({name:"gossipsub_rpc_sent_iwant_total",help:"RPC sent"}),rpcSentGraft:r.gauge({name:"gossipsub_rpc_sent_graft_total",help:"RPC sent"}),rpcSentPrune:r.gauge({name:"gossipsub_rpc_sent_prune_total",help:"RPC sent"}),rpcSentIDontWant:r.gauge({name:"gossipsub_rpc_sent_idontwant_total",help:"RPC sent"}),msgPublishCount:r.gauge({name:"gossipsub_msg_publish_count_total",help:"Total count of msg published by topic",labelNames:["topic"]}),msgPublishPeersByTopic:r.gauge({name:"gossipsub_msg_publish_peers_total",help:"Total count of peers that we publish a msg to",labelNames:["topic"]}),directPeersPublishedTotal:r.gauge({name:"gossipsub_direct_peers_published_total",help:"Total direct peers that we publish a msg to",labelNames:["topic"]}),floodsubPeersPublishedTotal:r.gauge({name:"gossipsub_floodsub_peers_published_total",help:"Total floodsub peers that we publish a msg to",labelNames:["topic"]}),meshPeersPublishedTotal:r.gauge({name:"gossipsub_mesh_peers_published_total",help:"Total mesh peers that we publish a msg to",labelNames:["topic"]}),fanoutPeersPublishedTotal:r.gauge({name:"gossipsub_fanout_peers_published_total",help:"Total fanout peers that we publish a msg to",labelNames:["topic"]}),msgPublishBytes:r.gauge({name:"gossipsub_msg_publish_bytes_total",help:"Total count of msg publish data.length bytes",labelNames:["topic"]}),msgPublishTime:r.histogram({name:"gossipsub_msg_publish_seconds",help:"Total time in seconds to publish a message",buckets:[.001,.002,.005,.01,.1,.5,1],labelNames:["topic"]}),msgForwardCount:r.gauge({name:"gossipsub_msg_forward_count_total",help:"Total count of msg forwarded by topic",labelNames:["topic"]}),msgForwardPeers:r.gauge({name:"gossipsub_msg_forward_peers_total",help:"Total count of peers that we forward a msg to",labelNames:["topic"]}),msgReceivedPreValidation:r.gauge({name:"gossipsub_msg_received_prevalidation_total",help:"Total count of recv msgs before any validation",labelNames:["topic"]}),msgReceivedError:r.gauge({name:"gossipsub_msg_received_error_total",help:"Total count of recv msgs error",labelNames:["topic"]}),prevalidationInvalidTotal:r.gauge({name:"gossipsub_pre_validation_invalid_total",help:"Total count of invalid messages received",labelNames:["topic"]}),prevalidationValidTotal:r.gauge({name:"gossipsub_pre_validation_valid_total",help:"Total count of valid messages received",labelNames:["topic"]}),prevalidationDuplicateTotal:r.gauge({name:"gossipsub_pre_validation_duplicate_total",help:"Total count of duplicate messages received",labelNames:["topic"]}),prevalidationUnknownTotal:r.gauge({name:"gossipsub_pre_validation_unknown_status_total",help:"Total count of unknown_status messages received",labelNames:["topic"]}),msgReceivedInvalid:r.gauge({name:"gossipsub_msg_received_invalid_total",help:"Tracks specific reason of invalid",labelNames:["error"]}),msgReceivedInvalidByTopic:r.gauge({name:"gossipsub_msg_received_invalid_by_topic_total",help:"Tracks specific invalid message by topic",labelNames:["topic"]}),duplicateMsgDeliveryDelay:r.histogram({name:"gossisub_duplicate_msg_delivery_delay_seconds",help:"Time since the 1st duplicated message validated",labelNames:["topic"],buckets:[.25*t.maxMeshMessageDeliveriesWindowSec,.5*t.maxMeshMessageDeliveriesWindowSec,Number(t.maxMeshMessageDeliveriesWindowSec),2*t.maxMeshMessageDeliveriesWindowSec,4*t.maxMeshMessageDeliveriesWindowSec]}),duplicateMsgLateDelivery:r.gauge({name:"gossisub_duplicate_msg_late_delivery_total",help:"Total count of late duplicate message delivery by topic, which triggers P3 penalty",labelNames:["topic"]}),duplicateMsgIgnored:r.gauge({name:"gossisub_ignored_published_duplicate_msgs_total",help:"Total count of published duplicate message ignored by topic",labelNames:["topic"]}),scoreFnCalls:r.gauge({name:"gossipsub_score_fn_calls_total",help:"Total times score() is called"}),scoreFnRuns:r.gauge({name:"gossipsub_score_fn_runs_total",help:"Total times score() call actually computed computeScore(), no cache"}),scoreCachedDelta:r.histogram({name:"gossipsub_score_cache_delta",help:"Delta of score between cached values that expired",buckets:[10,100,1e3]}),peersByScoreThreshold:r.gauge({name:"gossipsub_peers_by_score_threshold_count",help:"Current count of peers by score threshold",labelNames:["threshold"]}),score:r.avgMinMax({name:"gossipsub_score",help:"Avg min max of gossip scores"}),scoreWeights:r.avgMinMax({name:"gossipsub_score_weights",help:"Separate score weights",labelNames:["topic","p"]}),scorePerMesh:r.avgMinMax({name:"gossipsub_score_per_mesh",help:"Histogram of the scores for each mesh topic",labelNames:["topic"]}),scoringPenalties:r.gauge({name:"gossipsub_scoring_penalties_total",help:"A counter of the kind of penalties being applied to peers",labelNames:["penalty"]}),behaviourPenalty:r.histogram({name:"gossipsub_peer_stat_behaviour_penalty",help:"Current peer stat behaviour_penalty at each scrape",buckets:[.25*t.behaviourPenaltyThreshold,.5*t.behaviourPenaltyThreshold,Number(t.behaviourPenaltyThreshold),2*t.behaviourPenaltyThreshold,4*t.behaviourPenaltyThreshold]}),ihaveRcvIgnored:r.gauge({name:"gossipsub_ihave_rcv_ignored_total",help:"Total received IHAVE messages that we ignore for some reason",labelNames:["reason"]}),ihaveRcvMsgids:r.gauge({name:"gossipsub_ihave_rcv_msgids_total",help:"Total received IHAVE messages by topic",labelNames:["topic"]}),ihaveRcvNotSeenMsgids:r.gauge({name:"gossipsub_ihave_rcv_not_seen_msgids_total",help:"Total messages per topic we do not have, not actual requests",labelNames:["topic"]}),iwantRcvMsgids:r.gauge({name:"gossipsub_iwant_rcv_msgids_total",help:"Total received IWANT messages by topic",labelNames:["topic"]}),iwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_iwant_rcv_dont_have_msgids_total",help:"Total requested messageIDs that we do not have"}),idontwantRcvMsgids:r.gauge({name:"gossipsub_idontwant_rcv_msgids_total",help:"Total received IDONTWANT messages"}),idontwantRcvDonthaveMsgids:r.gauge({name:"gossipsub_idontwant_rcv_dont_have_msgids_total",help:"Total received IDONTWANT messageIDs that we do not have in mcache"}),iwantPromiseStarted:r.gauge({name:"gossipsub_iwant_promise_sent_total",help:"Total count of started IWANT promises"}),iwantPromiseResolved:r.gauge({name:"gossipsub_iwant_promise_resolved_total",help:"Total count of resolved IWANT promises"}),iwantPromiseResolvedFromDuplicate:r.gauge({name:"gossipsub_iwant_promise_resolved_from_duplicate_total",help:"Total count of resolved IWANT promises from duplicate messages"}),iwantPromiseResolvedPeers:r.gauge({name:"gossipsub_iwant_promise_resolved_peers",help:"Total count of peers we have asked IWANT promises that are resolved"}),iwantPromiseBroken:r.gauge({name:"gossipsub_iwant_promise_broken",help:"Total count of broken IWANT promises"}),iwantMessagePruned:r.gauge({name:"gossipsub_iwant_message_pruned",help:"Total count of pruned IWANT messages"}),iwantPromiseDeliveryTime:r.histogram({name:"gossipsub_iwant_promise_delivery_seconds",help:"Histogram of delivery time of resolved IWANT promises",buckets:[.5*t.gossipPromiseExpireSec,Number(t.gossipPromiseExpireSec),2*t.gossipPromiseExpireSec,4*t.gossipPromiseExpireSec]}),iwantPromiseUntracked:r.gauge({name:"gossip_iwant_promise_untracked",help:"Total count of untracked IWANT promise"}),connectedPeersBackoffSec:r.histogram({name:"gossipsub_connected_peers_backoff_seconds",help:"Backoff time in seconds",buckets:[1,2,4,10,20,60,120]}),cacheSize:r.gauge({name:"gossipsub_cache_size",help:"Unbounded cache sizes",labelNames:["cache"]}),mcacheSize:r.gauge({name:"gossipsub_mcache_size",help:"Current mcache msg count"}),mcacheNotValidatedCount:r.gauge({name:"gossipsub_mcache_not_validated_count",help:"Current mcache msg count not validated"}),fastMsgIdCacheCollision:r.gauge({name:"gossipsub_fastmsgid_cache_collision_total",help:"Total count of key collisions on fastmsgid cache put"}),newConnectionCount:r.gauge({name:"gossipsub_new_connection_total",help:"Total new connection by status",labelNames:["status"]}),topicStrToLabel:e,toTopic(s){return this.topicStrToLabel.get(s)??s},onJoin(s){this.topicSubscriptionStatus.set({topicStr:s},1),this.meshPeerCounts.set({topicStr:s},0)},onLeave(s){this.topicSubscriptionStatus.set({topicStr:s},0),this.meshPeerCounts.set({topicStr:s},0)},onAddToMesh(s,n,o){let i=this.toTopic(s);switch(n){case Ft.Fanout:this.meshPeerInclusionEventsFanout.inc({topic:i},o);break;case Ft.Random:this.meshPeerInclusionEventsRandom.inc({topic:i},o);break;case Ft.Subscribed:this.meshPeerInclusionEventsSubscribed.inc({topic:i},o);break;case Ft.Outbound:this.meshPeerInclusionEventsOutbound.inc({topic:i},o);break;case Ft.NotEnough:this.meshPeerInclusionEventsNotEnough.inc({topic:i},o);break;case Ft.Opportunistic:this.meshPeerInclusionEventsOpportunistic.inc({topic:i},o);break;default:this.meshPeerInclusionEventsUnknown.inc({topic:i},o);break}},onRemoveFromMesh(s,n,o){let i=this.toTopic(s);switch(n){case Fr.Dc:this.meshPeerChurnEventsDisconnected.inc({topic:i},o);break;case Fr.BadScore:this.meshPeerChurnEventsBadScore.inc({topic:i},o);break;case Fr.Prune:this.meshPeerChurnEventsPrune.inc({topic:i},o);break;case Fr.Excess:this.meshPeerChurnEventsExcess.inc({topic:i},o);break;default:this.meshPeerChurnEventsUnknown.inc({topic:i},o);break}},onReportValidation(s,n,o){if(this.asyncValidationMcacheHit.inc({hit:s!=null?"hit":"miss"}),s!=null){let i=this.toTopic(s.message.topic);switch(n){case Ot.Accept:this.acceptedMessagesTotal.inc({topic:i});break;case Ot.Ignore:this.ignoredMessagesTotal.inc({topic:i});break;case Ot.Reject:this.rejectedMessagesTotal.inc({topic:i});break;default:this.unknownValidationResultsTotal.inc({topic:i});break}}o!=null?this.asyncValidationDelayFromFirstSeenSec.observe((Date.now()-o)/1e3):this.asyncValidationUnknownFirstSeen.inc()},onScorePenalty(s){this.scoringPenalties.inc({penalty:s},1)},onIhaveRcv(s,n,o){let i=this.toTopic(s);this.ihaveRcvMsgids.inc({topic:i},n),this.ihaveRcvNotSeenMsgids.inc({topic:i},o)},onIwantRcv(s,n){for(let[o,i]of s){let a=this.toTopic(o);this.iwantRcvMsgids.inc({topic:a},i)}this.iwantRcvDonthaveMsgids.inc(n)},onIdontwantRcv(s,n){this.idontwantRcvMsgids.inc(s),this.idontwantRcvDonthaveMsgids.inc(n)},onForwardMsg(s,n){let o=this.toTopic(s);this.msgForwardCount.inc({topic:o},1),this.msgForwardPeers.inc({topic:o},n)},onPublishMsg(s,n,o,i,a){let c=this.toTopic(s);this.msgPublishCount.inc({topic:c},1),this.msgPublishBytes.inc({topic:c},o*i),this.msgPublishPeersByTopic.inc({topic:c},o),this.directPeersPublishedTotal.inc({topic:c},n.direct),this.floodsubPeersPublishedTotal.inc({topic:c},n.floodsub),this.meshPeersPublishedTotal.inc({topic:c},n.mesh),this.fanoutPeersPublishedTotal.inc({topic:c},n.fanout),this.msgPublishTime.observe({topic:c},a/1e3)},onMsgRecvPreValidation(s){let n=this.toTopic(s);this.msgReceivedPreValidation.inc({topic:n},1)},onMsgRecvError(s){let n=this.toTopic(s);this.msgReceivedError.inc({topic:n},1)},onPrevalidationResult(s,n){let o=this.toTopic(s);switch(n){case kt.duplicate:this.prevalidationDuplicateTotal.inc({topic:o});break;case kt.invalid:this.prevalidationInvalidTotal.inc({topic:o});break;case kt.valid:this.prevalidationValidTotal.inc({topic:o});break;default:this.prevalidationUnknownTotal.inc({topic:o});break}},onMsgRecvInvalid(s,n){let o=this.toTopic(s),i=n.reason===Bt.Error?n.error:n.reason;this.msgReceivedInvalid.inc({error:i},1),this.msgReceivedInvalidByTopic.inc({topic:o},1)},onDuplicateMsgDelivery(s,n,o){let i=this.toTopic(s);this.duplicateMsgDeliveryDelay.observe({topic:i},n/1e3),o&&this.duplicateMsgLateDelivery.inc({topic:i},1)},onPublishDuplicateMsg(s){let n=this.toTopic(s);this.duplicateMsgIgnored.inc({topic:n},1)},onPeerReadStreamError(){this.peerReadStreamError.inc(1)},onRpcRecvError(){this.rpcRecvError.inc(1)},onRpcDataError(){this.rpcDataError.inc(1)},onRpcRecv(s,n){this.rpcRecvBytes.inc(n),this.rpcRecvCount.inc(1),s.subscriptions!=null&&this.rpcRecvSubscription.inc(s.subscriptions.length),s.messages!=null&&this.rpcRecvMessage.inc(s.messages.length),s.control!=null&&(this.rpcRecvControl.inc(1),s.control.ihave!=null&&this.rpcRecvIHave.inc(s.control.ihave.length),s.control.iwant!=null&&this.rpcRecvIWant.inc(s.control.iwant.length),s.control.graft!=null&&this.rpcRecvGraft.inc(s.control.graft.length),s.control.prune!=null&&this.rpcRecvPrune.inc(s.control.prune.length))},onRpcSent(s,n){if(this.rpcSentBytes.inc(n),this.rpcSentCount.inc(1),s.subscriptions!=null&&this.rpcSentSubscription.inc(s.subscriptions.length),s.messages!=null&&this.rpcSentMessage.inc(s.messages.length),s.control!=null){let o=s.control.ihave?.length??0,i=s.control.iwant?.length??0,a=s.control.graft?.length??0,c=s.control.prune?.length??0,l=s.control.idontwant?.length??0;o>0&&this.rpcSentIHave.inc(o),i>0&&this.rpcSentIWant.inc(i),a>0&&this.rpcSentGraft.inc(a),c>0&&this.rpcSentPrune.inc(c),l>0&&this.rpcSentIDontWant.inc(l),(o>0||i>0||a>0||c>0||l>0)&&this.rpcSentControl.inc(1)}},registerScores(s,n){let o=0,i=0,a=0,c=0;for(let l of s)l>=n.graylistThreshold&&o++,l>=n.publishThreshold&&i++,l>=n.gossipThreshold&&a++,l>=0&&c++;this.peersByScoreThreshold.set({threshold:ji.graylist},o),this.peersByScoreThreshold.set({threshold:ji.publish},i),this.peersByScoreThreshold.set({threshold:ji.gossip},a),this.peersByScoreThreshold.set({threshold:ji.mesh},c),this.score.set(s)},registerScoreWeights(s){for(let[n,o]of s.byTopic)this.scoreWeights.set({topic:n,p:"p1"},o.p1w),this.scoreWeights.set({topic:n,p:"p2"},o.p2w),this.scoreWeights.set({topic:n,p:"p3"},o.p3w),this.scoreWeights.set({topic:n,p:"p3b"},o.p3bw),this.scoreWeights.set({topic:n,p:"p4"},o.p4w);this.scoreWeights.set({p:"p5"},s.p5w),this.scoreWeights.set({p:"p6"},s.p6w),this.scoreWeights.set({p:"p7"},s.p7w)},registerScorePerMesh(s,n){let o=new Map;s.forEach((i,a)=>{let c=this.topicStrToLabel.get(a)??"unknown",l=o.get(c);l==null&&(l=new Set,o.set(c,l)),i.forEach(u=>l?.add(u))});for(let[i,a]of o){let c=[];a.forEach(l=>{c.push(n.get(l)??0)}),this.scorePerMesh.set({topic:i},c)}}}}var be=class extends Error{static name="InvalidPeerScoreParamsError";constructor(e="Invalid peer score params"){super(e),this.name="InvalidPeerScoreParamsError"}};var KP={topics:{},topicScoreCap:10,appSpecificScore:()=>0,appSpecificWeight:10,IPColocationFactorWeight:-5,IPColocationFactorThreshold:10,IPColocationFactorWhitelist:new Set,behaviourPenaltyWeight:-10,behaviourPenaltyThreshold:0,behaviourPenaltyDecay:.2,decayInterval:1e3,decayToZero:.1,retainScore:3600*1e3},HP={topicWeight:.5,timeInMeshWeight:1,timeInMeshQuantum:1,timeInMeshCap:3600,firstMessageDeliveriesWeight:1,firstMessageDeliveriesDecay:.5,firstMessageDeliveriesCap:2e3,meshMessageDeliveriesWeight:-1,meshMessageDeliveriesDecay:.5,meshMessageDeliveriesCap:100,meshMessageDeliveriesThreshold:20,meshMessageDeliveriesWindow:10,meshMessageDeliveriesActivation:5e3,meshFailurePenaltyWeight:-1,meshFailurePenaltyDecay:.5,invalidMessageDeliveriesWeight:-1,invalidMessageDeliveriesDecay:.3};function Cv(r={}){return{...KP,...r,topics:r.topics!=null?Object.entries(r.topics).reduce((e,[t,s])=>(e[t]=zP(s),e),{}):{}}}function zP(r={}){return{...HP,...r}}function Tv(r){for(let[e,t]of Object.entries(r.topics))try{qP(t)}catch(s){throw new be(`invalid score parameters for topic ${e}: ${s.message}`)}if(r.topicScoreCap<0)throw new be("invalid topic score cap; must be positive (or 0 for no cap)");if(r.appSpecificScore===null||r.appSpecificScore===void 0)throw new be("missing application specific score function");if(r.IPColocationFactorWeight>0)throw new be("invalid IPColocationFactorWeight; must be negative (or 0 to disable)");if(r.IPColocationFactorWeight!==0&&r.IPColocationFactorThreshold<1)throw new be("invalid IPColocationFactorThreshold; must be at least 1");if(r.behaviourPenaltyWeight>0)throw new be("invalid BehaviourPenaltyWeight; must be negative (or 0 to disable)");if(r.behaviourPenaltyWeight!==0&&(r.behaviourPenaltyDecay<=0||r.behaviourPenaltyDecay>=1))throw new be("invalid BehaviourPenaltyDecay; must be between 0 and 1");if(r.decayInterval<1e3)throw new be("invalid DecayInterval; must be at least 1s");if(r.decayToZero<=0||r.decayToZero>=1)throw new be("invalid DecayToZero; must be between 0 and 1")}function qP(r){if(r.topicWeight<0)throw new be("invalid topic weight; must be >= 0");if(r.timeInMeshQuantum===0)throw new be("invalid TimeInMeshQuantum; must be non zero");if(r.timeInMeshWeight<0)throw new be("invalid TimeInMeshWeight; must be positive (or 0 to disable)");if(r.timeInMeshWeight!==0&&r.timeInMeshQuantum<=0)throw new be("invalid TimeInMeshQuantum; must be positive");if(r.timeInMeshWeight!==0&&r.timeInMeshCap<=0)throw new be("invalid TimeInMeshCap; must be positive");if(r.firstMessageDeliveriesWeight<0)throw new be("invallid FirstMessageDeliveriesWeight; must be positive (or 0 to disable)");if(r.firstMessageDeliveriesWeight!==0&&(r.firstMessageDeliveriesDecay<=0||r.firstMessageDeliveriesDecay>=1))throw new be("invalid FirstMessageDeliveriesDecay; must be between 0 and 1");if(r.firstMessageDeliveriesWeight!==0&&r.firstMessageDeliveriesCap<=0)throw new be("invalid FirstMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight>0)throw new be("invalid MeshMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.meshMessageDeliveriesWeight!==0&&(r.meshMessageDeliveriesDecay<=0||r.meshMessageDeliveriesDecay>=1))throw new be("invalid MeshMessageDeliveriesDecay; must be between 0 and 1");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesCap<=0)throw new be("invalid MeshMessageDeliveriesCap; must be positive");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesThreshold<=0)throw new be("invalid MeshMessageDeliveriesThreshold; must be positive");if(r.meshMessageDeliveriesWindow<0)throw new be("invalid MeshMessageDeliveriesWindow; must be non-negative");if(r.meshMessageDeliveriesWeight!==0&&r.meshMessageDeliveriesActivation<1e3)throw new be("invalid MeshMessageDeliveriesActivation; must be at least 1s");if(r.meshFailurePenaltyWeight>0)throw new be("invalid MeshFailurePenaltyWeight; must be negative (or 0 to disable)");if(r.meshFailurePenaltyWeight!==0&&(r.meshFailurePenaltyDecay<=0||r.meshFailurePenaltyDecay>=1))throw new be("invalid MeshFailurePenaltyDecay; must be between 0 and 1");if(r.invalidMessageDeliveriesWeight>0)throw new be("invalid InvalidMessageDeliveriesWeight; must be negative (or 0 to disable)");if(r.invalidMessageDeliveriesDecay<=0||r.invalidMessageDeliveriesDecay>=1)throw new be("invalid InvalidMessageDeliveriesDecay; must be between 0 and 1")}var $P={gossipThreshold:-10,publishThreshold:-50,graylistThreshold:-80,acceptPXThreshold:10,opportunisticGraftThreshold:20};function Pv(r={}){return{...$P,...r}}function Qh(r,e,t=()=>!0){let s=new Set;if(e<=0)return s;for(let n of r){if(s.size>=e)break;t(n)&&(s.add(n),r.delete(n))}return s}function kv(r,e){return Qh(r,e,()=>!0)}var Zh=class extends Map{getDefault;constructor(e){super(),this.getDefault=e}getOrDefault(e){let t=super.get(e);return t===void 0&&(t=this.getDefault(),this.set(e,t)),t}};function Dv(r,e,t,s){let n=0;Object.entries(e.topics).forEach(([i,a])=>{let c=t.topics[i];if(c===void 0)return;let l=0;if(a.inMesh){let f=a.meshTime/c.timeInMeshQuantum;f>c.timeInMeshCap&&(f=c.timeInMeshCap),l+=f*c.timeInMeshWeight}let u=a.firstMessageDeliveries;if(u>c.firstMessageDeliveriesCap&&(u=c.firstMessageDeliveriesCap),l+=u*c.firstMessageDeliveriesWeight,a.meshMessageDeliveriesActive&&a.meshMessageDeliveries<c.meshMessageDeliveriesThreshold){let f=c.meshMessageDeliveriesThreshold-a.meshMessageDeliveries,p=f*f;l+=p*c.meshMessageDeliveriesWeight}let h=a.meshFailurePenalty;l+=h*c.meshFailurePenaltyWeight;let d=a.invalidMessageDeliveries*a.invalidMessageDeliveries;l+=d*c.invalidMessageDeliveriesWeight,n+=l*c.topicWeight}),t.topicScoreCap>0&&n>t.topicScoreCap&&(n=t.topicScoreCap);let o=t.appSpecificScore(r);if(n+=o*t.appSpecificWeight,e.knownIPs.forEach(i=>{if(t.IPColocationFactorWhitelist.has(i))return;let a=s.get(i),c=a!=null?a.size:0;if(c>t.IPColocationFactorThreshold){let l=c-t.IPColocationFactorThreshold,u=l*l;n+=u*t.IPColocationFactorWeight}}),e.behaviourPenalty>t.behaviourPenaltyThreshold){let i=e.behaviourPenalty-t.behaviourPenaltyThreshold,a=i*i;n+=a*t.behaviourPenaltyWeight}return n}var Lv=we(Ov(),1);var Ut;(function(r){r[r.unknown=0]="unknown",r[r.valid=1]="valid",r[r.invalid=2]="invalid",r[r.ignored=3]="ignored"})(Ut||(Ut={}));var Jh=class{records;queue;constructor(){this.records=new Map,this.queue=new Lv.default}getRecord(e){return this.records.get(e)}ensureRecord(e){let t=this.records.get(e);if(t!=null)return t;t={status:Ut.unknown,firstSeenTsMs:Date.now(),validated:0,peers:new Set},this.records.set(e,t);let s={msgId:e,expire:Date.now()+12e4};return this.queue.push(s),t}gc(){let e=Date.now(),t=this.queue.peekFront();for(;t!=null&&t.expire<e;)this.records.delete(t.msgId),this.queue.shift(),t=this.queue.peekFront()}clear(){this.records.clear(),this.queue.clear()}};var ed=class{params;metrics;peerStats=new Map;peerIPs=new Zh(()=>new Set);scoreCache=new Map;deliveryRecords=new Jh;_backgroundInterval;scoreCacheValidityMs;computeScore;log;constructor(e,t,s,n){this.params=e,this.metrics=t,Tv(e),this.scoreCacheValidityMs=n.scoreCacheValidityMs,this.computeScore=n.computeScore??Dv,this.log=s.forComponent("libp2p:gossipsub:score")}get size(){return this.peerStats.size}start(){if(this._backgroundInterval!=null){this.log("Peer score already running");return}this._backgroundInterval=setInterval(()=>{this.background()},this.params.decayInterval),this.log("started")}stop(){if(this._backgroundInterval==null){this.log("Peer score already stopped");return}clearInterval(this._backgroundInterval),delete this._backgroundInterval,this.peerIPs.clear(),this.peerStats.clear(),this.deliveryRecords.clear(),this.log("stopped")}background(){this.refreshScores(),this.deliveryRecords.gc()}dumpPeerScoreStats(){return Object.fromEntries(Array.from(this.peerStats.entries()).map(([e,t])=>[e,t]))}messageFirstSeenTimestampMs(e){let t=this.deliveryRecords.getRecord(e);return t!=null?t.firstSeenTsMs:null}refreshScores(){let e=Date.now(),t=this.params.decayToZero;this.peerStats.forEach((s,n)=>{if(!s.connected){e>s.expire&&(this.removeIPsForPeer(n,s.knownIPs),this.peerStats.delete(n),this.scoreCache.delete(n));return}Object.entries(s.topics).forEach(([o,i])=>{let a=this.params.topics[o];a!==void 0&&(i.firstMessageDeliveries*=a.firstMessageDeliveriesDecay,i.firstMessageDeliveries<t&&(i.firstMessageDeliveries=0),i.meshMessageDeliveries*=a.meshMessageDeliveriesDecay,i.meshMessageDeliveries<t&&(i.meshMessageDeliveries=0),i.meshFailurePenalty*=a.meshFailurePenaltyDecay,i.meshFailurePenalty<t&&(i.meshFailurePenalty=0),i.invalidMessageDeliveries*=a.invalidMessageDeliveriesDecay,i.invalidMessageDeliveries<t&&(i.invalidMessageDeliveries=0),i.inMesh&&(i.meshTime=e-i.graftTime,i.meshTime>a.meshMessageDeliveriesActivation&&(i.meshMessageDeliveriesActive=!0)))}),s.behaviourPenalty*=this.params.behaviourPenaltyDecay,s.behaviourPenalty<t&&(s.behaviourPenalty=0)})}score(e){this.metrics?.scoreFnCalls.inc();let t=this.peerStats.get(e);if(t==null)return 0;let s=Date.now(),n=this.scoreCache.get(e);if(n!=null&&n.cacheUntil>s)return n.score;this.metrics?.scoreFnRuns.inc();let o=this.computeScore(e,t,this.params,this.peerIPs),i=s+this.scoreCacheValidityMs;return n!=null?(this.metrics?.scoreCachedDelta.observe(Math.abs(o-n.score)),n.score=o,n.cacheUntil=i):this.scoreCache.set(e,{score:o,cacheUntil:i}),o}addPenalty(e,t,s){let n=this.peerStats.get(e);n!=null&&(n.behaviourPenalty+=t,this.metrics?.onScorePenalty(s))}addPeer(e){let t={connected:!0,expire:0,topics:{},knownIPs:new Set,behaviourPenalty:0};this.peerStats.set(e,t)}addIP(e,t){let s=this.peerStats.get(e);s?.knownIPs.add(t),this.peerIPs.getOrDefault(t).add(e)}removeIP(e,t){let s=this.peerStats.get(e);s?.knownIPs.delete(t);let n=this.peerIPs.get(t);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(t))}removePeer(e){let t=this.peerStats.get(e);if(t!=null){if(this.score(e)>0){this.removeIPsForPeer(e,t.knownIPs),this.peerStats.delete(e);return}Object.entries(t.topics).forEach(([s,n])=>{n.firstMessageDeliveries=0;let o=this.params.topics[s].meshMessageDeliveriesThreshold;if(n.inMesh&&n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<o){let i=o-n.meshMessageDeliveries;n.meshFailurePenalty+=i*i}n.inMesh=!1,n.meshMessageDeliveriesActive=!1}),t.connected=!1,t.expire=Date.now()+this.params.retainScore}}graft(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);n!=null&&(n.inMesh=!0,n.graftTime=Date.now(),n.meshTime=0,n.meshMessageDeliveriesActive=!1)}}prune(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);if(n!=null){let o=this.params.topics[t].meshMessageDeliveriesThreshold;if(n.meshMessageDeliveriesActive&&n.meshMessageDeliveries<o){let i=o-n.meshMessageDeliveries;n.meshFailurePenalty+=i*i}n.meshMessageDeliveriesActive=!1,n.inMesh=!1}}}validateMessage(e){this.deliveryRecords.ensureRecord(e)}deliverMessage(e,t,s){this.markFirstMessageDelivery(e,s);let n=this.deliveryRecords.ensureRecord(t),o=Date.now();if(n.status!==Ut.unknown){this.log("unexpected delivery: message from %s was first seen %s ago and has delivery status %s",e,o-n.firstSeenTsMs,Ut[n.status]);return}n.status=Ut.valid,n.validated=o,n.peers.forEach(i=>{i!==e.toString()&&this.markDuplicateMessageDelivery(i,s)})}rejectInvalidMessage(e,t){this.markInvalidMessageDelivery(e,t)}rejectMessage(e,t,s,n){switch(n){case Bt.Error:this.markInvalidMessageDelivery(e,s);return;case Bt.Blacklisted:return}let o=this.deliveryRecords.ensureRecord(t);if(o.status!==Ut.unknown){this.log("unexpected rejection: message from %s was first seen %s ago and has delivery status %d",e,Date.now()-o.firstSeenTsMs,Ut[o.status]);return}if(n===Bt.Ignore){o.status=Ut.ignored,o.peers.clear();return}o.status=Ut.invalid,this.markInvalidMessageDelivery(e,s),o.peers.forEach(i=>{this.markInvalidMessageDelivery(i,s)}),o.peers.clear()}duplicateMessage(e,t,s){let n=this.deliveryRecords.ensureRecord(t);if(!n.peers.has(e))switch(n.status){case Ut.unknown:n.peers.add(e);break;case Ut.valid:n.peers.add(e),this.markDuplicateMessageDelivery(e,s,n.validated);break;case Ut.invalid:this.markInvalidMessageDelivery(e,s);break;case Ut.ignored:break}}markInvalidMessageDelivery(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);n!=null&&(n.invalidMessageDeliveries+=1)}}markFirstMessageDelivery(e,t){let s=this.peerStats.get(e);if(s!=null){let n=this.getPtopicStats(s,t);if(n!=null){let o=this.params.topics[t].firstMessageDeliveriesCap;n.firstMessageDeliveries=Math.min(o,n.firstMessageDeliveries+1),n.inMesh&&(o=this.params.topics[t].meshMessageDeliveriesCap,n.meshMessageDeliveries=Math.min(o,n.meshMessageDeliveries+1))}}}markDuplicateMessageDelivery(e,t,s){let n=this.peerStats.get(e);if(n!=null){let o=s!==void 0?Date.now():0,i=this.getPtopicStats(n,t);if(i!=null&&i.inMesh){let a=this.params.topics[t];if(s!==void 0){let l=o-s,u=l>a.meshMessageDeliveriesWindow;if(this.metrics?.onDuplicateMsgDelivery(t,l,u),u)return}let c=a.meshMessageDeliveriesCap;i.meshMessageDeliveries=Math.min(c,i.meshMessageDeliveries+1)}}}removeIPsForPeer(e,t){for(let s of t){let n=this.peerIPs.get(s);n!=null&&(n.delete(e),n.size===0&&this.peerIPs.delete(s))}}getPtopicStats(e,t){let s=e.topics[t];return s!==void 0?s:this.params.topics[t]!==void 0?(s={inMesh:!1,graftTime:0,meshTime:0,firstMessageDeliveries:0,meshMessageDeliveries:0,meshMessageDeliveriesActive:!1,meshFailurePenalty:0,invalidMessageDeliveries:0},e.topics[t]=s,s):null}};function GP(r,e,t,s,n){let o=0,i=new Map;if(Object.entries(e.topics).forEach(([d,f])=>{let p=n.get(d)??"unknown",m=t.topics[d];if(m===void 0)return;let g=i.get(p);g==null&&(g={p1w:0,p2w:0,p3w:0,p3bw:0,p4w:0},i.set(p,g));let y=0,w=0,b=0,x=0,E=0;if(f.inMesh){let v=Math.max(f.meshTime/m.timeInMeshQuantum,m.timeInMeshCap);y+=v*m.timeInMeshWeight}let P=f.firstMessageDeliveries;if(P>m.firstMessageDeliveriesCap&&(P=m.firstMessageDeliveriesCap),w+=P*m.firstMessageDeliveriesWeight,f.meshMessageDeliveriesActive&&f.meshMessageDeliveries<m.meshMessageDeliveriesThreshold){let v=m.meshMessageDeliveriesThreshold-f.meshMessageDeliveries,M=v*v;b+=M*m.meshMessageDeliveriesWeight}let T=f.meshFailurePenalty;x+=T*m.meshFailurePenaltyWeight;let D=f.invalidMessageDeliveries*f.invalidMessageDeliveries;E+=D*m.invalidMessageDeliveriesWeight,o+=(y+w+b+x+E)*m.topicWeight,g.p1w+=y,g.p2w+=w,g.p3w+=b,g.p3bw+=x,g.p4w+=E}),t.topicScoreCap>0&&o>t.topicScoreCap){o=t.topicScoreCap;let d=t.topicScoreCap/o;for(let f of i.values())f.p1w*=d,f.p2w*=d,f.p3w*=d,f.p3bw*=d,f.p4w*=d}let a=0,c=0,l=0,u=t.appSpecificScore(r);a+=u*t.appSpecificWeight,e.knownIPs.forEach(d=>{if(t.IPColocationFactorWhitelist.has(d))return;let f=s.get(d),p=f!=null?f.size:0;if(p>t.IPColocationFactorThreshold){let m=p-t.IPColocationFactorThreshold,g=m*m;c+=g*t.IPColocationFactorWeight}});let h=e.behaviourPenalty*e.behaviourPenalty;return l+=h*t.behaviourPenaltyWeight,o+=a+c+l,{byTopic:i,p5w:a,p6w:c,p7w:l,score:o}}function Rv(r,e,t,s,n){let o={byTopic:new Map,p5w:[],p6w:[],p7w:[],score:[]};for(let i of r){let a=e.get(i);if(a!=null){let c=GP(i,a,t,s,n);for(let[l,u]of c.byTopic){let h=o.byTopic.get(l);h==null&&(h={p1w:[],p2w:[],p3w:[],p3bw:[],p4w:[]},o.byTopic.set(l,h)),h.p1w.push(u.p1w),h.p2w.push(u.p2w),h.p3w.push(u.p3w),h.p3bw.push(u.p3bw),h.p4w.push(u.p4w)}o.p5w.push(c.p5w),o.p6w.push(c.p6w),o.p7w.push(c.p7w),o.score.push(c.score)}else o.p5w.push(0),o.p6w.push(0),o.p7w.push(0),o.score.push(0)}return o}var td=class{rawStream;pushable;closeController;maxBufferSize;constructor(e,t,s){this.rawStream=e,this.pushable=dt(),this.closeController=new AbortController,this.maxBufferSize=s.maxBufferSize??1/0,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(n=>{e.abort(n)})}),st(this.pushable,this.rawStream).catch(t)}get protocol(){return this.rawStream.protocol}push(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(Wi.single(e))}pushPrefixed(e){if(this.pushable.readableLength>this.maxBufferSize)throw Error(`OutboundStream buffer full, size > ${this.maxBufferSize}`);this.pushable.push(e)}async close(){this.closeController.abort(),await this.pushable.return()}},rd=class{source;rawStream;closeController;constructor(e,t={}){this.rawStream=e,this.closeController=new AbortController,this.closeController.signal.addEventListener("abort",()=>{e.close().catch(s=>{e.abort(s)})}),this.source=st(this.rawStream,s=>Yc(s,t))}async close(){this.closeController.abort()}};var sd=class{gossipsubIWantFollowupMs;msgIdToStrFn;metrics;promises=new Map;requestMsByMsg=new Map;requestMsByMsgExpire;constructor(e,t,s){this.gossipsubIWantFollowupMs=e,this.msgIdToStrFn=t,this.metrics=s,this.requestMsByMsgExpire=10*e}get size(){return this.promises.size}get requestMsByMsgSize(){return this.requestMsByMsg.size}addPromise(e,t){let s=Math.floor(Math.random()*t.length),n=t[s],o=this.msgIdToStrFn(n),i=this.promises.get(o);i==null&&(i=new Map,this.promises.set(o,i));let a=Date.now();i.has(e)||(i.set(e,a+this.gossipsubIWantFollowupMs),this.metrics!=null&&(this.metrics.iwantPromiseStarted.inc(1),this.requestMsByMsg.has(o)||this.requestMsByMsg.set(o,a)))}getBrokenPromises(){let e=Date.now(),t=new Map,s=0;return this.promises.forEach((n,o)=>{n.forEach((i,a)=>{i<e&&(t.set(a,(t.get(a)??0)+1),n.delete(a),s++)}),n.size===0&&this.promises.delete(o)}),this.metrics?.iwantPromiseBroken.inc(s),t}deliverMessage(e,t=!1){this.trackMessage(e);let s=this.promises.get(e);s!=null&&(this.promises.delete(e),this.metrics!=null&&(this.metrics.iwantPromiseResolved.inc(1),t&&this.metrics.iwantPromiseResolvedFromDuplicate.inc(1),this.metrics.iwantPromiseResolvedPeers.inc(s.size)))}rejectMessage(e,t){switch(this.trackMessage(e),t){case Bt.Error:return;default:break}this.promises.delete(e)}clear(){this.promises.clear()}prune(){let e=Date.now()-this.requestMsByMsgExpire,t=0;for(let[s,n]of this.requestMsByMsg.entries())if(n<e)this.requestMsByMsg.delete(s),t++;else break;this.metrics?.iwantMessagePruned.inc(t)}trackMessage(e){if(this.metrics!=null){let t=this.requestMsByMsg.get(e);t!==void 0&&(this.metrics.iwantPromiseDeliveryTime.observe((Date.now()-t)/1e3),this.requestMsByMsg.delete(e))}}};ft();X();ce();ir();Kr();ge();Se();var Nv=L("libp2p-pubsub:");async function Bv(r,e,t,s){switch(r.type){case un.Signing:{let n={from:r.author.toMultihash().bytes,data:s,seqno:Gr(8),topic:e,signature:void 0,key:void 0},o=Ye([Nv,Ns.Message.encode(n)]);n.signature=await r.privateKey.sign(o),n.key=r.key;let i={type:"signed",from:r.author,data:t,sequenceNumber:BigInt(`0x${K(n.seqno??new Uint8Array(0),"base16")}`),topic:e,signature:n.signature,key:Je(n.key)};return{raw:n,msg:i}}case un.Anonymous:return{raw:{from:void 0,data:s,seqno:void 0,topic:e,signature:void 0,key:void 0},msg:{type:"unsigned",data:t,topic:e}};default:throw new Error("Unreachable")}}async function Fv(r,e){switch(r){case jo:return e.signature!=null?{valid:!1,error:Pt.SignaturePresent}:e.seqno!=null?{valid:!1,error:Pt.SeqnoPresent}:e.from!=null?{valid:!1,error:Pt.FromPresent}:{valid:!0,message:{type:"unsigned",topic:e.topic,data:e.data??new Uint8Array(0)}};case In:{if(e.seqno==null)return{valid:!1,error:Pt.InvalidSeqno};if(e.seqno.length!==8)return{valid:!1,error:Pt.InvalidSeqno};if(e.signature==null)return{valid:!1,error:Pt.InvalidSignature};if(e.from==null)return{valid:!1,error:Pt.InvalidPeerId};let t;try{t=Pr(Ht(e.from))}catch{return{valid:!1,error:Pt.InvalidPeerId}}let s;if(e.key!=null){if(s=Je(e.key),t.publicKey!==void 0&&!s.equals(t.publicKey))return{valid:!1,error:Pt.InvalidPeerId}}else{if(t.publicKey==null)return{valid:!1,error:Pt.InvalidPeerId};s=t.publicKey}let n={from:e.from,data:e.data,seqno:e.seqno,topic:e.topic,signature:void 0,key:void 0},o=Ye([Nv,Ns.Message.encode(n)]);return await s.verify(o,e.signature)?{valid:!0,message:{type:"signed",from:t,data:e.data??new Uint8Array(0),sequenceNumber:BigInt(`0x${K(e.seqno,"base16")}`),topic:e.topic,signature:e.signature,key:s}}:{valid:!1,error:Pt.InvalidSignature}}default:throw new Error("Unreachable")}}function Ur(r=[],e){return{subscriptions:[],messages:r,control:e!==void 0?{graft:e.graft??[],prune:e.prune??[],ihave:e.ihave??[],iwant:e.iwant??[],idontwant:e.idontwant??[]}:void 0}}function ig(r){return r.control===void 0&&(r.control={graft:[],prune:[],ihave:[],iwant:[],idontwant:[]}),r}function is(r){if(r.length<=1)return r;let e=()=>Math.floor(Math.random()*Math.floor(r.length));for(let t=0;t<r.length;t++){let s=e(),n=r[t];r[t]=r[s],r[s]=n}return r}Se();function Uv(r){return K(r,"base64")}ft();X();function Kv(r,e,t){switch(r){case In:return{type:un.Signing,author:e,key:Ve(t.publicKey),privateKey:t};case jo:return{type:un.Anonymous};default:throw new Error(`Unknown signature policy "${r}"`)}}ft();ir();us();ge();Se();var Hv=(r,e)=>{let t=L(e.toString(16).padStart(16,"0"),"base16"),s=Ve(r),n=new Uint8Array(s.byteLength+t.length);return n.set(s,0),n.set(t,s.byteLength),n};us();function zv(r){if(r.type!=="signed")throw new Error("expected signed message type");if(r.sequenceNumber==null)throw Error("missing seqno field");return Hv(r.from.publicKey??r.key,r.sequenceNumber)}async function qv(r){return Qe.encode(r.data)}var nd;(function(r){r[r.ip4=4]="ip4",r[r.ip6=41]="ip6"})(nd||(nd={}));function $v(r){for(let e of r.tuples())switch(e[0]){case nd.ip4:case nd.ip6:return h4(e[0],e[1]);default:break}return null}var Zi=class{entries=new Map;validityMs;constructor(e){this.validityMs=e.validityMs}get size(){return this.entries.size}put(e,t){return this.entries.has(e)?!0:(this.entries.set(e,{value:t,validUntilMs:Date.now()+this.validityMs}),!1)}prune(){let e=Date.now();for(let[t,s]of this.entries.entries())if(s.validUntilMs<e)this.entries.delete(t);else break}has(e){return this.entries.has(e)}get(e){let t=this.entries.get(e);return t!=null&&t.validUntilMs>=Date.now()?t.value:void 0}clear(){this.entries.clear()}};var tr;(function(r){r[r.started=0]="started",r[r.stopped=1]="stopped"})(tr||(tr={}));var ag=class extends Xe{globalSignaturePolicy;multicodecs=[Yh,xv,ng];publishConfig;dataTransform;peers=new Map;streamsInbound=new Map;streamsOutbound=new Map;outboundInflightQueue=dt({objectMode:!0});direct=new Set;floodsubPeers=new Set;seenCache;acceptFromWhitelist=new Map;topics=new Map;subscriptions=new Set;mesh=new Map;fanout=new Map;fanoutLastpub=new Map;gossip=new Map;control=new Map;peerhave=new Map;iasked=new Map;backoff=new Map;outbound=new Map;msgIdFn;fastMsgIdFn;msgIdToStrFn;fastMsgIdCache;publishedMessageIds;mcache;score;topicValidators=new Map;log;heartbeatTicks=0;gossipTracer;idontwantCounts=new Map;idontwants=new Map;components;directPeerInitial=null;static multicodec=Yh;opts;decodeRpcLimits;metrics;status={code:tr.stopped};maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;allowedTopics;heartbeatTimer=null;constructor(e,t={}){super();let s={fallbackToFloodsub:!0,floodPublish:!0,batchPublish:!1,tagMeshPeers:!0,doPX:!1,directPeers:[],D:6,Dlo:4,Dhi:12,Dscore:4,Dout:2,Dlazy:6,heartbeatInterval:1e3,fanoutTTL:6e4,mcacheLength:5,mcacheGossip:3,seenTTL:12e4,gossipsubIWantFollowupMs:3e3,prunePeers:16,pruneBackoff:6e4,unsubcribeBackoff:1e4,graftFloodThreshold:1e4,opportunisticGraftPeers:2,opportunisticGraftTicks:60,directConnectTicks:300,gossipFactor:.25,idontwantMinDataSize:512,idontwantMaxMessages:512,...t,scoreParams:Cv(t.scoreParams),scoreThresholds:Pv(t.scoreThresholds)};if(this.components=e,this.decodeRpcLimits=s.decodeRpcLimits??Sv,this.globalSignaturePolicy=s.globalSignaturePolicy??In,s.fallbackToFloodsub&&this.multicodecs.push(sg),this.log=e.logger.forComponent(s.debugName??"libp2p:gossipsub"),this.opts=s,this.direct=new Set(s.directPeers.map(n=>n.id.toString())),this.seenCache=new Zi({validityMs:s.seenTTL}),this.publishedMessageIds=new Zi({validityMs:s.seenTTL}),t.msgIdFn!=null)this.msgIdFn=t.msgIdFn;else switch(this.globalSignaturePolicy){case In:this.msgIdFn=zv;break;case jo:this.msgIdFn=qv;break;default:throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)}if(t.fastMsgIdFn!=null&&(this.fastMsgIdFn=t.fastMsgIdFn,this.fastMsgIdCache=new Zi({validityMs:s.seenTTL})),this.msgIdToStrFn=t.msgIdToStrFn??Uv,this.mcache=t.messageCache??new Xh(s.mcacheGossip,s.mcacheLength,this.msgIdToStrFn),t.dataTransform!=null&&(this.dataTransform=t.dataTransform),t.metricsRegister!=null){if(t.metricsTopicStrToLabel==null)throw Error("Must set metricsTopicStrToLabel with metrics");let n=Math.max(...Object.values(s.scoreParams.topics).map(i=>i.meshMessageDeliveriesWindow),1e3),o=Av(t.metricsRegister,t.metricsTopicStrToLabel,{gossipPromiseExpireSec:this.opts.gossipsubIWantFollowupMs/1e3,behaviourPenaltyThreshold:s.scoreParams.behaviourPenaltyThreshold,maxMeshMessageDeliveriesWindowSec:n/1e3});o.mcacheSize.addCollect(()=>{this.onScrapeMetrics(o)});for(let i of this.multicodecs)o.protocolsEnabled.set({protocol:i},1);this.metrics=o}else this.metrics=null;this.gossipTracer=new sd(this.opts.gossipsubIWantFollowupMs,this.msgIdToStrFn,this.metrics),this.score=new ed(this.opts.scoreParams,this.metrics,this.components.logger,{scoreCacheValidityMs:s.heartbeatInterval}),this.maxInboundStreams=t.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams,this.runOnLimitedConnection=t.runOnLimitedConnection,this.allowedTopics=s.allowedTopics!=null?new Set(s.allowedTopics):null}[Symbol.toStringTag]="@chainsafe/libp2p-gossipsub";[et]=["@libp2p/pubsub"];[ka]=["@libp2p/identify"];getPeers(){return[...this.peers.values()]}isStarted(){return this.status.code===tr.started}async start(){if(this.isStarted())return;this.log("starting"),this.publishConfig=Kv(this.globalSignaturePolicy,this.components.peerId,this.components.privateKey),this.outboundInflightQueue=dt({objectMode:!0}),st(this.outboundInflightQueue,async o=>{for await(let{peerId:i,connection:a}of o)await this.createOutboundStream(i,a)}).catch(o=>{this.log.error("outbound inflight queue error",o)}),await Promise.all(this.opts.directPeers.map(async o=>{await this.components.peerStore.merge(o.id,{multiaddrs:o.addrs})}));let e=this.components.registrar;await Promise.all(this.multicodecs.map(async o=>e.handle(o,this.onIncomingStream.bind(this),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection})));let t={onConnect:this.onPeerConnected.bind(this),onDisconnect:this.onPeerDisconnected.bind(this),notifyOnLimitedConnection:this.runOnLimitedConnection},s=await Promise.all(this.multicodecs.map(async o=>e.register(o,t))),n=setTimeout(this.runHeartbeat,100);this.status={code:tr.started,registrarTopologyIds:s,heartbeatTimeout:n,hearbeatStartMs:Date.now()+100},this.score.start(),this.directPeerInitial=setTimeout(()=>{Promise.resolve().then(async()=>{await Promise.all(Array.from(this.direct).map(async o=>this.connect(o)))}).catch(o=>{this.log(o)})},1e3),this.opts.tagMeshPeers&&(this.addEventListener("gossipsub:graft",this.tagMeshPeer),this.addEventListener("gossipsub:prune",this.untagMeshPeer)),this.log("started")}async stop(){if(this.log("stopping"),this.status.code!==tr.started)return;let{registrarTopologyIds:e}=this.status;this.status={code:tr.stopped},this.opts.tagMeshPeers&&(this.removeEventListener("gossipsub:graft",this.tagMeshPeer),this.removeEventListener("gossipsub:prune",this.untagMeshPeer));let t=this.components.registrar;await Promise.all(this.multicodecs.map(async n=>t.unhandle(n))),e.forEach(n=>{t.unregister(n)}),this.outboundInflightQueue.end();let s=[];for(let n of this.streamsOutbound.values())s.push(n.close());this.streamsOutbound.clear();for(let n of this.streamsInbound.values())s.push(n.close());this.streamsInbound.clear(),await Promise.all(s),this.peers.clear(),this.subscriptions.clear(),this.heartbeatTimer!=null&&(this.heartbeatTimer.cancel(),this.heartbeatTimer=null),this.score.stop(),this.mesh.clear(),this.fanout.clear(),this.fanoutLastpub.clear(),this.gossip.clear(),this.control.clear(),this.peerhave.clear(),this.iasked.clear(),this.backoff.clear(),this.outbound.clear(),this.gossipTracer.clear(),this.seenCache.clear(),this.fastMsgIdCache!=null&&this.fastMsgIdCache.clear(),this.directPeerInitial!=null&&clearTimeout(this.directPeerInitial),this.idontwantCounts.clear(),this.idontwants.clear(),this.log("stopped")}dumpPeerScoreStats(){return this.score.dumpPeerScoreStats()}onIncomingStream({stream:e,connection:t}){if(!this.isStarted())return;let s=t.remotePeer;this.addPeer(s,t.direction,t.remoteAddr),this.createInboundStream(s,e),this.outboundInflightQueue.push({peerId:s,connection:t})}onPeerConnected(e,t){this.metrics?.newConnectionCount.inc({status:t.status}),!(!this.isStarted()||t.status!=="open")&&(this.addPeer(e,t.direction,t.remoteAddr),this.outboundInflightQueue.push({peerId:e,connection:t}))}onPeerDisconnected(e){this.log("connection ended %p",e),this.removePeer(e)}async createOutboundStream(e,t){if(!this.isStarted())return;let s=e.toString();if(this.peers.has(s)&&!this.streamsOutbound.has(s))try{let n=new td(await t.newStream(this.multicodecs,{runOnLimitedConnection:this.runOnLimitedConnection}),i=>{this.log.error("outbound pipe error",i)},{maxBufferSize:this.opts.maxOutboundBufferSize});this.log("create outbound stream %p",e),this.streamsOutbound.set(s,n);let o=n.protocol;o===sg&&this.floodsubPeers.add(s),this.metrics?.peersPerProtocol.inc({protocol:o},1),this.subscriptions.size>0&&(this.log("send subscriptions to",s),this.sendSubscriptions(s,Array.from(this.subscriptions),!0))}catch(n){this.log.error("createOutboundStream error",n)}}createInboundStream(e,t){if(!this.isStarted())return;let s=e.toString();if(!this.peers.has(s))return;let n=this.streamsInbound.get(s);n!==void 0&&(this.log("replacing existing inbound steam %s",s),n.close().catch(i=>{this.log.error(i)})),this.log("create inbound stream %s",s);let o=new rd(t,{maxDataLength:this.opts.maxInboundDataLength});this.streamsInbound.set(s,o),this.pipePeerReadStream(e,o.source).catch(i=>{this.log(i)})}addPeer(e,t,s){let n=e.toString();if(!this.peers.has(n)){this.log("new peer %p",e),this.peers.set(n,e),this.score.addPeer(n);let o=$v(s);o!==null?this.score.addIP(n,o):this.log("Added peer has no IP in current address %s %s",n,s.toString()),this.outbound.has(n)||this.outbound.set(n,t==="outbound")}}removePeer(e){let t=e.toString();if(!this.peers.has(t))return;this.log("delete peer %p",e),this.peers.delete(t);let s=this.streamsOutbound.get(t),n=this.streamsInbound.get(t);s!=null&&this.metrics?.peersPerProtocol.inc({protocol:s.protocol},-1),s?.close().catch(o=>{this.log.error(o)}),n?.close().catch(o=>{this.log.error(o)}),this.streamsOutbound.delete(t),this.streamsInbound.delete(t);for(let o of this.topics.values())o.delete(t);for(let[o,i]of this.mesh)i.delete(t)&&this.metrics?.onRemoveFromMesh(o,Fr.Dc,1);for(let o of this.fanout.values())o.delete(t);this.floodsubPeers.delete(t),this.gossip.delete(t),this.control.delete(t),this.outbound.delete(t),this.idontwantCounts.delete(t),this.idontwants.delete(t),this.score.removePeer(t),this.acceptFromWhitelist.delete(t)}get started(){return this.status.code===tr.started}getMeshPeers(e){let t=this.mesh.get(e);return t!=null?Array.from(t):[]}getSubscribers(e){let t=this.topics.get(e);return(t!=null?Array.from(t):[]).map(s=>this.peers.get(s)??$(s))}getTopics(){return Array.from(this.subscriptions)}async pipePeerReadStream(e,t){try{await st(t,async s=>{for await(let n of s)try{let o=n.subarray(),i=Ns.decode(o,{limits:{subscriptions:this.decodeRpcLimits.maxSubscriptions,messages:this.decodeRpcLimits.maxMessages,control$:{ihave:this.decodeRpcLimits.maxIhaveMessageIDs,iwant:this.decodeRpcLimits.maxIwantMessageIDs,graft:this.decodeRpcLimits.maxControlMessages,prune:this.decodeRpcLimits.maxControlMessages,prune$:{peers:this.decodeRpcLimits.maxPeerInfos},idontwant:this.decodeRpcLimits.maxControlMessages,idontwant$:{messageIDs:this.decodeRpcLimits.maxIdontwantMessageIDs}}}});if(this.metrics?.onRpcRecv(i,o.length),this.opts.awaitRpcHandler)try{await this.handleReceivedRpc(e,i)}catch(a){this.metrics?.onRpcRecvError(),this.log(a)}else this.handleReceivedRpc(e,i).catch(a=>{this.metrics?.onRpcRecvError(),this.log(a)})}catch(o){this.metrics?.onRpcDataError(),this.log(o)}})}catch(s){this.metrics?.onPeerReadStreamError(),this.handlePeerReadStreamError(s,e)}}handlePeerReadStreamError(e,t){this.log.error(e),this.onPeerDisconnected(t)}async handleReceivedRpc(e,t){if(!this.acceptFrom(e.toString())){this.log("received message from unacceptable peer %p",e),this.metrics?.rpcRecvNotAccepted.inc();return}let s=t.subscriptions!=null?t.subscriptions.length:0,n=t.messages!=null?t.messages.length:0,o=0,i=0,a=0,c=0;if(t.control!=null&&(t.control.ihave!=null&&(o=t.control.ihave.length),t.control.iwant!=null&&(i=t.control.iwant.length),t.control.graft!=null&&(a=t.control.graft.length),t.control.prune!=null&&(c=t.control.prune.length)),this.log(`rpc.from ${e.toString()} subscriptions ${s} messages ${n} ihave ${o} iwant ${i} graft ${a} prune ${c}`),t.subscriptions!=null&&t.subscriptions.length>0){let l=[];t.subscriptions.forEach(u=>{let h=u.topic,d=u.subscribe===!0;if(h!=null){if(this.allowedTopics!=null&&!this.allowedTopics.has(h))return;this.handleReceivedSubscription(e,h,d),l.push({topic:h,subscribe:d})}}),this.safeDispatchEvent("subscription-change",{detail:{peerId:e,subscriptions:l}})}for(let l of t.messages){if(this.allowedTopics!=null&&!this.allowedTopics.has(l.topic))continue;let u=this.handleReceivedMessage(e,l).catch(h=>{this.metrics?.onMsgRecvError(l.topic),this.log(h)});this.opts.awaitRpcMessageHandler&&await u}t.control!=null&&await this.handleControlMessage(e.toString(),t.control)}handleReceivedSubscription(e,t,s){this.log("subscription update from %p topic %s",e,t);let n=this.topics.get(t);n==null&&(n=new Set,this.topics.set(t,n)),s?n.add(e.toString()):n.delete(e.toString())}async handleReceivedMessage(e,t){this.metrics?.onMsgRecvPreValidation(t.topic);let s=await this.validateReceivedMessage(e,t);this.metrics?.onPrevalidationResult(t.topic,s.code);let n=s.code;switch(n){case kt.duplicate:this.score.duplicateMessage(e.toString(),s.msgIdStr,t.topic),this.gossipTracer.deliverMessage(s.msgIdStr,!0),this.mcache.observeDuplicate(s.msgIdStr,e.toString());return;case kt.invalid:if(s.msgIdStr!=null){let o=s.msgIdStr;this.score.rejectMessage(e.toString(),o,t.topic,s.reason),this.gossipTracer.rejectMessage(o,s.reason)}else this.score.rejectInvalidMessage(e.toString(),t.topic);this.metrics?.onMsgRecvInvalid(t.topic,s);return;case kt.valid:this.score.validateMessage(s.messageId.msgIdStr),this.gossipTracer.deliverMessage(s.messageId.msgIdStr),this.mcache.put(s.messageId,t,!this.opts.asyncValidation),this.subscriptions.has(t.topic)&&(!this.components.peerId.equals(e)||this.opts.emitSelf)&&(super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:e,msgId:s.messageId.msgIdStr,msg:s.msg}})),super.dispatchEvent(new CustomEvent("message",{detail:s.msg}))),this.opts.asyncValidation||this.forwardMessage(s.messageId.msgIdStr,t,e.toString());break;default:throw new Error(`Invalid validation result: ${n}`)}}async validateReceivedMessage(e,t){let s=this.fastMsgIdFn?.(t),n=s!==void 0?this.fastMsgIdCache?.get(s):void 0;if(n!=null)return{code:kt.duplicate,msgIdStr:n};let o=await Fv(this.globalSignaturePolicy,t);if(!o.valid)return{code:kt.invalid,reason:Bt.Error,error:o.error};let i=o.message;try{this.dataTransform!=null&&(i.data=this.dataTransform.inboundTransform(t.topic,i.data))}catch(h){return this.log("Invalid message, transform failed",h),{code:kt.invalid,reason:Bt.Error,error:Pt.TransformFailed}}let a=await this.msgIdFn(i),c=this.msgIdToStrFn(a),l={msgId:a,msgIdStr:c};if(s!==void 0&&this.fastMsgIdCache!=null&&this.fastMsgIdCache.put(s,c)&&this.metrics?.fastMsgIdCacheCollision.inc(),this.seenCache.has(c))return{code:kt.duplicate,msgIdStr:c};this.seenCache.put(c),(t.data?.length??0)>=this.opts.idontwantMinDataSize&&this.sendIDontWants(a,t.topic,e.toString());let u=this.topicValidators.get(t.topic);if(u!=null){let h;try{h=await u(e,i)}catch(d){let f=d.code;f===Ev&&(h=Ot.Ignore),f===vv?h=Ot.Reject:h=Ot.Ignore}if(h!==Ot.Accept)return{code:kt.invalid,reason:og(h),msgIdStr:c}}return{code:kt.valid,messageId:l,msg:i}}getScore(e){return this.score.score(e)}sendSubscriptions(e,t,s){this.sendRpc(e,{subscriptions:t.map(n=>({topic:n,subscribe:s})),messages:[]})}async handleControlMessage(e,t){if(t===void 0)return;let s=t.ihave?.length>0?this.handleIHave(e,t.ihave):[],n=t.iwant?.length>0?this.handleIWant(e,t.iwant):[],o=t.graft?.length>0?await this.handleGraft(e,t.graft):[];if(t.prune?.length>0&&await this.handlePrune(e,t.prune),t.idontwant?.length>0&&this.handleIdontwant(e,t.idontwant),s.length===0&&n.length===0&&o.length===0)return;let i=this.sendRpc(e,Ur(n,{iwant:s,prune:o})),a=s[0]?.messageIDs;a!=null&&(i?this.gossipTracer.addPromise(e,a):this.metrics?.iwantPromiseUntracked.inc(1))}acceptFrom(e){if(this.direct.has(e))return!0;let t=Date.now(),s=this.acceptFromWhitelist.get(e);if(s!=null&&s.messagesAccepted<128&&s.acceptUntil>=t)return s.messagesAccepted+=1,!0;let n=this.score.score(e);return n>=0?this.acceptFromWhitelist.set(e,{messagesAccepted:0,acceptUntil:t+1e3}):this.acceptFromWhitelist.delete(e),n>=this.opts.scoreThresholds.graylistThreshold}handleIHave(e,t){if(t.length===0)return[];let s=this.score.score(e);if(s<this.opts.scoreThresholds.gossipThreshold)return this.log("IHAVE: ignoring peer %s with score below threshold [ score = %d ]",e,s),this.metrics?.ihaveRcvIgnored.inc({reason:Xi.LowScore}),[];let n=(this.peerhave.get(e)??0)+1;if(this.peerhave.set(e,n),n>10)return this.log("IHAVE: peer %s has advertised too many times (%d) within this heartbeat interval; ignoring",e,n),this.metrics?.ihaveRcvIgnored.inc({reason:Xi.MaxIhave}),[];let o=this.iasked.get(e)??0;if(o>=5e3)return this.log("IHAVE: peer %s has already advertised too many messages (%d); ignoring",e,o),this.metrics?.ihaveRcvIgnored.inc({reason:Xi.MaxIasked}),[];let i=new Map;if(t.forEach(({topicID:l,messageIDs:u})=>{if(l==null||u==null||!this.mesh.has(l))return;let h=0;u.forEach(d=>{let f=this.msgIdToStrFn(d);this.seenCache.has(f)||(i.set(f,d),h++)}),this.metrics?.onIhaveRcv(l,u.length,h)}),i.size===0)return[];let a=i.size;a+o>5e3&&(a=5e3-o),this.log("IHAVE: Asking for %d out of %d messages from %s",a,i.size,e);let c=Array.from(i.values());return is(c),c=c.slice(0,a),this.iasked.set(e,o+a),[{messageIDs:c}]}handleIWant(e,t){if(t.length===0)return[];let s=this.score.score(e);if(s<this.opts.scoreThresholds.gossipThreshold)return this.log("IWANT: ignoring peer %s with score below threshold [score = %d]",e,s),[];let n=new Map,o=new Map,i=0;return t.forEach(({messageIDs:a})=>{a?.forEach(c=>{let l=this.msgIdToStrFn(c),u=this.mcache.getWithIWantCount(l,e);if(u==null){i++;return}if(o.set(u.msg.topic,1+(o.get(u.msg.topic)??0)),u.count>3){this.log("IWANT: Peer %s has asked for message %s too many times: ignoring request",e,c);return}n.set(l,u.msg)})}),this.metrics?.onIwantRcv(o,i),n.size===0?(this.log("IWANT: Could not provide any wanted messages to %s",e),[]):(this.log("IWANT: Sending %d messages to %s",n.size,e),Array.from(n.values()))}async handleGraft(e,t){let s=[],n=this.score.score(e),o=Date.now(),i=this.opts.doPX;if(t.forEach(({topicID:c})=>{if(c==null)return;let l=this.mesh.get(c);if(l==null){i=!1;return}if(l.has(e))return;let u=this.backoff.get(c)?.get(e);if(this.direct.has(e))this.log("GRAFT: ignoring request from direct peer %s",e),s.push(c),i=!1;else if(typeof u=="number"&&o<u){this.log("GRAFT: ignoring backed off peer %s",e),this.score.addPenalty(e,1,Yi.GraftBackoff),i=!1;let h=u+this.opts.graftFloodThreshold-this.opts.pruneBackoff;o<h&&this.score.addPenalty(e,1,Yi.GraftBackoff),this.addBackoff(e,c),s.push(c)}else n<0?(this.log("GRAFT: ignoring peer %s with negative score: score=%d, topic=%s",e,n,c),s.push(c),i=!1,this.addBackoff(e,c)):l.size>=this.opts.Dhi&&!(this.outbound.get(e)??!1)?(s.push(c),this.addBackoff(e,c)):(this.log("GRAFT: Add mesh link from %s in %s",e,c),this.score.graft(e,c),l.add(e),this.metrics?.onAddToMesh(c,Ft.Subscribed,1));this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:c,direction:"inbound"}})}),s.length===0)return[];let a=!1;return Promise.all(s.map(async c=>this.makePrune(e,c,i,a)))}async handlePrune(e,t){let s=this.score.score(e);for(let{topicID:n,backoff:o,peers:i}of t){if(n==null)continue;let a=this.mesh.get(n);if(a==null)return;this.log("PRUNE: Remove mesh link to %s in %s",e,n),this.score.prune(e,n),a.has(e)&&(a.delete(e),this.metrics?.onRemoveFromMesh(n,Fr.Prune,1)),typeof o=="number"&&o>0?this.doAddBackoff(e,n,o*1e3):this.addBackoff(e,n),i!=null&&i.length>0&&(s<this.opts.scoreThresholds.acceptPXThreshold?this.log("PRUNE: ignoring PX from peer %s with insufficient score [score = %d, topic = %s]",e,s,n):await this.pxConnect(i)),this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:n,direction:"inbound"}})}}handleIdontwant(e,t){let s=this.idontwantCounts.get(e)??0;if(s>=this.opts.idontwantMaxMessages)return;let n=s,o=this.idontwants.get(e);o==null&&(o=new Map,this.idontwants.set(e,o));let i=0;e:for(let{messageIDs:c}of t)for(let l of c){if(s>=this.opts.idontwantMaxMessages)break e;s++;let u=this.msgIdToStrFn(l);o.set(u,this.heartbeatTicks),this.mcache.msgs.has(u)||i++}this.idontwantCounts.set(e,s);let a=s-n;this.metrics?.onIdontwantRcv(a,i)}addBackoff(e,t){this.doAddBackoff(e,t,this.opts.pruneBackoff)}doAddBackoff(e,t,s){let n=this.backoff.get(t);n==null&&(n=new Map,this.backoff.set(t,n));let o=Date.now()+s;(n.get(e)??0)<o&&n.set(e,o)}applyIwantPenalties(){this.gossipTracer.getBrokenPromises().forEach((e,t)=>{this.log("peer %s didn't follow up in %d IWANT requests; adding penalty",t,e),this.score.addPenalty(t,e,Yi.BrokenPromise)})}clearBackoff(){if(this.heartbeatTicks%15!==0)return;let e=Date.now();this.backoff.forEach((t,s)=>{t.forEach((n,o)=>{n+1*this.opts.heartbeatInterval<e&&t.delete(o)}),t.size===0&&this.backoff.delete(s)})}async directConnect(){let e=[];this.direct.forEach(t=>{this.streamsOutbound.has(t)||e.push(t)}),await Promise.all(e.map(async t=>this.connect(t)))}async pxConnect(e){e.length>this.opts.prunePeers&&(is(e),e=e.slice(0,this.opts.prunePeers));let t=[];await Promise.all(e.map(async s=>{if(s.peerID==null)return;let n=Pr(Ht(s.peerID)),o=n.toString();if(!this.peers.has(o)){if(s.signedPeerRecord==null){t.push(o);return}try{if(!await this.components.peerStore.consumePeerRecord(s.signedPeerRecord,n)){this.log("bogus peer record obtained through px: could not add peer record to address book");return}t.push(o)}catch{this.log("bogus peer record obtained through px: invalid signature or not a peer record")}}})),t.length!==0&&await Promise.all(t.map(async s=>this.connect(s)))}async connect(e){this.log("Initiating connection with %s",e);let t=$(e),s=await this.components.connectionManager.openConnection(t);for(let n of this.multicodecs)for(let o of this.components.registrar.getTopologies(n))o.onConnect?.(t,s)}subscribe(e){if(this.status.code!==tr.started)throw new Error("Pubsub has not started");if(!this.subscriptions.has(e)){this.subscriptions.add(e);for(let t of this.peers.keys())this.sendSubscriptions(t,[e],!0)}this.join(e)}unsubscribe(e){if(this.status.code!==tr.started)throw new Error("Pubsub is not started");let t=this.subscriptions.delete(e);if(this.log("unsubscribe from %s - am subscribed %s",e,t),t)for(let s of this.peers.keys())this.sendSubscriptions(s,[e],!1);this.leave(e)}join(e){if(this.status.code!==tr.started)throw new Error("Gossipsub has not started");if(this.mesh.has(e))return;this.log("JOIN %s",e),this.metrics?.onJoin(e);let t=new Set,s=this.backoff.get(e),n=this.fanout.get(e);if(n!=null&&(this.fanout.delete(e),this.fanoutLastpub.delete(e),n.forEach(o=>{!this.direct.has(o)&&this.score.score(o)>=0&&s?.has(o)!==!0&&t.add(o)}),this.metrics?.onAddToMesh(e,Ft.Fanout,t.size)),t.size<this.opts.D){let o=t.size;this.getRandomGossipPeers(e,this.opts.D,a=>!t.has(a)&&!this.direct.has(a)&&this.score.score(a)>=0&&s?.has(a)!==!0).forEach(a=>{t.add(a)}),this.metrics?.onAddToMesh(e,Ft.Random,t.size-o)}this.mesh.set(e,t),t.forEach(o=>{this.log("JOIN: Add mesh link to %s in %s",o,e),this.sendGraft(o,e)})}leave(e){if(this.status.code!==tr.started)throw new Error("Gossipsub has not started");this.log("LEAVE %s",e),this.metrics?.onLeave(e);let t=this.mesh.get(e);t!=null&&(Promise.all(Array.from(t).map(async s=>{this.log("LEAVE: Remove mesh link to %s in %s",s,e),await this.sendPrune(s,e)})).catch(s=>{this.log("Error sending prunes to mesh peers",s)}),this.mesh.delete(e))}selectPeersToForward(e,t,s){let n=new Set,o=this.topics.get(e);o!=null&&(this.direct.forEach(a=>{o.has(a)&&t!==a&&!(s?.has(a)??!1)&&n.add(a)}),this.floodsubPeers.forEach(a=>{o.has(a)&&t!==a&&!(s?.has(a)??!1)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold&&n.add(a)}));let i=this.mesh.get(e);return i!=null&&i.size>0&&i.forEach(a=>{t!==a&&!(s?.has(a)??!1)&&n.add(a)}),n}selectPeersToPublish(e){let t=new Set,s={direct:0,floodsub:0,mesh:0,fanout:0},n=this.topics.get(e);if(n!=null)if(this.opts.floodPublish)n.forEach(o=>{this.direct.has(o)?(t.add(o),s.direct++):this.score.score(o)>=this.opts.scoreThresholds.publishThreshold&&(t.add(o),s.floodsub++)});else{this.direct.forEach(i=>{n.has(i)&&(t.add(i),s.direct++)}),this.floodsubPeers.forEach(i=>{n.has(i)&&this.score.score(i)>=this.opts.scoreThresholds.publishThreshold&&(t.add(i),s.floodsub++)});let o=this.mesh.get(e);if(o!=null&&o.size>0)o.forEach(i=>{t.add(i),s.mesh++}),o.size<this.opts.D&&this.getRandomGossipPeers(e,this.opts.D-o.size,a=>!o.has(a)&&!this.direct.has(a)&&!this.floodsubPeers.has(a)&&this.score.score(a)>=this.opts.scoreThresholds.publishThreshold).forEach(a=>{t.add(a),s.mesh++});else{let i=this.fanout.get(e);if(i!=null&&i.size>0)i.forEach(a=>{t.add(a),s.fanout++});else{let a=this.getRandomGossipPeers(e,this.opts.D,c=>this.score.score(c)>=this.opts.scoreThresholds.publishThreshold);a.size>0&&(this.fanout.set(e,a),a.forEach(c=>{t.add(c),s.fanout++}))}this.fanoutLastpub.set(e,Date.now())}}return{tosend:t,tosendCount:s}}forwardMessage(e,t,s,n){s!=null&&this.score.deliverMessage(s,e,t.topic);let o=this.selectPeersToForward(t.topic,s,n);o.forEach(i=>{this.sendRpc(i,Ur([t]))}),this.metrics?.onForwardMsg(t.topic,o.size)}async publish(e,t,s){let n=Date.now(),o=this.dataTransform!=null?this.dataTransform.outboundTransform(e,t):t;if(this.publishConfig==null)throw Error("PublishError.Uninitialized");let{raw:i,msg:a}=await Bv(this.publishConfig,e,t,o),c=await this.msgIdFn(a),l=this.msgIdToStrFn(c),u=s?.ignoreDuplicatePublishError??this.opts.ignoreDuplicatePublishError;if(this.seenCache.has(l)){if(u)return this.metrics?.onPublishDuplicateMsg(e),{recipients:[]};throw Error("PublishError.Duplicate")}let{tosend:h,tosendCount:d}=this.selectPeersToPublish(e),f=this.opts.emitSelf&&this.subscriptions.has(e),p=s?.allowPublishToZeroTopicPeers??this.opts.allowPublishToZeroTopicPeers;if(h.size===0&&!p&&!f)throw Error("PublishError.NoPeersSubscribedToTopic");this.seenCache.put(l),this.mcache.put({msgId:c,msgIdStr:l},i,!0),this.gossipTracer.deliverMessage(l),this.publishedMessageIds.put(l);let m=s?.batchPublish??this.opts.batchPublish,g=Ur([i]);if(m)this.sendRpcInBatch(h,g);else for(let w of h)this.sendRpc(w,g)||h.delete(w);let y=Date.now()-n;return this.metrics?.onPublishMsg(e,d,h.size,i.data!=null?i.data.length:0,y),f&&(h.add(this.components.peerId.toString()),super.dispatchEvent(new CustomEvent("gossipsub:message",{detail:{propagationSource:this.components.peerId,msgId:l,msg:a}})),super.dispatchEvent(new CustomEvent("message",{detail:a}))),{recipients:Array.from(h.values()).map(w=>this.peers.get(w)??$(w))}}sendRpcInBatch(e,t){let s=Ns.encode(t),n=Wi.single(s);for(let o of e){let i=this.streamsOutbound.get(o);if(i==null){this.log(`Cannot send RPC to ${o} as there is no open stream to it available`),e.delete(o);continue}try{i.pushPrefixed(n)}catch(a){e.delete(o),this.log.error(`Cannot send rpc to ${o}`,a)}this.metrics?.onRpcSent(t,s.length)}}reportMessageValidationResult(e,t,s){let n;if(s===Ot.Accept){if(n=this.mcache.validate(e),n!=null){let{message:i,originatingPeers:a}=n;this.score.deliverMessage(t,e,i.topic),this.forwardMessage(e,n.message,t,a)}}else if(n=this.mcache.remove(e),n!=null){let i=og(s),{message:a,originatingPeers:c}=n;this.score.rejectMessage(t,e,a.topic,i);for(let l of c)this.score.rejectMessage(l,e,a.topic,i)}let o=this.score.messageFirstSeenTimestampMs(e);this.metrics?.onReportValidation(n,s,o)}sendGraft(e,t){let n=Ur([],{graft:[{topicID:t}]});this.sendRpc(e,n)}async sendPrune(e,t){let n=[await this.makePrune(e,t,this.opts.doPX,!0)],o=Ur([],{prune:n});this.sendRpc(e,o)}sendIDontWants(e,t,s){let n=this.mesh.get(t);if(n==null)return;let o=new Set(n);o.delete(s);for(let a of o)this.streamsOutbound.get(a)?.protocol!==Yh&&o.delete(a);let i=Ur([],{idontwant:[{messageIDs:[e]}]});this.sendRpcInBatch(o,i)}sendRpc(e,t){let s=this.streamsOutbound.get(e);if(s==null)return this.log(`Cannot send RPC to ${e} as there is no open stream to it available`),!1;let n=this.control.get(e);n!=null&&(this.piggybackControl(e,t,n),this.control.delete(e));let o=this.gossip.get(e);o!=null&&(this.piggybackGossip(e,t,o),this.gossip.delete(e));let i=Ns.encode(t);try{s.push(i)}catch(a){return this.log.error(`Cannot send rpc to ${e}`,a),n!=null&&this.control.set(e,n),o!=null&&this.gossip.set(e,o),!1}if(this.metrics?.onRpcSent(t,i.length),t.control?.graft!=null)for(let a of t.control?.graft)a.topicID!=null&&this.safeDispatchEvent("gossipsub:graft",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});if(t.control?.prune!=null)for(let a of t.control?.prune)a.topicID!=null&&this.safeDispatchEvent("gossipsub:prune",{detail:{peerId:e,topic:a.topicID,direction:"outbound"}});return!0}piggybackControl(e,t,s){let n=ig(t);for(let o of s.graft)o.topicID!=null&&(this.mesh.get(o.topicID)?.has(e)??!1)&&n.control.graft.push(o);for(let o of s.prune)o.topicID!=null&&!(this.mesh.get(o.topicID)?.has(e)??!1)&&n.control.prune.push(o)}piggybackGossip(e,t,s){let n=ig(t);n.control.ihave=s}async sendGraftPrune(e,t,s){let n=this.opts.doPX,o=!1;for(let[i,a]of e){let c=a.map(h=>({topicID:h})),l=[],u=t.get(i);u!=null&&(l=await Promise.all(u.map(async h=>this.makePrune(i,h,n&&!(s.get(i)??!1),o))),t.delete(i)),this.sendRpc(i,Ur([],{graft:c,prune:l}))}for(let[i,a]of t){let c=await Promise.all(a.map(async l=>this.makePrune(i,l,n&&!(s.get(i)??!1),o)));this.sendRpc(i,Ur([],{prune:c}))}}emitGossip(e){let t=this.mcache.getGossipIDs(new Set(e.keys()));for(let[s,n]of e)this.doEmitGossip(s,n,t.get(s)??[])}doEmitGossip(e,t,s){if(s.length===0||(is(s),s.length>5e3&&this.log("too many messages for gossip; will truncate IHAVE list (%d messages)",s.length),t.size===0))return;let n=this.opts.Dlazy,i=this.opts.gossipFactor*t.size,a=t;i>n&&(n=i),n>a.size?n=a.size:a=is(Array.from(a)).slice(0,n),a.forEach(c=>{let l=s;s.length>5e3&&(l=is(l.slice()).slice(0,5e3)),this.pushGossip(c,{topicID:e,messageIDs:l})})}flush(){for(let[e,t]of this.gossip.entries())this.gossip.delete(e),this.sendRpc(e,Ur([],{ihave:t}));for(let[e,t]of this.control.entries()){this.control.delete(e);let s=Ur([],{graft:t.graft,prune:t.prune});this.sendRpc(e,s)}}pushGossip(e,t){this.log("Add gossip to %s",e);let s=this.gossip.get(e)??[];this.gossip.set(e,s.concat(t))}async makePrune(e,t,s,n){if(this.score.prune(e,t),this.streamsOutbound.get(e)?.protocol===ng)return{topicID:t,peers:[]};let o=n?this.opts.unsubcribeBackoff:this.opts.pruneBackoff,i=o/1e3;if(this.doAddBackoff(e,t,o),!s)return{topicID:t,peers:[],backoff:i};let a=this.getRandomGossipPeers(t,this.opts.prunePeers,l=>l!==e&&this.score.score(l)>=0),c=await Promise.all(Array.from(a).map(async l=>{let u=this.peers.get(l)??$(l),h;try{h=await this.components.peerStore.get(u)}catch(d){if(d.name!=="NotFoundError")throw d}return{peerID:u.toMultihash().bytes,signedPeerRecord:h?.peerRecordEnvelope}}));return{topicID:t,peers:c,backoff:i}}runHeartbeat=()=>{let e=this.metrics?.heartbeatDuration.startTimer();this.heartbeat().catch(t=>{this.log("Error running heartbeat",t)}).finally(()=>{if(e?.(),this.status.code===tr.started){clearTimeout(this.status.heartbeatTimeout);let t=this.opts.heartbeatInterval-(Date.now()-this.status.hearbeatStartMs)%this.opts.heartbeatInterval;t<this.opts.heartbeatInterval*.25&&(t+=this.opts.heartbeatInterval,this.metrics?.heartbeatSkipped.inc()),this.status.heartbeatTimeout=setTimeout(this.runHeartbeat,t)}})};async heartbeat(){let{D:e,Dlo:t,Dhi:s,Dscore:n,Dout:o,fanoutTTL:i}=this.opts;this.heartbeatTicks++;let a=new Map,c=p=>{let m=a.get(p);return m===void 0&&(m=this.score.score(p),a.set(p,m)),m},l=new Map,u=new Map,h=new Map;this.clearBackoff(),this.peerhave.clear(),this.metrics?.cacheSize.set({cache:"iasked"},this.iasked.size),this.iasked.clear(),this.applyIwantPenalties(),this.idontwantCounts.clear();for(let p of this.idontwants.values())for(let[m,g]of p)this.heartbeatTicks-g>=this.opts.mcacheLength&&p.delete(m);this.heartbeatTicks%this.opts.directConnectTicks===0&&await this.directConnect(),this.fastMsgIdCache?.prune(),this.seenCache.prune(),this.gossipTracer.prune(),this.publishedMessageIds.prune();let d=new Map;this.mesh.forEach((p,m)=>{let g=this.topics.get(m),y=new Set,w=new Set;if(d.set(m,w),g!=null){let E=is(Array.from(g)),P=this.backoff.get(m);for(let T of E){let D=this.streamsOutbound.get(T);if(D!=null&&this.multicodecs.includes(D.protocol)&&!p.has(T)&&!this.direct.has(T)){let v=c(T);P?.has(T)!==!0&&v>=0&&y.add(T),v>=this.opts.scoreThresholds.gossipThreshold&&w.add(T)}}}let b=(E,P)=>{this.log("HEARTBEAT: Remove mesh link to %s in %s",E,m),this.addBackoff(E,m),p.delete(E),c(E)>=this.opts.scoreThresholds.gossipThreshold&&w.add(E),this.metrics?.onRemoveFromMesh(m,P,1);let T=u.get(E);T==null?u.set(E,[m]):T.push(m)},x=(E,P)=>{this.log("HEARTBEAT: Add mesh link to %s in %s",E,m),this.score.graft(E,m),p.add(E),w.delete(E),this.metrics?.onAddToMesh(m,P,1);let T=l.get(E);T==null?l.set(E,[m]):T.push(m)};if(p.forEach(E=>{let P=c(E);P<0&&(this.log("HEARTBEAT: Prune peer %s with negative score: score=%d, topic=%s",E,P,m),b(E,Fr.BadScore),h.set(E,!0))}),p.size<t){let E=e-p.size;kv(y,E).forEach(T=>{x(T,Ft.NotEnough)})}if(p.size>s){let E=Array.from(p);E.sort((T,D)=>c(D)-c(T)),E=E.slice(0,n).concat(is(E.slice(n)));let P=0;if(E.slice(0,e).forEach(T=>{(this.outbound.get(T)??!1)&&P++}),P<o){let T=v=>{let M=E[v];for(let F=v;F>0;F--)E[F]=E[F-1];E[0]=M};if(P>0){let v=P;for(let M=1;M<e&&v>0;M++)(this.outbound.get(E[M])??!1)&&(T(M),v--)}let D=e-P;for(let v=e;v<E.length&&D>0;v++)(this.outbound.get(E[v])??!1)&&(T(v),D--)}E.slice(e).forEach(T=>{b(T,Fr.Excess)})}if(p.size>=t){let E=0;if(p.forEach(P=>{(this.outbound.get(P)??!1)&&E++}),E<o){let P=o-E;Qh(y,P,D=>this.outbound.get(D)===!0).forEach(D=>{x(D,Ft.Outbound)})}}if(this.heartbeatTicks%this.opts.opportunisticGraftTicks===0&&p.size>1){let E=Array.from(p).sort((D,v)=>c(D)-c(v)),P=Math.floor(p.size/2),T=c(E[P]);if(T<this.opts.scoreThresholds.opportunisticGraftThreshold){let D=this.opts.opportunisticGraftPeers,v=Qh(y,D,M=>c(M)>T);for(let M of v)this.log("HEARTBEAT: Opportunistically graft peer %s on topic %s",M,m),x(M,Ft.Opportunistic)}}});let f=Date.now();this.fanoutLastpub.forEach((p,m)=>{p+i<f&&(this.fanout.delete(m),this.fanoutLastpub.delete(m))}),this.fanout.forEach((p,m)=>{let g=this.topics.get(m);p.forEach(x=>{(!(g?.has(x)??!1)||c(x)<this.opts.scoreThresholds.publishThreshold)&&p.delete(x)});let y=this.topics.get(m),w=[],b=new Set;if(d.set(m,b),y!=null){let x=is(Array.from(y));for(let E of x){let P=this.streamsOutbound.get(E);if(P!=null&&this.multicodecs.includes(P.protocol)&&!p.has(E)&&!this.direct.has(E)){let T=c(E);T>=this.opts.scoreThresholds.publishThreshold&&w.push(E),T>=this.opts.scoreThresholds.gossipThreshold&&b.add(E)}}}if(p.size<e){let x=e-p.size;w.slice(0,x).forEach(E=>{p.add(E),b?.delete(E)})}}),this.emitGossip(d),await this.sendGraftPrune(l,u,h),this.flush(),this.mcache.shift(),this.dispatchEvent(new CustomEvent("gossipsub:heartbeat"))}getRandomGossipPeers(e,t,s=()=>!0){let n=this.topics.get(e);if(n==null)return new Set;let o=[];return n.forEach(i=>{let a=this.streamsOutbound.get(i);a!=null&&this.multicodecs.includes(a.protocol)&&s(i)&&o.push(i)}),o=is(o),t>0&&o.length>t&&(o=o.slice(0,t)),new Set(o)}onScrapeMetrics(e){e.mcacheSize.set(this.mcache.size),e.mcacheNotValidatedCount.set(this.mcache.notValidatedCount),e.cacheSize.set({cache:"direct"},this.direct.size),e.cacheSize.set({cache:"seenCache"},this.seenCache.size),e.cacheSize.set({cache:"fastMsgIdCache"},this.fastMsgIdCache?.size??0),e.cacheSize.set({cache:"publishedMessageIds"},this.publishedMessageIds.size),e.cacheSize.set({cache:"mcache"},this.mcache.size),e.cacheSize.set({cache:"score"},this.score.size),e.cacheSize.set({cache:"gossipTracer.promises"},this.gossipTracer.size),e.cacheSize.set({cache:"gossipTracer.requests"},this.gossipTracer.requestMsByMsgSize),e.cacheSize.set({cache:"topics"},this.topics.size),e.cacheSize.set({cache:"subscriptions"},this.subscriptions.size),e.cacheSize.set({cache:"mesh"},this.mesh.size),e.cacheSize.set({cache:"fanout"},this.fanout.size),e.cacheSize.set({cache:"peers"},this.peers.size),e.cacheSize.set({cache:"streamsOutbound"},this.streamsOutbound.size),e.cacheSize.set({cache:"streamsInbound"},this.streamsInbound.size),e.cacheSize.set({cache:"acceptFromWhitelist"},this.acceptFromWhitelist.size),e.cacheSize.set({cache:"gossip"},this.gossip.size),e.cacheSize.set({cache:"control"},this.control.size),e.cacheSize.set({cache:"peerhave"},this.peerhave.size),e.cacheSize.set({cache:"outbound"},this.outbound.size);let t=0,s=Date.now();e.connectedPeersBackoffSec.reset();for(let c of this.backoff.values()){t+=c.size;for(let[l,u]of c.entries())this.peers.has(l)&&e.connectedPeersBackoffSec.observe(Math.max(0,u-s)/1e3)}e.cacheSize.set({cache:"backoff"},t);let n=0;for(let c of this.idontwants.values())n+=c.size;e.cacheSize.set({cache:"idontwants"},n);for(let[c,l]of this.topics)e.topicPeersCount.set({topicStr:c},l.size);for(let[c,l]of this.mesh)e.meshPeerCounts.set({topicStr:c},l.size);let o=[],i=new Map;e.behaviourPenalty.reset();for(let c of this.peers.keys()){let l=this.score.score(c);o.push(l),i.set(c,l),e.behaviourPenalty.observe(this.score.peerStats.get(c)?.behaviourPenalty??0)}e.registerScores(o,this.opts.scoreThresholds),e.registerScorePerMesh(this.mesh,i);let a=Rv(this.peers.keys(),this.score.peerStats,this.score.params,this.score.peerIPs,e.topicStrToLabel);e.registerScoreWeights(a)}tagMeshPeer=e=>{let{peerId:t,topic:s}=e.detail;this.components.peerStore.merge(this.peers.get(t)??$(t),{tags:{[s]:{value:100}}}).catch(n=>{this.log.error("Error tagging peer %s with topic %s",t,s,n)})};untagMeshPeer=e=>{let{peerId:t,topic:s}=e.detail;this.components.peerStore.merge(this.peers.get(t)??$(t),{tags:{[s]:void 0}}).catch(n=>{this.log.error("Error untagging peer %s with topic %s",t,s,n)})}};function Vv(r={}){return e=>new ag(e,r)}X();ce();var wk=H("dns4"),xk=H("dns6"),vk=H("dnsaddr"),Ao=qe(H("dns"),vk,wk,xk),ad=qe(H("ip4"),H("ip6")),Ji=qe(j(ad,H("tcp")),j(Ao,H("tcp"))),cd=j(ad,H("udp")),Ek=j(cd,H("utp")),Sk=j(cd,H("quic")),Ik=j(cd,H("quic-v1")),cg=qe(j(Ji,H("ws")),j(Ao,H("ws"))),od=qe(j(cg,H("p2p")),cg),lg=qe(j(Ji,H("wss")),j(Ao,H("wss")),j(Ji,H("tls"),H("ws")),j(Ao,H("tls"),H("ws"))),id=qe(j(lg,H("p2p")),lg),ug=qe(j(Ji,H("http")),j(ad,H("http")),j(Ao,H("http"))),hg=qe(j(Ji,H("https")),j(ad,H("https")),j(Ao,H("https"))),Wv=j(cd,H("webrtc-direct"),H("certhash")),Xv=qe(j(Wv,H("p2p")),Wv),jv=j(Ik,H("webtransport"),H("certhash"),H("certhash")),Zv=qe(j(jv,H("p2p")),jv),Qv=qe(j(od,H("p2p-webrtc-star"),H("p2p")),j(id,H("p2p-webrtc-star"),H("p2p")),j(od,H("p2p-webrtc-star")),j(id,H("p2p-webrtc-star"))),fae=qe(j(od,H("p2p-websocket-star"),H("p2p")),j(id,H("p2p-websocket-star"),H("p2p")),j(od,H("p2p-websocket-star")),j(id,H("p2p-websocket-star"))),Jv=qe(j(ug,H("p2p-webrtc-direct"),H("p2p")),j(hg,H("p2p-webrtc-direct"),H("p2p")),j(ug,H("p2p-webrtc-direct")),j(hg,H("p2p-webrtc-direct"))),Co=qe(cg,lg,ug,hg,Qv,Jv,Ji,Ek,Sk,Ao,Xv,Zv),pae=qe(j(Co,H("p2p-stardust"),H("p2p")),j(Co,H("p2p-stardust"))),hn=qe(j(Co,H("p2p")),Qv,Jv,Xv,Zv,H("p2p")),Yv=qe(j(hn,H("p2p-circuit"),hn),j(hn,H("p2p-circuit")),j(H("p2p-circuit"),hn),j(Co,H("p2p-circuit")),j(H("p2p-circuit"),Co),H("p2p-circuit")),eE=()=>qe(j(Yv,eE),Yv),_o=eE(),tE=qe(j(_o,hn,_o),j(hn,_o),j(_o,hn),_o,hn);var mae=qe(j(_o,H("webrtc"),H("p2p")),j(_o,H("webrtc")),j(Co,H("webrtc"),H("p2p")),j(Co,H("webrtc")),H("webrtc"));function rE(r){function e(t){let s;try{s=G(t)}catch{return!1}let n=r(s.protoNames());return n===null?!1:n===!0||n===!1?n:n.length===0}return e}function j(...r){function e(t){if(t.length<r.length)return null;let s=t;return r.some(n=>(s=typeof n=="function"?n().partialMatch(t):n.partialMatch(t),Array.isArray(s)&&(t=s),s===null)),s}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:rE(e),partialMatch:e}}function qe(...r){function e(s){let n=null;return r.some(o=>{let i=typeof o=="function"?o().partialMatch(s):o.partialMatch(s);return i!=null?(n=i,!0):!1}),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:rE(e),partialMatch:e}}function H(r){let e=r;function t(n){let o;try{o=G(n)}catch{return!1}let i=o.protoNames();return i.length===1&&i[0]===e}function s(n){return n.length===0?null:n[0]===e?n.slice(1):null}return{toString:function(){return e},matches:t,partialMatch:s}}Ze();var _k="bootstrap",Ak=50,Ck=1e3,dg=class extends Xe{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??Ck,this.list=[];for(let s of t.list){if(!tE.matches(s)){this.log.error("Invalid multiaddr");continue}let n=G(s),o=n.getPeerId();if(o==null){this.log.error("Invalid bootstrap multiaddr without peer id");continue}let i={id:$(o),multiaddrs:[n]};this.list.push(i)}this._init=t}[Ta]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[et]=["@libp2p/peer-discovery"];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(e=>{this.log.error(e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??_k]:{value:this._init.tagValue??Ak,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function sE(r){return e=>new dg(e,r)}ce();var ld=class{components;running=!1;log;cfg;readyPromise=null;coordinatorCache=new Map;clusterCache=new Map;lastEstimate=null;blacklist=new Map;libp2pRef;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("db-p2p:network-manager"),this.cfg={clusterSize:t.clusterSize??1,seedKeys:t.seedKeys??[],estimation:t.estimation??{samples:8,kth:5,timeoutMs:1e3,ttlMs:6e4},readiness:t.readiness??{minPeers:1,maxWaitMs:2e3},cacheTTLs:t.cacheTTLs??{coordinatorMs:30*6e4,clusterMs:5*6e4},expectedRemotes:t.expectedRemotes??!1,allowClusterDownsize:t.allowClusterDownsize??!0,clusterSizeTolerance:t.clusterSizeTolerance??.5}}setLibp2p(e){this.libp2pRef=e}getLibp2p(){return this.libp2pRef??this.components.libp2p}getFret(){let e=this.getLibp2p();if(e)return e.services?.fret}get[Symbol.toStringTag](){return"@libp2p/network-manager"}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}async ready(){return this.readyPromise?this.readyPromise:(this.readyPromise=(async()=>{let t=(await Promise.allSettled((this.cfg.seedKeys??[]).map(s=>this.seedKey(s)))).filter(s=>s.status==="rejected");t.length>0&&this.log("Failed to seed %d keys",t.length),await new Promise(s=>setTimeout(s,50))})(),this.readyPromise)}async seedKey(e){let t=this.getFret();if(!t)throw new Error("FRET service not available for seeding keys");let s=await Xt(e),n=t.getNeighbors(s,"both",1)}toCacheKey(e){return Buffer.from(e).toString("base64url")}getKnownPeers(){let e=this.getLibp2p();if(!e)return[];let t=e.peerId,s=e.peerStore?.getPeers?.()??[],n=(e.getConnections?.()??[]).map(a=>a.remotePeer),o=[...s.map(a=>a.id),...n];return o.filter((a,c)=>o.findIndex(l=>l.toString()===a.toString())===c).filter(a=>a.toString()!==t.toString())}getStatus(){let e=this.getLibp2p();if(!e)return{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0};let s=(e.peerStore?.getPeers?.()??[]).filter(n=>n.id.toString()!==e.peerId.toString()).length;return s===0?{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0}:{mode:"healthy",connections:s}}async awaitHealthy(e,t){let s=Date.now();for(;Date.now()-s<t;){let o=this.getLibp2p();if(o){let i=o.getConnections?.()??[],a=new Set(i.map(c=>c.remotePeer.toString()));if(a.size>=e)return this.log("awaitHealthy: satisfied with %d connections",a.size),!0}await new Promise(i=>setTimeout(i,100))}let n=this.getLibp2p();if(n){let o=n.getConnections?.()??[],i=new Set(o.map(c=>c.remotePeer.toString())),a=i.size>=e;return this.log("awaitHealthy: timeout - %d connections (needed %d)",i.size,e),a}return!1}reportBadPeer(e,t=1,s=10*6e4){let n=e.toString(),i=(this.blacklist.get(n)?.score??0)+Math.max(1,t);this.blacklist.set(n,{score:i,expires:Date.now()+s})}isBlacklisted(e){let t=e.toString(),s=this.blacklist.get(t);return s?s.expires<=Date.now()?(this.blacklist.delete(t),!1):s.score>=3:!1}recordCoordinator(e,t){let s=this.toCacheKey(e);this.coordinatorCache.set(s,{id:t,expires:Date.now()+this.cfg.cacheTTLs.coordinatorMs})}async findNearestPeerToKey(e){let t=this.getFret(),s=this.getLibp2p();if(!s)throw new Error("Libp2p not initialized");if(t){let a=await Xt(e),c=t.getNeighbors(a,"both",1);if(c.length>0){let l=c[0];if(l){let{peerIdFromString:u}=await Promise.resolve().then(()=>(ce(),Ep)),h=u(l);if(!this.isBlacklisted(h))return h}}}let n=(s.getConnections?.()??[]).map(a=>a.remotePeer),o=[s.peerId,...n,...this.getKnownPeers()].filter((a,c,l)=>l.findIndex(u=>u.toString()===a.toString())===c).filter(a=>!this.isBlacklisted(a));return o.length===0?s.peerId:o.reduce((a,c)=>this.lexLess(this.xor(a.toMultihash().bytes,e),this.xor(c.toMultihash().bytes,e))?a:c,o[0])}async getCluster(e){let t=this.toCacheKey(e),s=this.clusterCache.get(t);if(s&&s.expires>Date.now())return s.ids;let n=this.getFret(),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");if(n){let f=await Xt(e),p=n.getDiagnostics?.()??{},m=typeof p.estimate=="number"?p.estimate:typeof p.n=="number"?p.n:void 0,g=Math.max(1,Math.min(this.cfg.clusterSize,Number.isFinite(m)?m:this.cfg.clusterSize)),y=n.assembleCohort(f,g),{peerIdFromString:w}=await Promise.resolve().then(()=>(ce(),Ep)),b=y.map(x=>{try{return w(x)}catch(E){return this.log("Invalid peer ID in cohort: %s, %o",x,E),null}}).filter(x=>x!==null&&!this.isBlacklisted(x));if(b.length>0)return this.clusterCache.set(t,{ids:b,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),this.lastEstimate=m!=null?{estimate:m,samples:p.samples??0,updated:Date.now()}:this.lastEstimate,b}let i=await this.findNearestPeerToKey(e),a=i.toMultihash().bytes,c=(o.getConnections?.()??[]).map(f=>f.remotePeer),u=[i,o.peerId,...c,...this.getKnownPeers()].filter((f,p,m)=>!this.isBlacklisted(f)&&m.findIndex(g=>g.toString()===f.toString())===p).sort((f,p)=>this.lexLess(this.xor(f.toMultihash().bytes,a),this.xor(p.toMultihash().bytes,a))?-1:1),h=Math.min(this.cfg.clusterSize,u.length),d=u.slice(0,h);return this.clusterCache.set(t,{ids:d,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),d}async getCoordinator(e){let t=this.toCacheKey(e),s=this.coordinatorCache.get(t);if(s){if(s.expires>Date.now())return s.id;this.coordinatorCache.delete(t)}let n=await this.getCluster(e),o=this.getLibp2p();if(!o)throw new Error("Libp2p not initialized");let i=n.find(a=>!this.isBlacklisted(a))??o.peerId;return this.recordCoordinator(e,i),i}xor(e,t){let s=Math.max(e.length,t.length),n=new Uint8Array(s);for(let o=0;o<s;o++){let i=e[e.length-1-o]??0,a=t[t.length-1-o]??0;n[s-1-o]=i^a}return n}lexLess(e,t){let s=Math.max(e.length,t.length);for(let n=0;n<s;n++){let o=e[n]??0,i=t[n]??0;if(o<i)return!0;if(o>i)return!1}return!1}};function fg(r={}){return e=>new ld(e,r)}var ud=class{peerStatuses=new Map;unreachableThreshold=3;rapidChurnThreshold=5;rapidChurnWindow=1e4;peerTimeoutMs=6e4;recordSuccess(e){let t=Date.now(),s=this.peerStatuses.get(e);s?(s.lastSeen=t,s.consecutiveFailures=0):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:0}),this.cleanupOldPeers()}recordFailure(e){let t=Date.now(),s=this.peerStatuses.get(e);s?(s.consecutiveFailures++,s.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:1})}recordGoodbye(e){let t=Date.now(),s=this.peerStatuses.get(e);s?(s.lastGoodbye=t,s.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,lastGoodbye:t,consecutiveFailures:0})}detectPartition(){let e=Date.now(),t=this.getRecentGoodbyes(this.rapidChurnWindow),s=Array.from(this.peerStatuses.values()).filter(o=>o.consecutiveFailures>=this.unreachableThreshold&&!o.lastGoodbye);return t.length+s.length>=this.rapidChurnThreshold}getUnreachablePeers(){return Array.from(this.peerStatuses.values()).filter(e=>e.consecutiveFailures>=this.unreachableThreshold&&!e.lastGoodbye).map(e=>e.peerId)}getRecentGoodbyes(e){let t=Date.now()-e;return Array.from(this.peerStatuses.values()).filter(s=>s.lastGoodbye&&s.lastGoodbye>t)}cleanupOldPeers(){let e=Date.now()-this.peerTimeoutMs;for(let[t,s]of this.peerStatuses.entries())s.lastSeen<e&&this.peerStatuses.delete(t)}getStatistics(){let e=this.getUnreachablePeers().length,t=this.getRecentGoodbyes(this.rapidChurnWindow).length;return{totalPeers:this.peerStatuses.size,unreachable:e,recentGoodbyes:t}}reset(){this.peerStatuses.clear()}};async function Tk(r){let e=r.storageType??"memory",t;if(e==="file"){if(!r.storagePath)throw new Error('storagePath is required when storageType is "file"');t=new qa(r.storagePath)}else t=new $a;let s=async(b,x)=>{},n=new Ga(b=>new ci(b,t,s)),o,i,a={async update(b){if(!o)throw new Error("ClusterMember not initialized");return await o.update(b)}},c={async get(b,x){return await(i??n).get(b,x)},async pend(b,x){return await(i??n).pend(b,x)},async cancel(b,x){return await(i??n).cancel(b,x)},async commit(b,x){return await(i??n).commit(b,x)}},l=r.id?await $(r.id):void 0,u={start:!1,...l?{peerId:l}:{},addresses:{listen:[`/ip4/0.0.0.0/tcp/${r.port}`]},connectionManager:{autoDial:!0,minConnections:1,maxConnections:16,inboundConnectionUpgradeTimeout:1e4,dialQueue:{concurrency:2,attempts:2}},transports:[dw()],connectionEncrypters:[Zx()],streamMuxers:[lv()],services:{identify:mv({protocolPrefix:`/optimystic/${r.networkName}`}),ping:wv(),pubsub:Vv({allowPublishToZeroTopicPeers:!0,heartbeatInterval:7e3}),cluster:b=>o0({protocolPrefix:`/optimystic/${r.networkName}`,configuredClusterSize:r.clusterSize??10,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5})({logger:b.logger,registrar:b.registrar,cluster:a}),repo:b=>c0({protocolPrefix:`/optimystic/${r.networkName}`})({logger:b.logger,registrar:b.registrar,repo:c}),sync:b=>$0({protocolPrefix:`/optimystic/${r.networkName}`})({logger:b.logger,registrar:b.registrar,repo:c}),networkManager:b=>{let E=fg({clusterSize:r.clusterSize??10,expectedRemotes:(r.bootstrapNodes?.length??0)>0,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5})(b);try{E.setLibp2p?.(b.libp2p)}catch{}return E},fret:b=>{let E=q0({k:15,m:8,capacity:2048,profile:r.fretProfile??((r.bootstrapNodes?.length??0)>0?"core":"edge"),networkName:r.networkName,bootstraps:r.bootstrapNodes??[]})(b);try{E.setLibp2p(b.libp2p)}catch{}return E}},peerDiscovery:[...r.bootstrapNodes?.length?[sE({list:r.bootstrapNodes})]:[]]},h=await Jb(u);try{h.services?.fret?.setLibp2p?.(h)}catch{}try{h.services?.networkManager?.setLibp2p?.(h)}catch{}await h.start();let d=new ic(h),f=`/optimystic/${r.networkName}`,p=b=>Tn.create(b,d,f),m=new ud,g=h.services?.fret;if(o=n0({storageRepo:n,peerNetwork:d,peerId:h.peerId,protocolPrefix:f,partitionDetector:m,fretService:g,validator:r.validator}),i=a0(d,p,{clusterSize:r.clusterSize??10,superMajorityThreshold:r.clusterPolicy?.superMajorityThreshold??.67,simpleMajorityThreshold:.51,minAbsoluteClusterSize:2,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5,partitionDetectionWindow:6e4},g)({storageRepo:n,localCluster:o,localPeerId:h.peerId}),r.arachnode?.enableRingZulu??!0){let b=h.logger?.forComponent?.("db-p2p:arachnode"),x=h.services?.fret;if(x){let E=new oc(x),P=new nc(t,r.arachnode?.storage??{}),T=new sc(E,P,{minCapacity:100*1024*1024,thresholds:{moveOut:.85,moveIn:.4}}),D=h.peerId.toString(),v=await T.createArachnodeInfo(D);E.setArachnodeInfo(v),b?.("Announced Arachnode membership: Ring %d",v.ringDepth);let M=new rc(E,{connect:(S,_)=>h.dialProtocol(S,[_])},`/optimystic/${r.networkName}`),F=async(S,_)=>await M.restore(S,_);n.createBlockStorage=S=>new ci(S,t,F);let B=setInterval(async()=>{let S=await T.shouldTransition();if(S.shouldMove){b?.("Ring transition needed: moving %s to Ring %d",S.direction,S.newRingDepth);let _=await T.createArachnodeInfo(D);E.setArachnodeInfo(_)}},6e4),I=h.stop.bind(h);h.stop=async()=>{clearInterval(B),await I()}}else b?.("FRET service not available, Arachnode disabled")}return h.coordinatedRepo=i,h.storageRepo=n,h.keyNetwork=d,h}function nE(r,e){let t=Math.max(r.length,e.length),s=new Uint8Array(t);for(let n=0;n<t;n++){let o=r[r.length-1-n]??0,i=e[e.length-1-n]??0;s[t-1-n]=o^i}return s}function oE(r,e){let t=Math.max(r.length,e.length);for(let s=0;s<t;s++){let n=r[s]??0,o=e[s]??0;if(n<o)return!0;if(n>o)return!1}return!1}function iE(r,e){return r.map(t=>({p:t,d:nE(t.id.toMultihash().bytes,e)})).sort((t,s)=>oE(t.d,s.d)?-1:1).map(t=>t.p)}function Pk(r,e,t,s){let n=[e,...t],o=iE(n,r);if(n.length<=3)return{inCluster:o[0].id.equals(e.id),nearest:o};let i=Math.min(s,Math.max(1,Math.floor(n.length/2))),a=o.slice(0,i);return{inCluster:a.some(l=>l.id.equals(e.id)),nearest:a}}function kk(r){let e={id:r.peerId,addrs:r.getMultiaddrs().map(o=>o.toString())},t=r.getConnections(),s={};for(let o of t){let i=o.remotePeer,a=i.toString(),c=s[a]??(s[a]={id:i,addrs:new Set}),l=o.remoteAddr?.toString?.();l&&c.addrs.add(l)}let n=Object.values(s).map(o=>({id:o.id,addrs:Array.from(o.addrs)}));return[e,...n]}var Dk=lr("network:get-manager");function Mk(r){let e=r.services?.networkManager;if(e==null)throw new Error("networkManager service is not registered on this libp2p node");try{e.setLibp2p?.(r)}catch(t){Dk("getNetworkManager setLibp2p failed - %o",t)}return e}return dE(Ok);})();
|
|
29
|
+
/*! Bundled license information:
|
|
30
|
+
|
|
31
|
+
@noble/hashes/utils.js:
|
|
32
|
+
@noble/hashes/esm/utils.js:
|
|
33
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
34
|
+
|
|
35
|
+
@noble/curves/utils.js:
|
|
36
|
+
@noble/curves/abstract/modular.js:
|
|
37
|
+
@noble/curves/abstract/curve.js:
|
|
38
|
+
@noble/curves/abstract/weierstrass.js:
|
|
39
|
+
@noble/curves/secp256k1.js:
|
|
40
|
+
@noble/curves/esm/utils.js:
|
|
41
|
+
@noble/curves/esm/abstract/modular.js:
|
|
42
|
+
@noble/curves/esm/abstract/curve.js:
|
|
43
|
+
@noble/curves/esm/abstract/edwards.js:
|
|
44
|
+
@noble/curves/esm/abstract/montgomery.js:
|
|
45
|
+
@noble/curves/esm/ed25519.js:
|
|
46
|
+
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
47
|
+
|
|
48
|
+
@noble/ciphers/esm/utils.js:
|
|
49
|
+
(*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
|
|
50
|
+
*/
|
|
51
|
+
return OptimysticDbP2P}));
|
|
52
|
+
//# sourceMappingURL=index.min.js.map
|