@helia/delegated-routing-client 1.0.1-688bd9de → 1.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 +1 -1
- package/dist/index.min.js.map +2 -2
- package/dist/typedoc-urls.json +5 -0
- package/package.json +3 -3
package/dist/index.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaDelegatedRoutingClient = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var HeliaDelegatedRoutingClient=(()=>{var je=Object.defineProperty;var Pr=Object.getOwnPropertyDescriptor;var Sr=Object.getOwnPropertyNames;var Dr=Object.prototype.hasOwnProperty;var I=(r,e)=>{for(var t in e)je(r,t,{get:e[t],enumerable:!0})},Lr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Sr(e))!Dr.call(r,o)&&o!==t&&je(r,o,{get:()=>e[o],enumerable:!(n=Pr(e,o))||n.enumerable});return r};var Nr=r=>Lr(je({},"__esModule",{value:!0}),r);var us={};I(us,{delegatedHTTPRouter:()=>cs,delegatedHTTPRoutingDefaults:()=>Lt});var F=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var ve=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var M=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};function Ur(r){return typeof r?.handleEvent=="function"}function Or(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Ce=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=Or(n);super.addEventListener(e,i=>{if(o){let c=this.#e.get(i.type);c!=null&&(c=c.filter(({callback:a})=>a!==t),this.#e.set(i.type,c))}Ur(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function _(r=0){return new Uint8Array(r)}function V(r=0){return new Uint8Array(r)}function Rr(r){return r?.buffer instanceof ArrayBuffer}function ke(r){if(Rr(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function q(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=V(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return ke(t)}function J(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 Ot=Symbol.for("@achingbrain/uint8arraylist");function Nt(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function te(r){return!!r?.[Ot]}var Ut=class r{bufs;length;[Ot]=!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 n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(te(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}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 n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(te(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Nt(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Nt(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(te(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));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:n,length:o}=this._subList(e,t);return q(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:q(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_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 n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],c=o,a=c+i.byteLength;if(o=a,e>=a)continue;let u=e>=c&&e<a,l=t>c&&t<=a;if(u&&l){if(e===c&&t===a){n.push(i);break}let h=e-c;n.push(i.subarray(h,h+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-c));continue}if(l){if(t===a){n.push(i);break}n.push(i.subarray(0,t-c));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!te(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let c=i,a=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let h=t;h<=a;h+=l){l=0;for(let f=u;f>=0;f--){let p=this.get(h+f);if(n[f]!==p){l=Math.max(1,f-c[p]);break}}if(l===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 n=V(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=_(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=_(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=_(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,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 n=V(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=_(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=_(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=_(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=_(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=_(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,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(!J(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Je={};I(Je,{base10:()=>$r});var Cs=new Uint8Array(0);function Bt(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 D(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return X(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return X(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function _t(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var Rt=4096;function Vt(r){let e=r.length;if(e<=Rt)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=Rt));return t}function Br(r){return r?.buffer instanceof ArrayBuffer}function X(r){return Br(r)?r:r.slice()}function _r(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),c=i.charCodeAt(0);if(n[c]!==255)throw new TypeError(i+" is ambiguous");if(n[c]=s,t){var a=i.toLowerCase().charCodeAt(0),u=i.toUpperCase().charCodeAt(0);a!==c&&(n[a]=s),u!==c&&(n[u]=s)}}var l=r.length,h=r.charAt(0),f=Math.log(l)/Math.log(256),p=Math.log(256)/Math.log(l);function v(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,C=0,A=0,P=d.length;A!==P&&d[A]===0;)A++,y++;for(var R=(P-A)*p+1>>>0,S=new Uint8Array(R);A!==P;){for(var B=d[A],k=0,O=R-1;(B!==0||k<C)&&O!==-1;O--,k++)B+=256*S[O]>>>0,S[O]=B%l>>>0,B=B/l>>>0;if(B!==0)throw new Error("Non-zero carry");C=k,A++}for(var z=R-C;z!==R&&S[z]===0;)z++;for(var Ee=h.repeat(y);z<R;++z)Ee+=r.charAt(S[z]);return Ee}function U(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var C=0,A=0;d[y]===h;)C++,y++;for(var P=(d.length-y)*f+1>>>0,R=new Uint8Array(P);d[y];){var S=n[d.charCodeAt(y)];if(S===255)return;for(var B=0,k=P-1;(S!==0||B<A)&&k!==-1;k--,B++)S+=l*R[k]>>>0,R[k]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");A=B,y++}if(d[y]!==" "){for(var O=P-A;O!==P&&R[O]===0;)O++;for(var z=new Uint8Array(C+(P-O)),Ee=C;O!==P;)z[Ee++]=R[O++];return z}}}function m(d){var y=U(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:v,decodeUnsafe:U,decode:m}}var Vr=_r,zr=Vr,Ft=zr;var He=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ge=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}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 Mt(this,e)}},We=class{decoders;constructor(e){this.decoders=e}or(e){return Mt(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Mt(r,e){return new We({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Qe=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new He(e,t,n),this.decoder=new Ge(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function re({name:r,prefix:e,encode:t,decode:n}){return new Qe(r,e,t,n)}function H({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=Ft(t,r,n);return re({prefix:e,name:r,encode:o,decode:i=>D(s(i))})}function Fr(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,c=0,a=0;for(let u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,i+=t,i>=8&&(i-=8,s[a++]=255&c>>i)}if(i>=t||(255&c<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Mr(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,c=0;for(let a=0;a<r.length;++a)for(c=c<<8|r[a],i+=8;i>t;)i-=t,s+=e[o&c>>i];if(i!==0&&(s+=e[o&c<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function qr(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function b({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=qr(n,o);return re({prefix:e,name:r,encode(i){return Mr(i,n,t)},decode(i){return Fr(i,s,t,r)}})}var $r=H({prefix:"9",name:"base10",alphabet:"0123456789"});var Xe={};I(Xe,{base16:()=>jr,base16upper:()=>kr});var jr=b({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),kr=b({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Ke={};I(Ke,{base2:()=>Hr});var Hr=b({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ye={};I(Ye,{base256emoji:()=>Xr});var qt=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}"),Gr=qt.reduce((r,e,t)=>(r[t]=e,r),[]),Wr=qt.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Qr(r){return r.reduce((e,t)=>(e+=Gr[t],e),"")}function Jr(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Wr[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Xr=re({prefix:"\u{1F680}",name:"base256emoji",encode:Qr,decode:Jr});var Ze={};I(Ze,{base32:()=>G,base32hex:()=>en,base32hexpad:()=>rn,base32hexpadupper:()=>nn,base32hexupper:()=>tn,base32pad:()=>Yr,base32padupper:()=>Zr,base32upper:()=>Kr,base32z:()=>on});var G=b({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Kr=b({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Yr=b({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),Zr=b({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),en=b({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),tn=b({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),rn=b({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),nn=b({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),on=b({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var et={};I(et,{base36:()=>de,base36upper:()=>sn});var de=H({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),sn=H({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var tt={};I(tt,{base58btc:()=>L,base58flickr:()=>an});var L=H({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),an=H({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var nt={};I(nt,{base64:()=>cn,base64pad:()=>un,base64url:()=>rt,base64urlpad:()=>ln});var cn=b({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),un=b({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rt=b({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ln=b({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ot={};I(ot,{base8:()=>hn});var hn=b({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var st={};I(st,{identity:()=>fn});var fn=re({prefix:"\0",name:"identity",encode:r=>Vt(D(r)),decode:r=>D(_t(r))});var Fs=new TextEncoder,Ms=new TextDecoder;var at={};I(at,{identity:()=>Bn});var mn=kt,$t=128,gn=127,bn=~gn,yn=Math.pow(2,31);function kt(r,e,t){e=e||[],t=t||0;for(var n=t;r>=yn;)e[t++]=r&255|$t,r/=128;for(;r&bn;)e[t++]=r&255|$t,r>>>=7;return e[t]=r|0,kt.bytes=t-n+1,e}var wn=it,xn=128,jt=127;function it(r,n){var t=0,n=n||0,o=0,s=n,i,c=r.length;do{if(s>=c)throw it.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&jt)<<o:(i&jt)*Math.pow(2,o),o+=7}while(i>=xn);return it.bytes=s-n,t}var En=Math.pow(2,7),vn=Math.pow(2,14),Cn=Math.pow(2,21),In=Math.pow(2,28),Tn=Math.pow(2,35),An=Math.pow(2,42),Pn=Math.pow(2,49),Sn=Math.pow(2,56),Dn=Math.pow(2,63),Ln=function(r){return r<En?1:r<vn?2:r<Cn?3:r<In?4:r<Tn?5:r<An?6:r<Pn?7:r<Sn?8:r<Dn?9:10},Nn={encode:mn,decode:wn,encodingLength:Ln},Un=Nn,pe=Un;function me(r,e=0){return[pe.decode(r,e),pe.decode.bytes]}function ne(r,e,t=0){return pe.encode(r,e,t),e}function oe(r){return pe.encodingLength(r)}function ie(r,e){let t=e.byteLength,n=oe(r),o=n+oe(t),s=new Uint8Array(o+t);return ne(r,s,0),ne(t,s,n),s.set(e,o),new se(r,t,e,s)}function K(r){let e=D(r),[t,n]=me(e),[o,s]=me(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new se(t,o,i,e)}function Ht(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Bt(r.bytes,t.bytes)}}var se=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=X(n),this.bytes=X(o)}};var Gt=0,On="identity",Wt=D;function Rn(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 ie(Gt,Wt(r))}var Bn={code:Gt,name:On,encode:Wt,digest:Rn};var lt={};I(lt,{sha256:()=>Vn,sha512:()=>zn});var _n=20;function ut({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new ct(r,e,t,n,o)}var ct=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??_n,this.maxDigestLength=s}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 n=this.encode(e);return n instanceof Uint8Array?Qt(n,this.code,t?.truncate):n.then(o=>Qt(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Qt(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 ie(e,r)}function Xt(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Vn=ut({name:"sha2-256",code:18,encode:Xt("SHA-256")}),zn=ut({name:"sha2-512",code:19,encode:Xt("SHA-512")});function Kt(r,e){let{bytes:t,version:n}=r;return n===0?Mn(t,ht(r),e??L.encoder):qn(t,ht(r),e??G.encoder)}var Yt=new WeakMap;function ht(r){let e=Yt.get(r);if(e==null){let t=new Map;return Yt.set(r,t),t}return e}var T=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=X(o),this["/"]=this.bytes}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!==ge)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==$n)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,n=ie(e,t);return r.createV1(this.code,n)}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 n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Ht(e.multihash,n.multihash)}toString(e){return Kt(this,e)}toJSON(){return{"/":Kt(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:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Zt(n,o,s.bytes))}else if(t[jn]===!0){let{version:n,multihash:o,code:s}=t,i=K(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ge)throw new Error(`Version 0 CID must use dag-pb (code: ${ge}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Zt(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ge,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=D(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new se(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,f]=me(e.subarray(t));return t+=f,h},o=n(),s=ge;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,c=n(),a=n(),u=t+a,l=u-i;return{version:o,codec:s,multihashCode:c,digestSize:a,multihashSize:l,size:u}}static parse(e,t){let[n,o]=Fn(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ht(s).set(n,e),s}};function Fn(r,e){switch(r[0]){case"Q":{let t=e??L;return[L.prefix,t.decode(`${L.prefix}${r}`)]}case L.prefix:{let t=e??L;return[L.prefix,t.decode(r)]}case G.prefix:{let t=e??G;return[G.prefix,t.decode(r)]}case de.prefix:{let t=e??de;return[de.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 Mn(r,e,t){let{prefix:n}=t;if(n!==L.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function qn(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var ge=112,$n=18;function Zt(r,e,t){let n=oe(r),o=n+oe(e),s=new Uint8Array(o+t.byteLength);return ne(r,s,0),ne(e,s,n),s.set(t,o),s}var jn=Symbol.for("@ipld/js-cid/CID");var be={...st,...Ke,...ot,...Je,...Xe,...Ze,...et,...tt,...nt,...Ye},ci={...lt,...at};function tr(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var er=tr("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ft=tr("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=V(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),kn={utf8:er,"utf-8":er,hex:be.base16,latin1:ft,ascii:ft,binary:ft,...be},Te=kn;function W(r,e="utf8"){let t=Te[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Ae=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}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,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,c=this.peekChar();if(c===void 0)return;let a=c==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,e);if(!Number.isNaN(f))return f});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&a&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[c]=e(s.subarray(0,i));return t.set(s.subarray(0,c),16-c),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Hn=45,Gn=15,Pe=new Ae;function rr(r){if(!(r.length>Gn))return Pe.new(r).parseWith(()=>Pe.readIPv4Addr())}function nr(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Hn))return Pe.new(r).parseWith(()=>Pe.readIPv6Addr())}function Se(r){return!!rr(r)}function or(r){return!!nr(r)}var Wn=Math.pow(2,7),Qn=Math.pow(2,14),Jn=Math.pow(2,21),dt=Math.pow(2,28),pt=Math.pow(2,35),mt=Math.pow(2,42),gt=Math.pow(2,49),g=128,E=127;function ae(r){if(r<Wn)return 1;if(r<Qn)return 2;if(r<Jn)return 3;if(r<dt)return 4;if(r<pt)return 5;if(r<mt)return 6;if(r<gt)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function bt(r,e,t=0){switch(ae(r)){case 8:e[t++]=r&255|g,r/=128;case 7:e[t++]=r&255|g,r/=128;case 6:e[t++]=r&255|g,r/=128;case 5:e[t++]=r&255|g,r/=128;case 4:e[t++]=r&255|g,r>>>=7;case 3:e[t++]=r&255|g,r>>>=7;case 2:e[t++]=r&255|g,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Xn(r,e){let t=r[e],n=0;if(n+=t&E,t<g||(t=r[e+1],n+=(t&E)<<7,t<g)||(t=r[e+2],n+=(t&E)<<14,t<g)||(t=r[e+3],n+=(t&E)<<21,t<g)||(t=r[e+4],n+=(t&E)*dt,t<g)||(t=r[e+5],n+=(t&E)*pt,t<g)||(t=r[e+6],n+=(t&E)*mt,t<g)||(t=r[e+7],n+=(t&E)*gt,t<g))return n;throw new RangeError("Could not decode varint")}function Kn(r,e){let t=r.get(e),n=0;if(n+=t&E,t<g||(t=r.get(e+1),n+=(t&E)<<7,t<g)||(t=r.get(e+2),n+=(t&E)<<14,t<g)||(t=r.get(e+3),n+=(t&E)<<21,t<g)||(t=r.get(e+4),n+=(t&E)*dt,t<g)||(t=r.get(e+5),n+=(t&E)*pt,t<g)||(t=r.get(e+6),n+=(t&E)*mt,t<g)||(t=r.get(e+7),n+=(t&E)*gt,t<g))return n;throw new RangeError("Could not decode varint")}function yt(r,e=0){return r instanceof Uint8Array?Xn(r,e):Kn(r,e)}function Zn(r){return r.buffer instanceof ArrayBuffer}function ye(r){return Zn(r)?r:r.slice()}function Q(r,e="utf8"){let t=Te[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var x=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},$=class extends Error{static name="ValidationError";name="ValidationError"},De=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Le=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function xt(r){return e=>Q(e,r)}function Et(r){return e=>W(e,r)}function ce(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Z(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function sr(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=W(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Z(n);return q([t,o],t.length+o.length)}function ir(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=G.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Z(n);return q([t,o],t.length+o.length)}function vt(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=Q(e,"base32"),o=ce(t);return`${n}:${o}`}var Ct=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new x("Invalid byte value in IP address");e[n]=o}),e},ar=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Se(t[n]),i;s&&(i=Ct(t[n]),t[n]=Q(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,Q(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(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new x("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},cr=function(r){if(r.byteLength!==4)throw new x("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},ur=function(r){if(r.byteLength!==16)throw new x("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new x(`Invalid IPv6 address "${t}"`)}};function lr(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new x(`Invalid IPv6 address "${r}"`)}}var wt=Object.values(be).map(r=>r.decoder),eo=(function(){let r=wt[0].or(wt[1]);return wt.slice(2).forEach(e=>r=r.or(e)),r})();function hr(r){return eo.decode(r)}function fr(r){return e=>r.encoder.encode(e)}function to(r){if(parseInt(r).toString()!==r)throw new $("Value must be an integer")}function ro(r){if(r<0)throw new $("Value must be a positive integer, or zero")}function no(r){return e=>{if(e>r)throw new $(`Value must be smaller than or equal to ${r}`)}}function oo(...r){return e=>{for(let t of r)t(e)}}var we=oo(to,ro,no(65535));var w=-1,It=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 Le(`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(n=>{this.protocolsByName.delete(n)}))}},j=new It,Go=[{code:4,name:"ip4",size:32,valueToBytes:Ct,bytesToValue:cr,validate:r=>{if(!Se(r))throw new $(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Z,bytesToValue:ce,validate:we},{code:273,name:"udp",size:16,valueToBytes:Z,bytesToValue:ce,validate:we},{code:33,name:"dccp",size:16,valueToBytes:Z,bytesToValue:ce,validate:we},{code:41,name:"ip6",size:128,valueToBytes:ar,bytesToValue:ur,stringToValue:lr,validate:r=>{if(!or(r))throw new $(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:w},{code:43,name:"ipcidr",size:8,bytesToValue:xt("base10"),valueToBytes:Et("base10")},{code:53,name:"dns",size:w},{code:54,name:"dns4",size:w},{code:55,name:"dns6",size:w},{code:56,name:"dnsaddr",size:w},{code:132,name:"sctp",size:16,valueToBytes:Z,bytesToValue:ce,validate:we},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:w,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:w,bytesToValue:xt("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Et("base58btc")(r):T.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:vt,valueToBytes:sr},{code:445,name:"onion3",size:296,bytesToValue:vt,valueToBytes:ir},{code:446,name:"garlic64",size:w},{code:447,name:"garlic32",size:w},{code:448,name:"tls"},{code:449,name:"sni",size:w},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:w,bytesToValue:fr(rt),valueToBytes:hr},{code:480,name:"http"},{code:481,name:"http-path",size:w,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:w}];Go.forEach(r=>{j.addProtocol(r)});function dr(r){let e=[],t=0;for(;t<r.length;){let n=yt(r,t),o=j.getProtocol(n),s=ae(n),i=Wo(o,r,t+s),c=0;i>0&&o.size===w&&(c=ae(i));let a=s+c+i,u={code:n,name:o.name,bytes:ye(r.subarray(t,t+a))};if(i>0){let l=t+s+c,h=r.subarray(l,l+i);u.value=o.bytesToValue?.(h)??Q(h)}e.push(u),t+=a}return e}function pr(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=j.getProtocol(n.code),s=ae(n.code),i,c=0,a=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??W(n.value),c=i.byteLength,o.size===w&&(a=ae(c)));let u=new Uint8Array(s+a+c),l=0;bt(n.code,u,l),l+=s,i!=null&&(o.size===w&&(bt(c,u,l),l+=a),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return q(t,e)}function mr(r){if(r.charAt(0)!=="/")throw new x('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let c=s===r.length-1;if(i==="/"||c){let a=j.getProtocol(o);if(t==="protocol"){if(a.size==null||a.size===0){e.push({code:a.code,name:a.name}),n="",o="",t="protocol";continue}else if(c)throw new x(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:a.code,name:a.name};if(a.size!=null&&a.size!==0){if(n==="")throw new x(`Component ${o} was missing value`);u.value=a.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new x("Incomplete multiaddr");return e}function gr(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=j.getProtocol(e.code);if(t==null)throw new x(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Wo(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:yt(e,t)}var Qo=Symbol.for("nodejs.util.inspect.custom"),Tt=Symbol.for("@multiformats/multiaddr");function Jo(r){if(r==null&&(r="/"),br(r))return r.getComponents();if(r instanceof Uint8Array)return dr(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),mr(r);if(Array.isArray(r))return r;throw new x("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ne=class r{[Tt]=!0;#e;#r;#t;constructor(e="/",t={}){this.#e=Jo(e),t.validate!==!1&&Xo(this)}get bytes(){return this.#t==null&&(this.#t=pr(this.#e)),this.#t}toString(){return this.#r==null&&(this.#r=gr(this.#e)),this.#r}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new De(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return J(this.bytes,e.bytes)}[Qo](){return`Multiaddr(${this.toString()})`}};function Xo(r){r.getComponents().forEach(e=>{let t=j.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function br(r){return!!r?.[Tt]}function yr(r){return new Ne(r)}function ue(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ue=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}},le=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ue(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 Ue(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 At=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function wr(r={}){return Ko(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Ko(r,e){e=e??{};let t=e.onEnd,n=new le,o,s,i,c=ue(),a=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,d)=>{s=y=>{s=null,n.push(y);try{m(r(n))}catch(C){d(C)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=ue()})}},u=m=>s!=null?s(m):(n.push(m),o),l=m=>(n=new le,s!=null?s({error:m}):(n.push({error:m}),o)),h=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},f=m=>i?o:(i=!0,m!=null?l(m):u({done:!0})),p=()=>(n=new le,f(),{done:!0}),v=m=>(f(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:a,return:p,throw:v,push:h,end:f,get readableLength(){return n.size},onEmpty:async m=>{let d=m?.signal;if(d?.throwIfAborted(),n.isEmpty())return;let y,C;d!=null&&(y=new Promise((A,P)=>{C=()=>{P(new At)},d.addEventListener("abort",C)}));try{await Promise.race([c.promise,y])}finally{C!=null&&d!=null&&d?.removeEventListener("abort",C)}}},t==null)return o;let U=o;return o={[Symbol.asyncIterator](){return this},next(){return U.next()},throw(m){return U.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return U.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(m){return U.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return U.readableLength},onEmpty:m=>U.onEmpty(m)},o}var Pt=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},xr=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function St(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,c,a,l=new Promise((h,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){f(xr(i));return}if(i&&(a=()=>{f(xr(i))},i.addEventListener("abort",a,{once:!0})),r.then(h,f),t===Number.POSITIVE_INFINITY)return;let p=new Pt;c=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(v){f(v)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?h():o instanceof Error?f(o):(p.message=o??`Promise timed out after ${t} milliseconds`,f(p))},t)}).finally(()=>{l.clear(),a&&i&&i.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,c),c=void 0},l}var Yo=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 Zo(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!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 c=[e].flat(),a=[],{addListener:u,removeListener:l}=Yo(r),h=async(...p)=>{let v=t.multiArgs?p:p[0];if(t.filter)try{if(!await t.filter(v))return}catch(U){n(),i(U);return}a.push(v),t.count===a.length&&(n(),s(a))},f=(...p)=>{n(),i(t.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of c)l(p,h);for(let p of t.rejectionEvents)c.includes(p)||l(p,f)};for(let p of c)u(p,h);for(let p of t.rejectionEvents)c.includes(p)||u(p,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(a)});if(o.cancel=n,typeof t.timeout=="number"){let s=St(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Oe(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Zo(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Dt(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Re=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function es(r){return r.reason}async function Er(r,e,t){if(e==null)return r;let n=t?.translateError??es;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Be=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=ue(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new F)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function ts(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var _e=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=ts(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new F),this.cleanup())}async join(e){let t=new Be(e);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 Er(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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 Ve=class extends Ce{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,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=Dt(this.emitEmpty.bind(this),1),this.emitIdle=Dt(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;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 Re;let n=new _e(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new F)}),this.clear()}async onEmpty(e){this.size!==0&&await Oe(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Oe(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Oe(this,"idle",e)}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=wr({objectMode:!0}),n=a=>{a!=null?this.abort():this.clear(),t.end(a)},o=a=>{a.detail!=null&&t.push(a.detail)},s=a=>{n(a.detail.error)},i=()=>{n()},c=()=>{n(new F("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",c);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",c),n()}}};function he(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}async function*xe(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var ze=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*fe(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),te(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new ze("Incoming message too long");let i=o.split(t);o=i.pop()??"";for(let c=0;c<i.length;c++)yield JSON.parse(i[c])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var ee=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},N=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};var Fe={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},Me=class{url;started;httpQueue;shutDownController;timeout;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(e,t){this.log=e.logger.forComponent("helia:delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new Ve({concurrency:t.concurrentRequests??Fe.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??Fe.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.cacheName=t.cacheName??Fe.cacheName,this.cacheTTL=t.cacheTTL??Fe.cacheTTL}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&this.log("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){this.log("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers(),c=0;this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.url}routing/v1/providers/${e}`);this.#r(a,t.filterAddrs,t.filterProtocols);let u=await this.#t(a.toString(),{headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:o});if(!u.ok){if(u.status===404)return;throw u.status===422?new ee("Request does not conform to schema or semantic constraints"):new N(`Unexpected status code: ${u.status}`)}let l=u.headers.get("Content-Type");if(l==null)throw new N("No Content-Type header received");if(u.body==null){if(l!=="application/x-ndjson")throw new N("Routing response had no body");return}if(l.startsWith("application/json")){let f=(await u.json()).Providers??[];for(let p of f){let v=this.#e(p);v!=null&&(c++,yield v)}}else if(l.includes("application/x-ndjson"))for await(let h of fe(xe(u.body))){let f=this.#e(h);f!=null&&(c++,yield f)}else throw new N(`Unsupported Content-Type: ${l}`)}finally{o.clear(),i.resolve(),this.log("getProviders finished found %d providers for %c",c,e)}}async*getPeers(e,t={}){this.log("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let c=new URL(`${this.url}routing/v1/peers/${e}`);this.#r(c,t.filterAddrs,t.filterProtocols);let a=await this.#t(c.toString(),{headers:{Accept:"application/x-ndjson"},signal:o});if(a.status===404)return;if(a.status===422)throw new ee("Request does not conform to schema or semantic constraints");if(a.body==null)throw new N("Routing response had no body");if(a.headers.get("Content-Type")?.startsWith("application/json")){let h=(await a.json()).Peers??[];for(let f of h){let p=this.#e(f);p!=null&&(yield p)}}else for await(let l of fe(xe(a.body))){let h=this.#e(l);h!=null&&(yield h)}}catch(c){this.log.error("getPeers errored - %e",c)}finally{o.clear(),i.resolve(),this.log("getPeers finished: %c",e)}}async*getClosestPeers(e,t={}){let n;if(T.asCID(e)===e||e instanceof T)n=e.toV1().toString();else throw new ve("Key must be CID");this.log("getClosestPeers starts: %s",n);let o=AbortSignal.timeout(this.timeout),s=he([this.shutDownController.signal,o,t.signal]);let i=Promise.withResolvers(),c=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),c.promise));try{await i.promise;let a=new URL(`${this.url}routing/v1/dht/closest/peers/${n}`);this.#r(a,t.filterAddrs,t.filterProtocols);let u=await this.#t(a.toString(),{headers:{Accept:"application/x-ndjson"},signal:s});if(u.status===404)return;if(u.status===422)throw new ee("Request does not conform to schema or semantic constraints");if(u.body==null)throw new N("Routing response had no body");if(u.headers.get("Content-Type")?.startsWith("application/json")){let f=(await u.json()).Peers??[];for(let p of f){let v=this.#e(p);v!=null&&(yield v)}}else for await(let h of fe(xe(u.body))){let f=this.#e(h);f!=null&&(yield f)}}catch(a){this.log.error("getClosestPeers errored - %e",a)}finally{s.clear(),c.resolve(),this.log("getClosestPeers finished: %s",n)}}async getIPNS(e,t={}){this.log("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));let c=`${this.url}routing/v1/ipns/${e}`;try{await s.promise;let a=await this.#t(c,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(this.log("getIPNS GET %s %d",c,a.status),a.status===404)throw new M("No matching records found");if(a.status===422)throw new ee("Request does not conform to schema or semantic constraints");if(!a.ok)throw new N(`Unexpected status code: ${a.status}`);let u=a.headers.get("Content-Type");if(u==null||!u.includes("application/vnd.ipfs.ipns-record"))throw new M("No matching records found");if(a.body==null)throw new N("GET ipns response had no body");let l=await a.arrayBuffer();return new Uint8Array(l,0,l.byteLength)}catch(a){throw this.log.error("getIPNS GET %s error - %e",c,a),a}finally{o.clear(),i.resolve(),this.log("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=he([this.shutDownController.signal,o,n.signal]);let i=Promise.withResolvers(),c=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),c.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await i.promise;let u=await this.#t(a,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:ye(t),signal:s});if(this.log("putIPNS PUT %s %d",a,u.status),u.status!==200)throw new N("PUT ipns response had status other than 200")}catch(u){throw this.log.error("putIPNS PUT %s error - %e",a,u.stack),u}finally{s.clear(),c.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(yr)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:T.createV1(114,rs(e.ID)),Addrs:n,Protocols:t}}catch(t){this.log.error("could not conform record to peer schema - %e",t)}}#r(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#t(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let a=await this.cache?.match(e);if(a!=null){if(parseInt(a.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",o),this.logResponse(a),a;this.log("evicting cached response for %s",o),await this.cache?.delete(e)}else this.cache!=null&&this.log("cache miss for %s",o)}let s=this.inFlightRequests.get(o);if(s!=null){let a=await s;return this.log("deduplicating outgoing request for %s",o),a.clone()}this.log("outgoing request:"),this.logRequest(e,t);let i=fetch(e,t).then(async a=>{if(this.log("incoming response:"),this.logResponse(a),this.cache!=null&&a.ok&&n==="GET"){let u=Date.now()+this.cacheTTL,l=new Headers(a.headers);l.set("x-cache-expires",u.toString());let h=new Response(a.clone().body,{status:a.status,statusText:a.statusText,headers:l});await this.cache.put(e,h)}return a}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(e,t){let n=new Headers(t.headers);this.log("%s %s HTTP/1.1",t.method??"GET",e);for(let[o,s]of n.entries())this.log("%s: %s",o,s)}logResponse(e){this.log("HTTP/1.1 %d %s",e.status,e.statusText);for(let[t,n]of e.headers.entries())this.log("%s: %s",t,n)}};function rs(r){let e=L.baseDecode(r);return K(e)}function ns(r){return r[Symbol.asyncIterator]!=null}function os(r){if(ns(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var vr=os;function ss(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Cr=ss;function is(r){return r[Symbol.asyncIterator]!=null}function as(r,e){let t=0;if(is(r))return(async function*(){for await(let a of r)yield e(a,t++)})();let n=Cr(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let a of n)yield e(a,t++)})();let c=e;return(function*(){yield i;for(let a of n)yield c(a,t++)})()}var Ir=as;function Tr(r){return e=>new Me(e,r)}var qe=W("/ipns/");function Ar(r){return J(r.subarray(0,qe.byteLength),qe)}var $e=class{name="delegated-http-router";client;constructor(e,t){this.client=Tr(t)(e)}async provide(e,t){}async cancelReprovide(e,t){}async*findProviders(e,t){yield*Ir(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols,routing:"delegated-http-routing"}))}async put(e,t,n){if(!Ar(e))return;let o=K(e.slice(qe.length)),s=T.createV1(114,o);await this.client.putIPNS(s,t,n)}async get(e,t){if(!Ar(e))throw new M("Not found");let n=K(e.slice(qe.length)),o=T.createV1(114,n);try{return await this.client.getIPNS(o,t)}catch(s){throw s.name==="BadResponseError"?new M("Not found"):s}}async findPeer(e,t){let n=await vr(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new M("Not found")}async*getClosestPeers(e,t){}toString(){return`DelegatedHTTPRouter(${this.client.url})`}};function Lt(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}function cs(r){return e=>new $e(e,Lt(r))}return Nr(us);})();
|
|
2
|
+
"use strict";var HeliaDelegatedRoutingClient=(()=>{var je=Object.defineProperty;var Pr=Object.getOwnPropertyDescriptor;var Sr=Object.getOwnPropertyNames;var Dr=Object.prototype.hasOwnProperty;var I=(r,e)=>{for(var t in e)je(r,t,{get:e[t],enumerable:!0})},Lr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Sr(e))!Dr.call(r,o)&&o!==t&&je(r,o,{get:()=>e[o],enumerable:!(n=Pr(e,o))||n.enumerable});return r};var Nr=r=>Lr(je({},"__esModule",{value:!0}),r);var us={};I(us,{delegatedHTTPRouter:()=>cs,delegatedHTTPRoutingDefaults:()=>Lt});var F=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var ve=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var M=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};function Ur(r){return typeof r?.handleEvent=="function"}function Or(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Ce=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){let o=Or(n);super.addEventListener(e,i=>{if(o){let c=this.#e.get(i.type);c!=null&&(c=c.filter(({callback:a})=>a!==t),this.#e.set(i.type,c))}Ur(t)?t.handleEvent(i):t(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function _(r=0){return new Uint8Array(r)}function V(r=0){return new Uint8Array(r)}function Rr(r){return r?.buffer instanceof ArrayBuffer}function ke(r){if(Rr(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function q(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=V(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return ke(t)}function J(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 Ot=Symbol.for("@achingbrain/uint8arraylist");function Nt(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function te(r){return!!r?.[Ot]}var Ut=class r{bufs;length;[Ot]=!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 n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(te(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}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 n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(te(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Nt(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Nt(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(te(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));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:n,length:o}=this._subList(e,t);return q(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:q(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_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 n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],c=o,a=c+i.byteLength;if(o=a,e>=a)continue;let u=e>=c&&e<a,l=t>c&&t<=a;if(u&&l){if(e===c&&t===a){n.push(i);break}let h=e-c;n.push(i.subarray(h,h+(t-e)));break}if(u){if(e===0){n.push(i);continue}n.push(i.subarray(e-c));continue}if(l){if(t===a){n.push(i);break}n.push(i.subarray(0,t-c));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!te(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let c=i,a=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let h=t;h<=a;h+=l){l=0;for(let f=u;f>=0;f--){let p=this.get(h+f);if(n[f]!==p){l=Math.max(1,f-c[p]);break}}if(l===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 n=V(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=_(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=_(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=_(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,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 n=V(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=_(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=_(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=_(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=_(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=_(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,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(!J(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Je={};I(Je,{base10:()=>$r});var Cs=new Uint8Array(0);function Bt(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 D(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return X(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return X(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function _t(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var Rt=4096;function Vt(r){let e=r.length;if(e<=Rt)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.subarray(n,n+=Rt));return t}function Br(r){return r?.buffer instanceof ArrayBuffer}function X(r){return Br(r)?r:r.slice()}function _r(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),c=i.charCodeAt(0);if(n[c]!==255)throw new TypeError(i+" is ambiguous");if(n[c]=s,t){var a=i.toLowerCase().charCodeAt(0),u=i.toUpperCase().charCodeAt(0);a!==c&&(n[a]=s),u!==c&&(n[u]=s)}}var l=r.length,h=r.charAt(0),f=Math.log(l)/Math.log(256),p=Math.log(256)/Math.log(l);function v(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,C=0,A=0,P=d.length;A!==P&&d[A]===0;)A++,y++;for(var R=(P-A)*p+1>>>0,S=new Uint8Array(R);A!==P;){for(var B=d[A],k=0,O=R-1;(B!==0||k<C)&&O!==-1;O--,k++)B+=256*S[O]>>>0,S[O]=B%l>>>0,B=B/l>>>0;if(B!==0)throw new Error("Non-zero carry");C=k,A++}for(var z=R-C;z!==R&&S[z]===0;)z++;for(var Ee=h.repeat(y);z<R;++z)Ee+=r.charAt(S[z]);return Ee}function U(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var C=0,A=0;d[y]===h;)C++,y++;for(var P=(d.length-y)*f+1>>>0,R=new Uint8Array(P);d[y];){var S=n[d.charCodeAt(y)];if(S===255)return;for(var B=0,k=P-1;(S!==0||B<A)&&k!==-1;k--,B++)S+=l*R[k]>>>0,R[k]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");A=B,y++}if(d[y]!==" "){for(var O=P-A;O!==P&&R[O]===0;)O++;for(var z=new Uint8Array(C+(P-O)),Ee=C;O!==P;)z[Ee++]=R[O++];return z}}}function m(d){var y=U(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:v,decodeUnsafe:U,decode:m}}var Vr=_r,zr=Vr,Ft=zr;var He=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ge=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}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 Mt(this,e)}},We=class{decoders;constructor(e){this.decoders=e}or(e){return Mt(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Mt(r,e){return new We({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Qe=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new He(e,t,n),this.decoder=new Ge(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function re({name:r,prefix:e,encode:t,decode:n}){return new Qe(r,e,t,n)}function H({name:r,prefix:e,alphabet:t,caseInsensitive:n=!1}){let{encode:o,decode:s}=Ft(t,r,n);return re({prefix:e,name:r,encode:o,decode:i=>D(s(i))})}function Fr(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,c=0,a=0;for(let u=0;u<o;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,i+=t,i>=8&&(i-=8,s[a++]=255&c>>i)}if(i>=t||(255&c<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Mr(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,c=0;for(let a=0;a<r.length;++a)for(c=c<<8|r[a],i+=8;i>t;)i-=t,s+=e[o&c>>i];if(i!==0&&(s+=e[o&c<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function qr(r,e){let t={};for(let n=0;n<r.length;++n)if(t[r[n]]=n,e){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(t[o]=n),s!==r[n]&&(t[s]=n)}return t}function b({name:r,prefix:e,bitsPerChar:t,alphabet:n,caseInsensitive:o=!1}){let s=qr(n,o);return re({prefix:e,name:r,encode(i){return Mr(i,n,t)},decode(i){return Fr(i,s,t,r)}})}var $r=H({prefix:"9",name:"base10",alphabet:"0123456789"});var Xe={};I(Xe,{base16:()=>jr,base16upper:()=>kr});var jr=b({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),kr=b({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Ke={};I(Ke,{base2:()=>Hr});var Hr=b({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ye={};I(Ye,{base256emoji:()=>Xr});var qt=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}"),Gr=qt.reduce((r,e,t)=>(r[t]=e,r),[]),Wr=qt.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Qr(r){return r.reduce((e,t)=>(e+=Gr[t],e),"")}function Jr(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Wr[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Xr=re({prefix:"\u{1F680}",name:"base256emoji",encode:Qr,decode:Jr});var Ze={};I(Ze,{base32:()=>G,base32hex:()=>en,base32hexpad:()=>rn,base32hexpadupper:()=>nn,base32hexupper:()=>tn,base32pad:()=>Yr,base32padupper:()=>Zr,base32upper:()=>Kr,base32z:()=>on});var G=b({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Kr=b({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Yr=b({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),Zr=b({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),en=b({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),tn=b({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),rn=b({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),nn=b({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),on=b({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var et={};I(et,{base36:()=>de,base36upper:()=>sn});var de=H({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),sn=H({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var tt={};I(tt,{base58btc:()=>L,base58flickr:()=>an});var L=H({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),an=H({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var nt={};I(nt,{base64:()=>cn,base64pad:()=>un,base64url:()=>rt,base64urlpad:()=>ln});var cn=b({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),un=b({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rt=b({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ln=b({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ot={};I(ot,{base8:()=>hn});var hn=b({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var st={};I(st,{identity:()=>fn});var fn=re({prefix:"\0",name:"identity",encode:r=>Vt(D(r)),decode:r=>D(_t(r))});var Fs=new TextEncoder,Ms=new TextDecoder;var at={};I(at,{identity:()=>Bn});var mn=kt,$t=128,gn=127,bn=~gn,yn=Math.pow(2,31);function kt(r,e,t){e=e||[],t=t||0;for(var n=t;r>=yn;)e[t++]=r&255|$t,r/=128;for(;r&bn;)e[t++]=r&255|$t,r>>>=7;return e[t]=r|0,kt.bytes=t-n+1,e}var wn=it,xn=128,jt=127;function it(r,n){var t=0,n=n||0,o=0,s=n,i,c=r.length;do{if(s>=c)throw it.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&jt)<<o:(i&jt)*Math.pow(2,o),o+=7}while(i>=xn);return it.bytes=s-n,t}var En=Math.pow(2,7),vn=Math.pow(2,14),Cn=Math.pow(2,21),In=Math.pow(2,28),Tn=Math.pow(2,35),An=Math.pow(2,42),Pn=Math.pow(2,49),Sn=Math.pow(2,56),Dn=Math.pow(2,63),Ln=function(r){return r<En?1:r<vn?2:r<Cn?3:r<In?4:r<Tn?5:r<An?6:r<Pn?7:r<Sn?8:r<Dn?9:10},Nn={encode:mn,decode:wn,encodingLength:Ln},Un=Nn,pe=Un;function me(r,e=0){return[pe.decode(r,e),pe.decode.bytes]}function ne(r,e,t=0){return pe.encode(r,e,t),e}function oe(r){return pe.encodingLength(r)}function ie(r,e){let t=e.byteLength,n=oe(r),o=n+oe(t),s=new Uint8Array(o+t);return ne(r,s,0),ne(t,s,n),s.set(e,o),new se(r,t,e,s)}function K(r){let e=D(r),[t,n]=me(e),[o,s]=me(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new se(t,o,i,e)}function Ht(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Bt(r.bytes,t.bytes)}}var se=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=X(n),this.bytes=X(o)}};var Gt=0,On="identity",Wt=D;function Rn(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 ie(Gt,Wt(r))}var Bn={code:Gt,name:On,encode:Wt,digest:Rn};var lt={};I(lt,{sha256:()=>Vn,sha512:()=>zn});var _n=20;function ut({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new ct(r,e,t,n,o)}var ct=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??_n,this.maxDigestLength=s}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 n=this.encode(e);return n instanceof Uint8Array?Qt(n,this.code,t?.truncate):n.then(o=>Qt(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Qt(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 ie(e,r)}function Xt(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Vn=ut({name:"sha2-256",code:18,encode:Xt("SHA-256")}),zn=ut({name:"sha2-512",code:19,encode:Xt("SHA-512")});function Kt(r,e){let{bytes:t,version:n}=r;return n===0?Mn(t,ht(r),e??L.encoder):qn(t,ht(r),e??G.encoder)}var Yt=new WeakMap;function ht(r){let e=Yt.get(r);if(e==null){let t=new Map;return Yt.set(r,t),t}return e}var T=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=X(o),this["/"]=this.bytes}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!==ge)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==$n)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,n=ie(e,t);return r.createV1(this.code,n)}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 n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Ht(e.multihash,n.multihash)}toString(e){return Kt(this,e)}toJSON(){return{"/":Kt(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:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Zt(n,o,s.bytes))}else if(t[jn]===!0){let{version:n,multihash:o,code:s}=t,i=K(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ge)throw new Error(`Version 0 CID must use dag-pb (code: ${ge}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Zt(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ge,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=D(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new se(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[h,f]=me(e.subarray(t));return t+=f,h},o=n(),s=ge;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,c=n(),a=n(),u=t+a,l=u-i;return{version:o,codec:s,multihashCode:c,digestSize:a,multihashSize:l,size:u}}static parse(e,t){let[n,o]=Fn(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ht(s).set(n,e),s}};function Fn(r,e){switch(r[0]){case"Q":{let t=e??L;return[L.prefix,t.decode(`${L.prefix}${r}`)]}case L.prefix:{let t=e??L;return[L.prefix,t.decode(r)]}case G.prefix:{let t=e??G;return[G.prefix,t.decode(r)]}case de.prefix:{let t=e??de;return[de.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 Mn(r,e,t){let{prefix:n}=t;if(n!==L.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function qn(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var ge=112,$n=18;function Zt(r,e,t){let n=oe(r),o=n+oe(e),s=new Uint8Array(o+t.byteLength);return ne(r,s,0),ne(e,s,n),s.set(t,o),s}var jn=Symbol.for("@ipld/js-cid/CID");var be={...st,...Ke,...ot,...Je,...Xe,...Ze,...et,...tt,...nt,...Ye},ci={...lt,...at};function tr(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var er=tr("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ft=tr("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=V(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),kn={utf8:er,"utf-8":er,hex:be.base16,latin1:ft,ascii:ft,binary:ft,...be},Te=kn;function W(r,e="utf8"){let t=Te[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Ae=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}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,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,c=this.peekChar();if(c===void 0)return;let a=c==="0",u=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let f=Number.parseInt(h,e);if(!Number.isNaN(f))return f});if(l===void 0)break;if(s*=e,s+=l,s>u||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&a&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[c]=e(s.subarray(0,i));return t.set(s.subarray(0,c),16-c),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Hn=45,Gn=15,Pe=new Ae;function rr(r){if(!(r.length>Gn))return Pe.new(r).parseWith(()=>Pe.readIPv4Addr())}function nr(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Hn))return Pe.new(r).parseWith(()=>Pe.readIPv6Addr())}function Se(r){return!!rr(r)}function or(r){return!!nr(r)}var Wn=Math.pow(2,7),Qn=Math.pow(2,14),Jn=Math.pow(2,21),dt=Math.pow(2,28),pt=Math.pow(2,35),mt=Math.pow(2,42),gt=Math.pow(2,49),g=128,E=127;function ae(r){if(r<Wn)return 1;if(r<Qn)return 2;if(r<Jn)return 3;if(r<dt)return 4;if(r<pt)return 5;if(r<mt)return 6;if(r<gt)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function bt(r,e,t=0){switch(ae(r)){case 8:e[t++]=r&255|g,r/=128;case 7:e[t++]=r&255|g,r/=128;case 6:e[t++]=r&255|g,r/=128;case 5:e[t++]=r&255|g,r/=128;case 4:e[t++]=r&255|g,r>>>=7;case 3:e[t++]=r&255|g,r>>>=7;case 2:e[t++]=r&255|g,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Xn(r,e){let t=r[e],n=0;if(n+=t&E,t<g||(t=r[e+1],n+=(t&E)<<7,t<g)||(t=r[e+2],n+=(t&E)<<14,t<g)||(t=r[e+3],n+=(t&E)<<21,t<g)||(t=r[e+4],n+=(t&E)*dt,t<g)||(t=r[e+5],n+=(t&E)*pt,t<g)||(t=r[e+6],n+=(t&E)*mt,t<g)||(t=r[e+7],n+=(t&E)*gt,t<g))return n;throw new RangeError("Could not decode varint")}function Kn(r,e){let t=r.get(e),n=0;if(n+=t&E,t<g||(t=r.get(e+1),n+=(t&E)<<7,t<g)||(t=r.get(e+2),n+=(t&E)<<14,t<g)||(t=r.get(e+3),n+=(t&E)<<21,t<g)||(t=r.get(e+4),n+=(t&E)*dt,t<g)||(t=r.get(e+5),n+=(t&E)*pt,t<g)||(t=r.get(e+6),n+=(t&E)*mt,t<g)||(t=r.get(e+7),n+=(t&E)*gt,t<g))return n;throw new RangeError("Could not decode varint")}function yt(r,e=0){return r instanceof Uint8Array?Xn(r,e):Kn(r,e)}function Zn(r){return r.buffer instanceof ArrayBuffer}function ye(r){return Zn(r)?r:r.slice()}function Q(r,e="utf8"){let t=Te[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var x=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},$=class extends Error{static name="ValidationError";name="ValidationError"},De=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Le=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function xt(r){return e=>Q(e,r)}function Et(r){return e=>W(e,r)}function ce(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Z(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function sr(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=W(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Z(n);return q([t,o],t.length+o.length)}function ir(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=G.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Z(n);return q([t,o],t.length+o.length)}function vt(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=Q(e,"base32"),o=ce(t);return`${n}:${o}`}var Ct=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new x("Invalid byte value in IP address");e[n]=o}),e},ar=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Se(t[n]),i;s&&(i=Ct(t[n]),t[n]=Q(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,Q(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(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new x("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},cr=function(r){if(r.byteLength!==4)throw new x("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},ur=function(r){if(r.byteLength!==16)throw new x("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new x(`Invalid IPv6 address "${t}"`)}};function lr(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new x(`Invalid IPv6 address "${r}"`)}}var wt=Object.values(be).map(r=>r.decoder),eo=(function(){let r=wt[0].or(wt[1]);return wt.slice(2).forEach(e=>r=r.or(e)),r})();function hr(r){return eo.decode(r)}function fr(r){return e=>r.encoder.encode(e)}function to(r){if(parseInt(r).toString()!==r)throw new $("Value must be an integer")}function ro(r){if(r<0)throw new $("Value must be a positive integer, or zero")}function no(r){return e=>{if(e>r)throw new $(`Value must be smaller than or equal to ${r}`)}}function oo(...r){return e=>{for(let t of r)t(e)}}var we=oo(to,ro,no(65535));var w=-1,It=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 Le(`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(n=>{this.protocolsByName.delete(n)}))}},j=new It,Go=[{code:4,name:"ip4",size:32,valueToBytes:Ct,bytesToValue:cr,validate:r=>{if(!Se(r))throw new $(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Z,bytesToValue:ce,validate:we},{code:273,name:"udp",size:16,valueToBytes:Z,bytesToValue:ce,validate:we},{code:33,name:"dccp",size:16,valueToBytes:Z,bytesToValue:ce,validate:we},{code:41,name:"ip6",size:128,valueToBytes:ar,bytesToValue:ur,stringToValue:lr,validate:r=>{if(!or(r))throw new $(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:w},{code:43,name:"ipcidr",size:8,bytesToValue:xt("base10"),valueToBytes:Et("base10")},{code:53,name:"dns",size:w},{code:54,name:"dns4",size:w},{code:55,name:"dns6",size:w},{code:56,name:"dnsaddr",size:w},{code:132,name:"sctp",size:16,valueToBytes:Z,bytesToValue:ce,validate:we},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:w,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:w,bytesToValue:xt("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Et("base58btc")(r):T.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:vt,valueToBytes:sr},{code:445,name:"onion3",size:296,bytesToValue:vt,valueToBytes:ir},{code:446,name:"garlic64",size:w},{code:447,name:"garlic32",size:w},{code:448,name:"tls"},{code:449,name:"sni",size:w},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:w,bytesToValue:fr(rt),valueToBytes:hr},{code:480,name:"http"},{code:481,name:"http-path",size:w,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:w}];Go.forEach(r=>{j.addProtocol(r)});function dr(r){let e=[],t=0;for(;t<r.length;){let n=yt(r,t),o=j.getProtocol(n),s=ae(n),i=Wo(o,r,t+s),c=0;i>0&&o.size===w&&(c=ae(i));let a=s+c+i,u={code:n,name:o.name,bytes:ye(r.subarray(t,t+a))};if(i>0){let l=t+s+c,h=r.subarray(l,l+i);u.value=o.bytesToValue?.(h)??Q(h)}e.push(u),t+=a}return e}function pr(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=j.getProtocol(n.code),s=ae(n.code),i,c=0,a=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??W(n.value),c=i.byteLength,o.size===w&&(a=ae(c)));let u=new Uint8Array(s+a+c),l=0;bt(n.code,u,l),l+=s,i!=null&&(o.size===w&&(bt(c,u,l),l+=a),u.set(i,l)),n.bytes=u}t.push(n.bytes),e+=n.bytes.byteLength}return q(t,e)}function mr(r){if(r.charAt(0)!=="/")throw new x('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let c=s===r.length-1;if(i==="/"||c){let a=j.getProtocol(o);if(t==="protocol"){if(a.size==null||a.size===0){e.push({code:a.code,name:a.name}),n="",o="",t="protocol";continue}else if(c)throw new x(`Component ${o} was missing value`);t="value"}else if(t==="value"){let u={code:a.code,name:a.name};if(a.size!=null&&a.size!==0){if(n==="")throw new x(`Component ${o} was missing value`);u.value=a.stringToValue?.(n)??n}e.push(u),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new x("Incomplete multiaddr");return e}function gr(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=j.getProtocol(e.code);if(t==null)throw new x(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Wo(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:yt(e,t)}var Qo=Symbol.for("nodejs.util.inspect.custom"),Tt=Symbol.for("@multiformats/multiaddr");function Jo(r){if(r==null&&(r="/"),br(r))return r.getComponents();if(r instanceof Uint8Array)return dr(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),mr(r);if(Array.isArray(r))return r;throw new x("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ne=class r{[Tt]=!0;#e;#r;#t;constructor(e="/",t={}){this.#e=Jo(e),t.validate!==!1&&Xo(this)}get bytes(){return this.#t==null&&(this.#t=pr(this.#e)),this.#t}toString(){return this.#r==null&&(this.#r=gr(this.#e)),this.#r}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new De(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return J(this.bytes,e.bytes)}[Qo](){return`Multiaddr(${this.toString()})`}};function Xo(r){r.getComponents().forEach(e=>{let t=j.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function br(r){return!!r?.[Tt]}function yr(r){return new Ne(r)}function ue(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ue=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}},le=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ue(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 Ue(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 At=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function wr(r={}){return Ko(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Ko(r,e){e=e??{};let t=e.onEnd,n=new le,o,s,i,c=ue(),a=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,d)=>{s=y=>{s=null,n.push(y);try{m(r(n))}catch(C){d(C)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=ue()})}},u=m=>s!=null?s(m):(n.push(m),o),l=m=>(n=new le,s!=null?s({error:m}):(n.push({error:m}),o)),h=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},f=m=>i?o:(i=!0,m!=null?l(m):u({done:!0})),p=()=>(n=new le,f(),{done:!0}),v=m=>(f(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:a,return:p,throw:v,push:h,end:f,get readableLength(){return n.size},onEmpty:async m=>{let d=m?.signal;if(d?.throwIfAborted(),n.isEmpty())return;let y,C;d!=null&&(y=new Promise((A,P)=>{C=()=>{P(new At)},d.addEventListener("abort",C)}));try{await Promise.race([c.promise,y])}finally{C!=null&&d!=null&&d?.removeEventListener("abort",C)}}},t==null)return o;let U=o;return o={[Symbol.asyncIterator](){return this},next(){return U.next()},throw(m){return U.throw(m),t!=null&&(t(m),t=void 0),{done:!0}},return(){return U.return(),t!=null&&(t(),t=void 0),{done:!0}},push:h,end(m){return U.end(m),t!=null&&(t(m),t=void 0),o},get readableLength(){return U.readableLength},onEmpty:m=>U.onEmpty(m)},o}var Pt=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},xr=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function St(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,c,a,l=new Promise((h,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){f(xr(i));return}if(i&&(a=()=>{f(xr(i))},i.addEventListener("abort",a,{once:!0})),r.then(h,f),t===Number.POSITIVE_INFINITY)return;let p=new Pt;c=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(v){f(v)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?h():o instanceof Error?f(o):(p.message=o??`Promise timed out after ${t} milliseconds`,f(p))},t)}).finally(()=>{l.clear(),a&&i&&i.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,c),c=void 0},l}var Yo=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 Zo(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!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 c=[e].flat(),a=[],{addListener:u,removeListener:l}=Yo(r),h=async(...p)=>{let v=t.multiArgs?p:p[0];if(t.filter)try{if(!await t.filter(v))return}catch(U){n(),i(U);return}a.push(v),t.count===a.length&&(n(),s(a))},f=(...p)=>{n(),i(t.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of c)l(p,h);for(let p of t.rejectionEvents)c.includes(p)||l(p,f)};for(let p of c)u(p,h);for(let p of t.rejectionEvents)c.includes(p)||u(p,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(a)});if(o.cancel=n,typeof t.timeout=="number"){let s=St(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Oe(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=Zo(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Dt(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Re=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function es(r){return r.reason}async function Er(r,e,t){if(e==null)return r;let n=t?.translateError??es;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Be=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=ue(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new F)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function ts(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var _e=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=ts(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new F),this.cleanup())}async join(e){let t=new Be(e);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 Er(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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 Ve=class extends Ce{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,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=Dt(this.emitEmpty.bind(this),1),this.emitIdle=Dt(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;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 Re;let n=new _e(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new F)}),this.clear()}async onEmpty(e){this.size!==0&&await Oe(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Oe(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Oe(this,"idle",e)}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=wr({objectMode:!0}),n=a=>{a!=null?this.abort():this.clear(),t.end(a)},o=a=>{a.detail!=null&&t.push(a.detail)},s=a=>{n(a.detail.error)},i=()=>{n()},c=()=>{n(new F("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",c);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",c),n()}}};function he(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}async function*xe(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var ze=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*fe(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),te(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new ze("Incoming message too long");let i=o.split(t);o=i.pop()??"";for(let c=0;c<i.length;c++)yield JSON.parse(i[c])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var ee=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},N=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};var Fe={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},Me=class{url;started;httpQueue;shutDownController;timeout;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(e,t){this.log=e.logger.forComponent("delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new Ve({concurrency:t.concurrentRequests??Fe.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??Fe.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.cacheName=t.cacheName??Fe.cacheName,this.cacheTTL=t.cacheTTL??Fe.cacheTTL}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&this.log("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){this.log("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers(),c=0;this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.url}routing/v1/providers/${e}`);this.#r(a,t.filterAddrs,t.filterProtocols);let u=await this.#t(a.toString(),{headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:o});if(!u.ok){if(u.status===404)return;throw u.status===422?new ee("Request does not conform to schema or semantic constraints"):new N(`Unexpected status code: ${u.status}`)}let l=u.headers.get("Content-Type");if(l==null)throw new N("No Content-Type header received");if(u.body==null){if(l!=="application/x-ndjson")throw new N("Routing response had no body");return}if(l.startsWith("application/json")){let f=(await u.json()).Providers??[];for(let p of f){let v=this.#e(p);v!=null&&(c++,yield v)}}else if(l.includes("application/x-ndjson"))for await(let h of fe(xe(u.body))){let f=this.#e(h);f!=null&&(c++,yield f)}else throw new N(`Unsupported Content-Type: ${l}`)}finally{o.clear(),i.resolve(),this.log("getProviders finished found %d providers for %c",c,e)}}async*getPeers(e,t={}){this.log("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let c=new URL(`${this.url}routing/v1/peers/${e}`);this.#r(c,t.filterAddrs,t.filterProtocols);let a=await this.#t(c.toString(),{headers:{Accept:"application/x-ndjson"},signal:o});if(a.status===404)return;if(a.status===422)throw new ee("Request does not conform to schema or semantic constraints");if(a.body==null)throw new N("Routing response had no body");if(a.headers.get("Content-Type")?.startsWith("application/json")){let h=(await a.json()).Peers??[];for(let f of h){let p=this.#e(f);p!=null&&(yield p)}}else for await(let l of fe(xe(a.body))){let h=this.#e(l);h!=null&&(yield h)}}catch(c){this.log.error("getPeers errored - %e",c)}finally{o.clear(),i.resolve(),this.log("getPeers finished: %c",e)}}async*getClosestPeers(e,t={}){let n;if(T.asCID(e)===e||e instanceof T)n=e.toV1().toString();else throw new ve("Key must be CID");this.log("getClosestPeers starts: %s",n);let o=AbortSignal.timeout(this.timeout),s=he([this.shutDownController.signal,o,t.signal]);let i=Promise.withResolvers(),c=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),c.promise));try{await i.promise;let a=new URL(`${this.url}routing/v1/dht/closest/peers/${n}`);this.#r(a,t.filterAddrs,t.filterProtocols);let u=await this.#t(a.toString(),{headers:{Accept:"application/x-ndjson"},signal:s});if(u.status===404)return;if(u.status===422)throw new ee("Request does not conform to schema or semantic constraints");if(u.body==null)throw new N("Routing response had no body");if(u.headers.get("Content-Type")?.startsWith("application/json")){let f=(await u.json()).Peers??[];for(let p of f){let v=this.#e(p);v!=null&&(yield v)}}else for await(let h of fe(xe(u.body))){let f=this.#e(h);f!=null&&(yield f)}}catch(a){this.log.error("getClosestPeers errored - %e",a)}finally{s.clear(),c.resolve(),this.log("getClosestPeers finished: %s",n)}}async getIPNS(e,t={}){this.log("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=he([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));let c=`${this.url}routing/v1/ipns/${e}`;try{await s.promise;let a=await this.#t(c,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(this.log("getIPNS GET %s %d",c,a.status),a.status===404)throw new M("No matching records found");if(a.status===422)throw new ee("Request does not conform to schema or semantic constraints");if(!a.ok)throw new N(`Unexpected status code: ${a.status}`);let u=a.headers.get("Content-Type");if(u==null||!u.includes("application/vnd.ipfs.ipns-record"))throw new M("No matching records found");if(a.body==null)throw new N("GET ipns response had no body");let l=await a.arrayBuffer();return new Uint8Array(l,0,l.byteLength)}catch(a){throw this.log.error("getIPNS GET %s error - %e",c,a),a}finally{o.clear(),i.resolve(),this.log("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=he([this.shutDownController.signal,o,n.signal]);let i=Promise.withResolvers(),c=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),c.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await i.promise;let u=await this.#t(a,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:ye(t),signal:s});if(this.log("putIPNS PUT %s %d",a,u.status),u.status!==200)throw new N("PUT ipns response had status other than 200")}catch(u){throw this.log.error("putIPNS PUT %s error - %e",a,u.stack),u}finally{s.clear(),c.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(yr)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:T.createV1(114,rs(e.ID)),Addrs:n,Protocols:t}}catch(t){this.log.error("could not conform record to peer schema - %e",t)}}#r(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#t(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let a=await this.cache?.match(e);if(a!=null){if(parseInt(a.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",o),this.logResponse(a),a;this.log("evicting cached response for %s",o),await this.cache?.delete(e)}else this.cache!=null&&this.log("cache miss for %s",o)}let s=this.inFlightRequests.get(o);if(s!=null){let a=await s;return this.log("deduplicating outgoing request for %s",o),a.clone()}this.log("outgoing request:"),this.logRequest(e,t);let i=fetch(e,t).then(async a=>{if(this.log("incoming response:"),this.logResponse(a),this.cache!=null&&a.ok&&n==="GET"){let u=Date.now()+this.cacheTTL,l=new Headers(a.headers);l.set("x-cache-expires",u.toString());let h=new Response(a.clone().body,{status:a.status,statusText:a.statusText,headers:l});await this.cache.put(e,h)}return a}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(e,t){let n=new Headers(t.headers);this.log("%s %s HTTP/1.1",t.method??"GET",e);for(let[o,s]of n.entries())this.log("%s: %s",o,s)}logResponse(e){this.log("HTTP/1.1 %d %s",e.status,e.statusText);for(let[t,n]of e.headers.entries())this.log("%s: %s",t,n)}};function rs(r){let e=L.baseDecode(r);return K(e)}function ns(r){return r[Symbol.asyncIterator]!=null}function os(r){if(ns(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var vr=os;function ss(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Cr=ss;function is(r){return r[Symbol.asyncIterator]!=null}function as(r,e){let t=0;if(is(r))return(async function*(){for await(let a of r)yield e(a,t++)})();let n=Cr(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let a of n)yield e(a,t++)})();let c=e;return(function*(){yield i;for(let a of n)yield c(a,t++)})()}var Ir=as;function Tr(r){return e=>new Me(e,r)}var qe=W("/ipns/");function Ar(r){return J(r.subarray(0,qe.byteLength),qe)}var $e=class{name="delegated-http-router";client;constructor(e,t){this.client=Tr(t)(e)}async provide(e,t){}async cancelReprovide(e,t){}async*findProviders(e,t){yield*Ir(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols,routing:"delegated-http-routing"}))}async put(e,t,n){if(!Ar(e))return;let o=K(e.slice(qe.length)),s=T.createV1(114,o);await this.client.putIPNS(s,t,n)}async get(e,t){if(!Ar(e))throw new M("Not found");let n=K(e.slice(qe.length)),o=T.createV1(114,n);try{return await this.client.getIPNS(o,t)}catch(s){throw s.name==="BadResponseError"?new M("Not found"):s}}async findPeer(e,t){let n=await vr(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new M("Not found")}async*getClosestPeers(e,t){}toString(){return`DelegatedHTTPRouter(${this.client.url})`}};function Lt(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}function cs(r){return e=>new $e(e,Lt(r))}return Nr(us);})();
|
|
3
3
|
return HeliaDelegatedRoutingClient}));
|
|
4
4
|
//# sourceMappingURL=index.min.js.map
|