helia 7.1.12-bbf05cb7 → 7.1.13

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 CHANGED
@@ -110,7 +110,7 @@ ${e}`)}`:n!=null?`${n.split(`
110
110
  ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function QV(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function t_(r,e=""){if(QV(r)){let t=Jk(r,e);return r.errors.length>0?(e=`${e} `,t+=`
111
111
  ${e}${r.errors.map(n=>`${t_(n,`${e}`)}`).join(`
112
112
  ${e}`)}`):t+=`
113
- ${e}[Error list was empty]`,t.trim()}return Jk(r,e)}function ZV(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function r_(r){return{forComponent(e){return n_(e,r)}}}function n_(r,e){let t=ZV(`${r}:trace`);return et.enabled(`${r}:trace`)&&et.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=et(`${r}:trace`,e)),Object.assign(et(r,e),{error:et(`${r}:error`,e),trace:t,newScope:n=>n_(`${r}:${n}`,e)})}function e_(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Xo=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,bytes:o}of e)await this.put(n,o,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};function JV(r){return typeof r?.then=="function"}var Cf=class extends Xo{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let o;if(t instanceof Uint8Array)o=[t];else{let s=$o(t);if(JV(s))return s.then(i=>this._put(e,i,n));o=s}return this._put(e,o,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(xt.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(xt.encode(e.multihash.bytes));if(n==null)throw new kr;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(xt.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(xt.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:$.createV1(po,Ce(xt.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};var _Ae=Ja("blockstore:core:tiered");var o_="SHARDING";var XAe=new Ve(o_);var uTe=Ja("datastore:core:tiered");var bg=class{lock;child;pins;routing;started;constructor(e,t,n,o={}){this.child=e,this.pins=t,this.routing=n,this.lock=cd({singleProcess:o.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await yt(this.child),this.started=!0}async stop(){await Dt(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new fu("Block was pinned - please unpin and try again");await this.routing.cancelReprovide(e,t),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany((async function*(){for await(let s of e){if(await o.pins.isPinned(s))throw new fu("Block was pinned - please unpin and try again");await o.routing.cancelReprovide(s,t),yield s}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var L7=new Ve("/version"),i_=1;async function a_(r){if(!await r.has(L7)){await r.put(L7,A(`${i_}`));return}let e=await r.get(L7),t=_(e);if(parseInt(t,10)!==i_)throw new e1("Invalid datastore version, a datastore migration may be required")}var M7={};we(M7,{code:()=>B7,createLink:()=>w_,createNode:()=>y_,decode:()=>hq,encode:()=>fq,name:()=>dq,prepare:()=>N7,validate:()=>O7});var tq=new TextDecoder;function R7(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Eg(r,e){let t;[t,e]=R7(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function c_(r,e){let t;return[t,e]=R7(r,e),[t&7,t>>3,e]}function rq(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=c_(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Eg(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Eg(r,n),e.Name=tq.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=R7(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function l_(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=c_(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Eg(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Eg(r,t),n.push(rq(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return s&&(i.Data=s),i.Links=n||[],i}var f_=new TextEncoder,u_=2**32,nq=2**31;function oq(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=kf(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=f_.encode(r.Name);t-=n.length,e.set(n,t),t=kf(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=kf(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function d_(r,e,t){return r-=e.Data.length,t.set(e.Data,r),r=kf(t,r,e.Data.length)-1,t[r]=10,r}function h_(r,e){let t=iq(r),n=new Uint8Array(t),o=t,s=e?.fieldOrder==="data-first"?e.fieldOrder:"links-first";if(r.Data&&s==="links-first"&&(o=d_(o,r,n)),r.Links)for(let i=r.Links.length-1;i>=0;i--){let a=oq(r.Links[i],n.subarray(0,o));o-=a,o=kf(n,o,a)-1,n[o]=18}return r.Data&&s==="data-first"&&(o=d_(o,r,n)),n}function sq(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+yl(t)}if(typeof r.Name=="string"){let t=f_.encode(r.Name).length;e+=1+t+yl(t)}return typeof r.Tsize=="number"&&(e+=1+yl(r.Tsize)),e}function iq(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+yl(t)}if(r.Links)for(let t of r.Links){let n=sq(t);e+=1+n+yl(n)}return e}function kf(r,e,t){e-=yl(t);let n=e;for(;t>=nq;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function yl(r){return r%2===0&&r++,Math.floor((aq(r)+6)/7)}function aq(r){let e=0;return r>=u_&&(r=Math.floor(r/u_),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+cq[r]}var cq=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var lq=["Data","Links"],uq=["Hash","Name","Tsize"],D7=new TextEncoder;function m_(r,e){if(r===e)return 0;let t=r.Name?D7.encode(r.Name):[],n=e.Name?D7.encode(e.Name):[],o=t.length,s=n.length;for(let i=0,a=Math.min(o,s);i<a;++i)if(t[i]!==n[i]){o=t[i],s=n[i];break}return o<s?-1:s<o?1:0}function p_(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function g_(r){if(typeof r.asCID=="object"){let t=$.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=$.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=$.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=$.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function N7(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=D7.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(g_),e.Links.sort(m_);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function O7(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!p_(r,lq))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!p_(t,uq))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&m_(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function y_(r,e=[]){return N7({Data:r,Links:e})}function w_(r,e,t){return g_({Hash:t,Name:r,Tsize:e})}function b_(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var dq="dag-pb",B7=112;function fq(r,e){O7(r);let t={};return r.Links&&(t.Links=r.Links.map(n=>{let o={};return n.Hash&&(o.Hash=n.Hash.bytes),n.Name!==void 0&&(o.Name=n.Name),n.Tsize!==void 0&&(o.Tsize=n.Tsize),o})),r.Data&&(t.Data=r.Data),h_(t,e)}function hq(r){let e=b_(r),t=l_(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=$.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}function E_(r=[],e){let t={[B7]:M7,[po]:ii};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);hs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Vl(`Could not load codec for ${n}`)}}function x_(r=[],e){let t={};return r=[y3(),b3(),$l(),...r],r.forEach(n=>{t[n.type]=n,t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);hs(s)?o=await s:o=s,t[o.type]=o,t[o.code]=o}if(o!=null)return o;throw new ql(`Could not load crypto for ${o}`)}}function v_(r=[],e){let t={[je.code]:je,[st.code]:st};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);hs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Hl(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var xg=0,wl=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},vg=class extends Xo{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}async*get(e,t){if(e.multihash.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new kr;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return t?.signal?.throwIfAborted(),!0}return this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};var pq=128,bl=class{child;getHasher;log;logger;blockBrokers;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.blockBrokers=e.blockBrokers,this.child=new vg(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??pq}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new P("blocks:put:duplicate",e)),e):(n.onProgress?.(new P("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new P("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Hr(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new P("blocks:put-many:duplicate",s)),!i}),o=_c(n,async({cid:s})=>{t.onProgress?.(new P("blocks:put-many:providers:notify",s)),await Promise.all(this.blockBrokers.map(async i=>i.announce?.(s,t)))});t.onProgress?.(new P("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){let n=await this.child.has(e,t),o=t.offline===!0;if(!n){if(o)throw new hu("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new P("blocks:get:providers:get",e));let i=await S_(e,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new P("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),t.onProgress?.(new P("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield i;return}t.onProgress?.(new P("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new P("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(_c(e,async n=>{let o=await this.child.has(n,t),s=t.offline===!0;if(!o){if(s)throw new hu("The block was present in the blockstore and the node is running offline so cannot fetch it");let i=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new P("blocks:get-many:providers:get",n));let a=await S_(n,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new P("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new P("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new P("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new P("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany((async function*(){for await(let n of e)yield n})(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new P("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function S_(r,e,t,n){let o=gq(r,t),s=new AbortController,i=he([s.signal,n.signal]);s.signal;let a=[];for(let c of e)mq(c)&&a.push(c);if(a.length===0)throw new So(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:i,validateFn:async d=>{await o(d),n.signal?.throwIfAborted(),l=!0}});return l||(await o(u),n.signal?.throwIfAborted()),u}catch(l){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,l),l}}))}catch(c){throw new r1(c.errors,`Failed to load block for ${r}`)}finally{s.abort(),i.clear()}}function mq(r){return typeof r.retrieve=="function"}var gq=(r,e)=>{if(e==null)throw new v(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t,{truncate:r.multihash.digest.byteLength});if(hs(o)?n=await o:n=o,!oe(n.digest,r.multihash.digest))throw new ya("Hash of downloaded block did not match multihash from passed CID")}};var Sg=class extends bl{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async addPeer(e,t){await Promise.all(this.blockBrokers.map(n=>n.addPeer(e,t)))}async put(e,t,n={}){let o=he([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=he([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=he([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=he([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var Ag=class extends bl{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await yt(this.child,...this.blockBrokers),this.started=!0}async stop(){await Dt(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new So("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(t)).filter(o=>o!=null);if(n.length===0)throw new So(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new Sg({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var T_="/pin/",A_="/pinned-block/",U7=cr;function Tg(r){return r.version===0&&(r=r.toV1()),new Ve(`${T_}${r.toString(U7)}`)}var Ig=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=Tg(e);if(await this.datastore.has(n))throw new Jh("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new v("Depth must be greater than or equal to 0");let s=(t.walker??U4())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of s.walk(e,{...t,depth:o})){let c=a.block.cid;await this.#e(c,l=>l.pinnedBy.find(u=>oe(u,e.bytes))!=null?!1:(l.pinCount++,l.pinnedBy.push(e.bytes),!0),t),yield c}let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ti(i),t)}async#e(e,t,n){let o=new Ve(`${A_}${U7.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=An(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ti(s),n),n.onProgress?.(new P("helia:pin:add",e))}}async*rm(e,t={}){let n=Tg(e),o=await this.datastore.get(n,t),s=An(o);await this.datastore.delete(n,t);let i=(t.walker??U4())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of i.walk(e,{...t,depth:s.depth})){let c=a.block.cid;await this.#e(c,l=>(l.pinCount--,l.pinnedBy=l.pinnedBy.filter(u=>oe(u,e.bytes)),!0),{...t,depth:s.depth}),yield c}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:T_+(e.cid!=null?`${e.cid.toString(cr)}`:"")},e)){let o=$.parse(t.toString().substring(5),cr),s=An(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new Ve(`${A_}${U7.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=Tg(e),o=await this.datastore.get(n,t);return An(o)}async setMetadata(e,t,n){let o=Tg(e),s=await this.datastore.get(o,n),i=An(s);i.metadata=t??{},await this.datastore.put(o,Ti(i),n)}};var yq=5,Cg=class{name;log;routers;providerLookupConcurrency;constructor(e,t){this.name="helia",this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??yq,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await yt(...this.routers)}async stop(){await Dt(...this.routers)}hasRouter(e){return this.routers.findIndex(t=>t.name===e)!==-1}addRouter(e){this.routers.push(e)}async*findProviders(e,t={}){if(this.routers.length===0)throw new ns("No content routers available");let n=0,o=[],s=this;async function*i(u){let d=0,f=u.map(async function*(p){let g=0;t?.onProgress?.(new P("helia:routing:find-providers:start",{router:p.name,cid:e}));try{for await(let y of p.findProviders(e,t))g++,t?.onProgress?.(new P("helia:routing:find-providers:provider",{router:p.name,cid:e,provider:y})),yield y}catch(y){o.push(y)}finally{s.log("router %s found %d providers for %c",p.name,g,e),t?.onProgress?.(new P("helia:routing:find-providers:end",{router:p.name,cid:e,found:g})),d++,d===u.length&&h.size===0&&h.emitIdle()}}),h=new ht({concurrency:s.providerLookupConcurrency});for await(let p of hr(h.toGenerator(),...f))if(p!=null){if(p.multiaddrs.length===0){if(h.queue.find(g=>g.options.peer.equals(p.id))!=null)continue;h.add(async()=>{try{let g=await s.findPeer(p.id,t);return g.multiaddrs.length===0?null:{...g,protocols:p.protocols,router:p.router,fallback:p.fallback}}catch(g){return s.log.error("could not load multiaddrs for peer %p - %e",p.id,g),null}},{peer:p.id,signal:t.signal}).catch(g=>{s.log.error("could not load multiaddrs for peer %p - %e",p.id,g)});continue}n++,yield p}}let a=ua(this.routers,"findProviders"),c=a.filter(u=>u.capabilities==null||!u.capabilities().includes("fallback")),l=a.filter(u=>u.capabilities?.().includes("fallback")===!0);this.log("findProviders for %c start using routers %s",e,c.map(u=>u.name).join(", ")),yield*i(c),l.length>0&&(this.log("findProviders for %c using fallback routers %s",e,l.map(u=>u.name).join(", ")),yield*i(l)),this.log("findProviders finished, found %d providers for %c",n,e)}async provide(e,t={}){if(this.routers.length===0)throw new ns("No content routers available");await Promise.all(ua(this.routers,"provide").map(async n=>{t?.onProgress?.(new P("helia:routing:provide:start",{router:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new P("helia:routing:provide:end",{router:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(ua(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new P("helia:routing:cancel-reprovide:start",{router:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new P("helia:routing:cancel-reprovide:end",{router:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(ua(this.routers,"put").map(async o=>{n?.onProgress?.(new P("helia:routing:put:start",{router:o.name,key:e,value:t})),await o.put(e,t,n),n?.onProgress?.(new P("helia:routing:put:end",{router:o.name,key:e,value:t}))}))}async get(e,t){let n=[],o,s=new AbortController,i=he([s.signal,t?.signal]);try{o=await Promise.any(ua(this.routers,"get").map(async a=>{t?.onProgress?.(new P("helia:routing:get:start",{router:a.name,key:e}));try{return await a.get(e,{...t,signal:i})}catch(c){throw this.log("router %s failed with %e",a.name,c),n.push(c),c}finally{t?.onProgress?.(new P("helia:routing:get:end",{router:a.name,key:e}))}}))}catch{}finally{s.abort(),i.clear()}if(o==null)throw new t1(n,`Failed to get value key ${_(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new ns("No peer routers available");let n=new AbortController,o=he([n.signal,t?.signal]);let s=this,i=hr(...ua(this.routers,"findPeer").map(a=>(async function*(){t?.onProgress?.(new P("helia:routing:find-peer:start",{router:a.name,peerId:e}));try{yield await a.findPeer(e,{...t,signal:o})}catch(c){s.log.error(c)}finally{t?.onProgress?.(new P("helia:routing:find-peer:end",{router:a.name,peerId:e}))}})()));try{for await(let a of i)if(a!=null)return a}finally{n.abort(),o.clear()}throw new Re("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new ns("No peer routers available");for await(let n of hr(...ua(this.routers,"getClosestPeers").map(async function*(o){t?.onProgress?.(new P("helia:routing:get-closest-peers:start",{router:o.name,key:e}));try{yield*o.getClosestPeers(e,t)}finally{t?.onProgress?.(new P("helia:routing:get-closest-peers:end",{router:o.name,key:e}))}})))n!=null&&(yield n)}};function ua(r,e){return r.filter(t=>t[e]!=null)}var kg=class{info;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;getCrypto;dns;keychain;metrics;status;log;blockBrokers;mixins;components;constructor(e){this.info={name:e.name,version:e.version},this.logger=e.logger??r_(),this.log=this.logger.forComponent("helia"),this.getHasher=v_(e.hashers,e.loadHasher),this.getCodec=E_(e.codecs,e.loadCodec),this.getCrypto=x_(e.cryptos,e.loadCrypto),this.dns=e.dns??Xm(),this.metrics=e.metrics,this.events=new ge,this.status="stopped",this.mixins=[],this.components={blockstore:e.blockstore??new Cf,datastore:e.datastore??new Qi,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,getCrypto:this.getCrypto,dns:this.dns,metrics:this.metrics,...e.components??{}},this.keychain=this.components.keychain=Zk()(this.components),this.routing=this.components.routing=new Cg(this.components,{routers:(e.routers??[]).flatMap(n=>(typeof n=="function"&&(n=n(this.components)),[n])),providerLookupConcurrency:e.providerLookupConcurrency}),this.blockBrokers=this.components.blockBrokers=(e.blockBrokers??[]).map(n=>(typeof n=="function"&&(n=n(this.components)),n));let t=new Ag(this.components,e);this.pins=new Ig(this.components.datastore,t,this.getCodec),this.blockstore=new bg(t,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=this.components.datastore}hasRouter(e){return this.routing.hasRouter(e)}addRouter(e){typeof e=="function"&&(e=e(this.components)),this.routing.addRouter(e)}hasBlockBroker(e){return this.blockBrokers.findIndex(t=>t.name===e)!==-1}addBlockBroker(e){typeof e=="function"&&(e=e(this.components)),this.blockBrokers.push(e)}addMixin(e){if(this.mixins.find(t=>t.name===e.name)!=null)throw new So(`A mixin with the name "${e.name} is already present`);this.mixins.push(e)}async start(){this.status="starting",await a_(this.datastore),await yt(this.blockstore,this.datastore,this.routing,...this.blockBrokers);for(let e of this.mixins)await e.start?.(this);return this.status="started",this.events.dispatchEvent(new CustomEvent("start",{detail:this})),this}async stop(){this.status="stopping";for(let e of this.mixins)await e.stop?.(this);return await Dt(this.blockstore,this.datastore,this.routing,...this.blockBrokers),this.status="stopped",this.events.dispatchEvent(new CustomEvent("stop",{detail:this})),this}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Cr(o.deleteMany((async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new P("helia:gc:deleted",s))}catch(i){n.log.error("error during gc - %e",i),e.onProgress?.(new P("helia:gc:error",i))}})()))}finally{t()}this.log("gc finished")}};var I_="7.1.12-bbf05cb7",C_="helia";function wq(r={}){return Bx($k(ov(k_({...r,codecs:[A7,_7,Hf,...r.codecs??[]],hashers:[i3,...r.hashers??[]]}),r.http),r.libp2p),r.bitswap)}function k_(r={}){return new kg({name:C_,version:I_,...r})}return M_(bq);})();
113
+ ${e}[Error list was empty]`,t.trim()}return Jk(r,e)}function ZV(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function r_(r){return{forComponent(e){return n_(e,r)}}}function n_(r,e){let t=ZV(`${r}:trace`);return et.enabled(`${r}:trace`)&&et.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=et(`${r}:trace`,e)),Object.assign(et(r,e),{error:et(`${r}:error`,e),trace:t,newScope:n=>n_(`${r}:${n}`,e)})}function e_(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Xo=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,bytes:o}of e)await this.put(n,o,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};function JV(r){return typeof r?.then=="function"}var Cf=class extends Xo{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let o;if(t instanceof Uint8Array)o=[t];else{let s=$o(t);if(JV(s))return s.then(i=>this._put(e,i,n));o=s}return this._put(e,o,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(xt.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(xt.encode(e.multihash.bytes));if(n==null)throw new kr;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(xt.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(xt.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:$.createV1(po,Ce(xt.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};var _Ae=Ja("blockstore:core:tiered");var o_="SHARDING";var XAe=new Ve(o_);var uTe=Ja("datastore:core:tiered");var bg=class{lock;child;pins;routing;started;constructor(e,t,n,o={}){this.child=e,this.pins=t,this.routing=n,this.lock=cd({singleProcess:o.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await yt(this.child),this.started=!0}async stop(){await Dt(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new fu("Block was pinned - please unpin and try again");await this.routing.cancelReprovide(e,t),await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany((async function*(){for await(let s of e){if(await o.pins.isPinned(s))throw new fu("Block was pinned - please unpin and try again");await o.routing.cancelReprovide(s,t),yield s}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var L7=new Ve("/version"),i_=1;async function a_(r){if(!await r.has(L7)){await r.put(L7,A(`${i_}`));return}let e=await r.get(L7),t=_(e);if(parseInt(t,10)!==i_)throw new e1("Invalid datastore version, a datastore migration may be required")}var M7={};we(M7,{code:()=>B7,createLink:()=>w_,createNode:()=>y_,decode:()=>hq,encode:()=>fq,name:()=>dq,prepare:()=>N7,validate:()=>O7});var tq=new TextDecoder;function R7(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Eg(r,e){let t;[t,e]=R7(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function c_(r,e){let t;return[t,e]=R7(r,e),[t&7,t>>3,e]}function rq(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=c_(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Eg(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Eg(r,n),e.Name=tq.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=R7(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function l_(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=c_(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Eg(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Eg(r,t),n.push(rq(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return s&&(i.Data=s),i.Links=n||[],i}var f_=new TextEncoder,u_=2**32,nq=2**31;function oq(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=kf(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=f_.encode(r.Name);t-=n.length,e.set(n,t),t=kf(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=kf(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function d_(r,e,t){return r-=e.Data.length,t.set(e.Data,r),r=kf(t,r,e.Data.length)-1,t[r]=10,r}function h_(r,e){let t=iq(r),n=new Uint8Array(t),o=t,s=e?.fieldOrder==="data-first"?e.fieldOrder:"links-first";if(r.Data&&s==="links-first"&&(o=d_(o,r,n)),r.Links)for(let i=r.Links.length-1;i>=0;i--){let a=oq(r.Links[i],n.subarray(0,o));o-=a,o=kf(n,o,a)-1,n[o]=18}return r.Data&&s==="data-first"&&(o=d_(o,r,n)),n}function sq(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+yl(t)}if(typeof r.Name=="string"){let t=f_.encode(r.Name).length;e+=1+t+yl(t)}return typeof r.Tsize=="number"&&(e+=1+yl(r.Tsize)),e}function iq(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+yl(t)}if(r.Links)for(let t of r.Links){let n=sq(t);e+=1+n+yl(n)}return e}function kf(r,e,t){e-=yl(t);let n=e;for(;t>=nq;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function yl(r){return r%2===0&&r++,Math.floor((aq(r)+6)/7)}function aq(r){let e=0;return r>=u_&&(r=Math.floor(r/u_),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+cq[r]}var cq=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var lq=["Data","Links"],uq=["Hash","Name","Tsize"],D7=new TextEncoder;function m_(r,e){if(r===e)return 0;let t=r.Name?D7.encode(r.Name):[],n=e.Name?D7.encode(e.Name):[],o=t.length,s=n.length;for(let i=0,a=Math.min(o,s);i<a;++i)if(t[i]!==n[i]){o=t[i],s=n[i];break}return o<s?-1:s<o?1:0}function p_(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function g_(r){if(typeof r.asCID=="object"){let t=$.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=$.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=$.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=$.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function N7(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=D7.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(g_),e.Links.sort(m_);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function O7(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!p_(r,lq))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!p_(t,uq))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&m_(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function y_(r,e=[]){return N7({Data:r,Links:e})}function w_(r,e,t){return g_({Hash:t,Name:r,Tsize:e})}function b_(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var dq="dag-pb",B7=112;function fq(r,e){O7(r);let t={};return r.Links&&(t.Links=r.Links.map(n=>{let o={};return n.Hash&&(o.Hash=n.Hash.bytes),n.Name!==void 0&&(o.Name=n.Name),n.Tsize!==void 0&&(o.Tsize=n.Tsize),o})),r.Data&&(t.Data=r.Data),h_(t,e)}function hq(r){let e=b_(r),t=l_(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=$.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}function E_(r=[],e){let t={[B7]:M7,[po]:ii};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);hs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Vl(`Could not load codec for ${n}`)}}function x_(r=[],e){let t={};return r=[y3(),b3(),$l(),...r],r.forEach(n=>{t[n.type]=n,t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);hs(s)?o=await s:o=s,t[o.type]=o,t[o.code]=o}if(o!=null)return o;throw new ql(`Could not load crypto for ${o}`)}}function v_(r=[],e){let t={[je.code]:je,[st.code]:st};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);hs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Hl(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var xg=0,wl=class extends Error{static name="IdentityHashDigestTooLongError";name="IdentityHashDigestTooLongError"},vg=class extends Xo{child;maxDigestLength;constructor(e,t){super(),this.child=e,this.maxDigestLength=t?.maxDigestLength}put(e,t,n){if(e.multihash.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return n?.signal?.throwIfAborted(),e}return this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}async*get(e,t){if(e.multihash.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new kr;yield*this.child.get(e,t)}has(e,t){if(e.multihash.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);return t?.signal?.throwIfAborted(),!0}return this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===xg){if(this.maxDigestLength!=null&&e.multihash.digest.byteLength>this.maxDigestLength)throw new wl(`Identity digest too long - ${e.multihash.digest.byteLength} > this.maxDigestLength`);t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}async*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};var pq=128,bl=class{child;getHasher;log;logger;blockBrokers;constructor(e,t={}){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.blockBrokers=e.blockBrokers,this.child=new vg(e.blockstore,{maxDigestLength:t.maxIdentityHashDigestLength??pq}),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new P("blocks:put:duplicate",e)),e):(n.onProgress?.(new P("blocks:put:providers:notify",e)),await Promise.all(this.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new P("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Hr(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new P("blocks:put-many:duplicate",s)),!i}),o=_c(n,async({cid:s})=>{t.onProgress?.(new P("blocks:put-many:providers:notify",s)),await Promise.all(this.blockBrokers.map(async i=>i.announce?.(s,t)))});t.onProgress?.(new P("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){let n=await this.child.has(e,t),o=t.offline===!0;if(!n){if(o)throw new hu("The block was present in the blockstore and the node is running offline so cannot fetch it");let s=await this.getHasher(e.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new P("blocks:get:providers:get",e));let i=await S_(e,this.blockBrokers,s,{...t,log:this.log});t.onProgress?.(new P("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),t.onProgress?.(new P("blocks:get:providers:notify",e)),await Promise.all(this.blockBrokers.map(async a=>a.announce?.(e,t))),yield i;return}t.onProgress?.(new P("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new P("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(_c(e,async n=>{let o=await this.child.has(n,t),s=t.offline===!0;if(!o){if(s)throw new hu("The block was present in the blockstore and the node is running offline so cannot fetch it");let i=await this.getHasher(n.multihash.code);t?.signal?.throwIfAborted(),t.onProgress?.(new P("blocks:get-many:providers:get",n));let a=await S_(n,this.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new P("blocks:get-many:blockstore:put",n)),await this.child.put(n,a,t),t.onProgress?.(new P("blocks:get-many:providers:notify",n)),await Promise.all(this.blockBrokers.map(async c=>c.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new P("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new P("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany((async function*(){for await(let n of e)yield n})(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new P("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}};async function S_(r,e,t,n){let o=gq(r,t),s=new AbortController,i=he([s.signal,n.signal]);s.signal;let a=[];for(let c of e)mq(c)&&a.push(c);if(a.length===0)throw new So(`No block brokers capable of retrieving blocks are configured, the CID ${r} cannot be fetched from the network`);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:i,validateFn:async d=>{await o(d),n.signal?.throwIfAborted(),l=!0}});return l||(await o(u),n.signal?.throwIfAborted()),u}catch(l){throw n.log.error("could not retrieve verified block for %c from %s - %e",r,c.name,l),l}}))}catch(c){throw new r1(c.errors,`Failed to load block for ${r}`)}finally{s.abort(),i.clear()}}function mq(r){return typeof r.retrieve=="function"}var gq=(r,e)=>{if(e==null)throw new v(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t,{truncate:r.multihash.digest.byteLength});if(hs(o)?n=await o:n=o,!oe(n.digest,r.multihash.digest))throw new ya("Hash of downloaded block did not match multihash from passed CID")}};var Sg=class extends bl{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async addPeer(e,t){await Promise.all(this.blockBrokers.map(n=>n.addPeer(e,t)))}async put(e,t,n={}){let o=he([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=he([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=he([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=he([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=he([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};var Ag=class extends bl{started;constructor(e,t={}){super(e,t),this.started=!1}isStarted(){return this.started}async start(){await yt(this.child,...this.blockBrokers),this.started=!0}async stop(){await Dt(this.child,...this.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){if(this.blockBrokers.length===0)throw new So("No block brokers configured");let n=this.blockBrokers.map(o=>o.createSession?.(t)).filter(o=>o!=null);if(n.length===0)throw new So(`No configured block brokers support sessions - tried ${this.blockBrokers.map(o=>o.name).join(", ")}`);return new Sg({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}};var T_="/pin/",A_="/pinned-block/",U7=cr;function Tg(r){return r.version===0&&(r=r.toV1()),new Ve(`${T_}${r.toString(U7)}`)}var Ig=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=Tg(e);if(await this.datastore.has(n))throw new Jh("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new v("Depth must be greater than or equal to 0");let s=(t.walker??U4())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of s.walk(e,{...t,depth:o})){let c=a.block.cid;await this.#e(c,l=>l.pinnedBy.find(u=>oe(u,e.bytes))!=null?!1:(l.pinCount++,l.pinnedBy.push(e.bytes),!0),t),yield c}let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ti(i),t)}async#e(e,t,n){let o=new Ve(`${A_}${U7.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=An(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ti(s),n),n.onProgress?.(new P("helia:pin:add",e))}}async*rm(e,t={}){let n=Tg(e),o=await this.datastore.get(n,t),s=An(o);await this.datastore.delete(n,t);let i=(t.walker??U4())({blockstore:this.blockstore,getCodec:this.getCodec});for await(let a of i.walk(e,{...t,depth:s.depth})){let c=a.block.cid;await this.#e(c,l=>(l.pinCount--,l.pinnedBy=l.pinnedBy.filter(u=>oe(u,e.bytes)),!0),{...t,depth:s.depth}),yield c}}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:T_+(e.cid!=null?`${e.cid.toString(cr)}`:"")},e)){let o=$.parse(t.toString().substring(5),cr),s=An(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new Ve(`${A_}${U7.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=Tg(e),o=await this.datastore.get(n,t);return An(o)}async setMetadata(e,t,n){let o=Tg(e),s=await this.datastore.get(o,n),i=An(s);i.metadata=t??{},await this.datastore.put(o,Ti(i),n)}};var yq=5,Cg=class{name;log;routers;providerLookupConcurrency;constructor(e,t){this.name="helia",this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??yq,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await yt(...this.routers)}async stop(){await Dt(...this.routers)}hasRouter(e){return this.routers.findIndex(t=>t.name===e)!==-1}addRouter(e){this.routers.push(e)}async*findProviders(e,t={}){if(this.routers.length===0)throw new ns("No content routers available");let n=0,o=[],s=this;async function*i(u){let d=0,f=u.map(async function*(p){let g=0;t?.onProgress?.(new P("helia:routing:find-providers:start",{router:p.name,cid:e}));try{for await(let y of p.findProviders(e,t))g++,t?.onProgress?.(new P("helia:routing:find-providers:provider",{router:p.name,cid:e,provider:y})),yield y}catch(y){o.push(y)}finally{s.log("router %s found %d providers for %c",p.name,g,e),t?.onProgress?.(new P("helia:routing:find-providers:end",{router:p.name,cid:e,found:g})),d++,d===u.length&&h.size===0&&h.emitIdle()}}),h=new ht({concurrency:s.providerLookupConcurrency});for await(let p of hr(h.toGenerator(),...f))if(p!=null){if(p.multiaddrs.length===0){if(h.queue.find(g=>g.options.peer.equals(p.id))!=null)continue;h.add(async()=>{try{let g=await s.findPeer(p.id,t);return g.multiaddrs.length===0?null:{...g,protocols:p.protocols,router:p.router,fallback:p.fallback}}catch(g){return s.log.error("could not load multiaddrs for peer %p - %e",p.id,g),null}},{peer:p.id,signal:t.signal}).catch(g=>{s.log.error("could not load multiaddrs for peer %p - %e",p.id,g)});continue}n++,yield p}}let a=ua(this.routers,"findProviders"),c=a.filter(u=>u.capabilities==null||!u.capabilities().includes("fallback")),l=a.filter(u=>u.capabilities?.().includes("fallback")===!0);this.log("findProviders for %c start using routers %s",e,c.map(u=>u.name).join(", ")),yield*i(c),l.length>0&&(this.log("findProviders for %c using fallback routers %s",e,l.map(u=>u.name).join(", ")),yield*i(l)),this.log("findProviders finished, found %d providers for %c",n,e)}async provide(e,t={}){if(this.routers.length===0)throw new ns("No content routers available");await Promise.all(ua(this.routers,"provide").map(async n=>{t?.onProgress?.(new P("helia:routing:provide:start",{router:n.name,cid:e})),await n.provide(e,t),t?.onProgress?.(new P("helia:routing:provide:end",{router:n.name,cid:e}))}))}async cancelReprovide(e,t={}){await Promise.all(ua(this.routers,"cancelReprovide").map(async n=>{t?.onProgress?.(new P("helia:routing:cancel-reprovide:start",{router:n.name,cid:e})),await n.cancelReprovide(e,t),t?.onProgress?.(new P("helia:routing:cancel-reprovide:end",{router:n.name,cid:e}))}))}async put(e,t,n){await Promise.all(ua(this.routers,"put").map(async o=>{n?.onProgress?.(new P("helia:routing:put:start",{router:o.name,key:e,value:t})),await o.put(e,t,n),n?.onProgress?.(new P("helia:routing:put:end",{router:o.name,key:e,value:t}))}))}async get(e,t){let n=[],o,s=new AbortController,i=he([s.signal,t?.signal]);try{o=await Promise.any(ua(this.routers,"get").map(async a=>{t?.onProgress?.(new P("helia:routing:get:start",{router:a.name,key:e}));try{return await a.get(e,{...t,signal:i})}catch(c){throw this.log("router %s failed with %e",a.name,c),n.push(c),c}finally{t?.onProgress?.(new P("helia:routing:get:end",{router:a.name,key:e}))}}))}catch{}finally{s.abort(),i.clear()}if(o==null)throw new t1(n,`Failed to get value key ${_(e,"base58btc")}`);return o}async findPeer(e,t){if(this.routers.length===0)throw new ns("No peer routers available");let n=new AbortController,o=he([n.signal,t?.signal]);let s=this,i=hr(...ua(this.routers,"findPeer").map(a=>(async function*(){t?.onProgress?.(new P("helia:routing:find-peer:start",{router:a.name,peerId:e}));try{yield await a.findPeer(e,{...t,signal:o})}catch(c){s.log.error(c)}finally{t?.onProgress?.(new P("helia:routing:find-peer:end",{router:a.name,peerId:e}))}})()));try{for await(let a of i)if(a!=null)return a}finally{n.abort(),o.clear()}throw new Re("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new ns("No peer routers available");for await(let n of hr(...ua(this.routers,"getClosestPeers").map(async function*(o){t?.onProgress?.(new P("helia:routing:get-closest-peers:start",{router:o.name,key:e}));try{yield*o.getClosestPeers(e,t)}finally{t?.onProgress?.(new P("helia:routing:get-closest-peers:end",{router:o.name,key:e}))}})))n!=null&&(yield n)}};function ua(r,e){return r.filter(t=>t[e]!=null)}var kg=class{info;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;getCrypto;dns;keychain;metrics;status;log;blockBrokers;mixins;components;constructor(e){this.info={name:e.name,version:e.version},this.logger=e.logger??r_(),this.log=this.logger.forComponent("helia"),this.getHasher=v_(e.hashers,e.loadHasher),this.getCodec=E_(e.codecs,e.loadCodec),this.getCrypto=x_(e.cryptos,e.loadCrypto),this.dns=e.dns??Xm(),this.metrics=e.metrics,this.events=new ge,this.status="stopped",this.mixins=[],this.components={blockstore:e.blockstore??new Cf,datastore:e.datastore??new Qi,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,getCrypto:this.getCrypto,dns:this.dns,metrics:this.metrics,...e.components??{}},this.keychain=this.components.keychain=Zk()(this.components),this.routing=this.components.routing=new Cg(this.components,{routers:(e.routers??[]).flatMap(n=>(typeof n=="function"&&(n=n(this.components)),[n])),providerLookupConcurrency:e.providerLookupConcurrency}),this.blockBrokers=this.components.blockBrokers=(e.blockBrokers??[]).map(n=>(typeof n=="function"&&(n=n(this.components)),n));let t=new Ag(this.components,e);this.pins=new Ig(this.components.datastore,t,this.getCodec),this.blockstore=new bg(t,this.pins,this.routing,{holdGcLock:e.holdGcLock??!0}),this.datastore=this.components.datastore}hasRouter(e){return this.routing.hasRouter(e)}addRouter(e){typeof e=="function"&&(e=e(this.components)),this.routing.addRouter(e)}hasBlockBroker(e){return this.blockBrokers.findIndex(t=>t.name===e)!==-1}addBlockBroker(e){typeof e=="function"&&(e=e(this.components)),this.blockBrokers.push(e)}addMixin(e){if(this.mixins.find(t=>t.name===e.name)!=null)throw new So(`A mixin with the name "${e.name} is already present`);this.mixins.push(e)}async start(){this.status="starting",await a_(this.datastore),await yt(this.blockstore,this.datastore,this.routing,...this.blockBrokers);for(let e of this.mixins)await e.start?.(this);return this.status="started",this.events.dispatchEvent(new CustomEvent("start",{detail:this})),this}async stop(){this.status="stopping";for(let e of this.mixins)await e.stop?.(this);return await Dt(this.blockstore,this.datastore,this.routing,...this.blockBrokers),this.status="stopped",this.events.dispatchEvent(new CustomEvent("stop",{detail:this})),this}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Cr(o.deleteMany((async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new P("helia:gc:deleted",s))}catch(i){n.log.error("error during gc - %e",i),e.onProgress?.(new P("helia:gc:error",i))}})()))}finally{t()}this.log("gc finished")}};var I_="7.1.13",C_="helia";function wq(r={}){return Bx($k(ov(k_({...r,codecs:[A7,_7,Hf,...r.codecs??[]],hashers:[i3,...r.hashers??[]]}),r.http),r.libp2p),r.bitswap)}function k_(r={}){return new kg({name:C_,version:I_,...r})}return M_(bq);})();
114
114
  /*! Bundled license information:
115
115
 
116
116
  pvtsutils/build/index.js: