@helia/verified-fetch 2.2.0 → 2.2.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 CHANGED
@@ -48,7 +48,7 @@ a=ice-pwd:`+e+`
48
48
  `),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let i=new le(...e.map(s=>ar.single(C(`${s}
49
49
  `))),C(`
50
50
  `));t.log.trace('handle: respond with "%s" for %s',e,o),await ps(n,i,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log.trace('handle: respond with "na" for "%s"',o),await ps(n,C(`na
51
- `),t),t.log('handle: responded with "na" for "%s"',o)}}var gL=500,K4=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:i,abort:s,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=i,this._abort=s,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[S6]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new du("the connection is being closed");if(this.status==="closed")throw new bs("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new vs("Cannot open protocol stream on limited connection");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(gL);H(1/0,t),e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}};function ev(r){return new K4(r)}function bL(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return $4}function EL(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??H4}function tv(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var i0=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;outboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=new Map,t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??3e3,this.outboundUpgradeTimeout=t.outboundUpgradeTimeout??3e3,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??2e3,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??2e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Hp(`The multiaddr connection is blocked by gater.${e}`)}async upgradeInbound(e,t={}){let n=!1;try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Vp("Connection denied");await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",t)}catch(o){throw this.metrics.errors?.increment({inbound:!0}),o}finally{n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t={}){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),o;return n!=null&&(o=De(n),await this.shouldBlockConnection("denyOutboundConnection",o,e)),await this._performUpgrade(e,"outbound",t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let o,i,s,a,c,l=AbortSignal.timeout(t==="inbound"?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),d=pe([l,n.signal]);H(1/0,l,d),n.signal=d,this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let u=e;if(n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),u=await f.protect(e,n))}try{if(o=u,n?.skipEncryption!==!0){n?.onProgress?.(new F(`upgrader:encrypt-${t}-connection`)),{conn:o,remotePeer:i,protocol:c}=await(t==="inbound"?this._encryptInbound(u,{...n,signal:d}):this._encryptOutbound(u,{...n,signal:d}));let f={...u,...o};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",i,f)}else{let f=e.remoteAddr.getPeerId();if(f==null)throw new vo(`${t} connection that skipped encryption must have a peer id`);let h=De(f);c="native",i=h}if(i.equals(this.components.peerId)){let f=new xs("Can not dial self");throw e.abort(f),f}if(s=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new F(`upgrader:multiplex-${t}-connection`));let f=await(t==="inbound"?this._multiplexInbound({...u,...o},this.streamMuxers,n):this._multiplexOutbound({...u,...o},this.streamMuxers,n));a=f.muxerFactory,s=f.stream}}catch(f){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,f),f}finally{d.clear()}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",i,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:i,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:i,remotePeer:s,muxerFactory:a,limits:c}=e,l,d,u;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:p=>{u!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),g=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);H(1/0,g);let{stream:y,protocol:w}=await Xl(p,m,{signal:g,log:p.log,yieldBytes:!1});if(u==null)return;u.log("incoming stream opened on %s",w);let b=bL(w,this.components.registrar);if(tv(w,"inbound",u)===b){let A=new mu(`Too many inbound protocol streams for protocol "${w}" - limit ${b}`);throw p.abort(A),A}p.source=y.source,p.sink=y.sink,p.protocol=w,y.closeWrite!=null&&(p.closeWrite=y.closeWrite),y.closeRead!=null&&(p.closeRead=y.closeRead),y.close!=null&&(p.close=y.close),await this.components.peerStore.merge(s,{protocols:[w]}),this.components.metrics?.trackProtocolStream(p,u),this._onStream({connection:u,stream:p,protocol:w})}).catch(async m=>{u.log.error("error handling incoming stream id %s - %e",p.id,m),p.timeline.close==null&&await p.close()})}}),d=async(p,m={})=>{if(l==null)throw new ds("Connection is not multiplexed");u.log.trace("starting new stream for protocols %s",p);let g=await l.newStream();u.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);H(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:w}=await Yl(g,p,{...m,log:g.log,yieldBytes:!0});g.log.trace("selected protocol %s",w);let b=EL(w,this.components.registrar,m),E=tv(w,"outbound",u);if(E>=b){let A=new _o(`Too many outbound protocol streams for protocol "${w}" - ${E}/${b}`);throw g.abort(A),A}return await this.components.peerStore.merge(s,{protocols:[w]}),g.source=y.source,g.sink=y.sink,g.protocol=w,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,u),g}catch(y){throw u.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,p,y),g.timeline.close==null&&g.abort(y),y}},Promise.all([l.sink(i.source),i.sink(l.source)]).catch(p=>{u.log.error("error piping data through muxer - %e",p)}));let f=o.timeline;o.timeline=new Proxy(f,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&f.close==null&&(async()=>{try{u.status==="open"&&await u.close()}catch(m){u.log.error("error closing connection after timeline close %e",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(m=>{u.log.error("error thrown while dispatching connection:close event %e",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new ds("Connection is not multiplexed")};return u=ev({remoteAddr:o.remoteAddr,remotePeer:s,status:"open",direction:n,timeline:o.timeline,multiplexer:l?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:d??h,getStreams:()=>l?.streams??[],close:async p=>{await l?.close(p),await o.close(p)},abort:p=>{o.abort(p),l?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:u}),u.__maConnTimeline=f,u}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:i,options:s}=this.components.registrar.getHandler(o);if(t.limits!=null&&s.runOnLimitedConnection!==!0)throw new vs("Cannot open protocol stream on limited connection");i({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:i}=await Xl(e,n,{...t,log:e.log}),s=this.connectionEncrypters.get(i);if(s==null)throw new fs(`no crypto module found for ${i}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,i),{...await s.secureInbound(o,t),protocol:i}}catch(o){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,o),new fs(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:i}=await Yl(e,n,{...t,log:e.log,yieldBytes:!0}),s=this.connectionEncrypters.get(i);if(s==null)throw new fs(`no crypto module found for ${i}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,i),{...await s.secureOutbound(o,t),protocol:i}}catch(o){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,o),new fs(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let{stream:i,protocol:s}=await Yl(e,o,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let a=t.get(s);return{stream:i,muxerFactory:a}}catch(i){throw e.log.error("error multiplexing outbound connection",i),new ds(String(i))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{let{stream:i,protocol:s}=await Xl(e,o,{...n,log:e.log}),a=t.get(s);return{stream:i,muxerFactory:a}}catch(i){throw e.log.error("error multiplexing inbound connection",i),new ds(String(i))}}};var s0=class extends we{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new we,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),l=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||l},H(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Vo(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=Lx({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:Ip,version:Ap},logger:this.logger,events:t,datastore:e.datastore??new Lp,connectionGater:Bx(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",Px(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(l=>l.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new i0(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),streamMuxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,outboundUpgradeTimeout:e.connectionManager?.outboundUpgradeTimeout}),this.configureComponent("transportManager",new o0(this.components,e.transportManager)),this.configureComponent("connectionManager",new Zp(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Jp(this.components,e.connectionMonitor)),this.configureComponent("registrar",new n0(this.components)),this.configureComponent("addressManager",new Op(this.components,e.addresses));let i=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new t0(this.components,{routers:i}));let s=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new e0(this.components,{routers:s})),this.configureComponent("randomWalk",new r0(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],l=c(this.components);if(l==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=l,this.configureComponent(a,l),l[xn]!=null&&(this.log("registering service %s for content routing",a),s.push(l[xn])),l[vn]!=null&&(this.log("registering service %s for peer routing",a),i.push(l[vn])),l[di]!=null&&(this.log("registering service %s for peer discovery",a),l[di].addEventListener?.("peer",d=>{this.#e(d)}))}Ox(o)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new hr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new P("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new P("no protocols were provided to open a stream");return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Yo(e)&&(e=De(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.name!=="NotFoundError")throw s}let n=be([C("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),i=it(o);return await this.peerStore.patch(e,{publicKey:i}),i}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function a0(r={}){r.privateKey??=await Hd("Ed25519");let e=new s0({...await Ix(r),peerId:F5(r.privateKey)});return r.start!==!1&&await e.start(),e}async function rv(r){let e=r.libp2p?.privateKey,t=r.logger??Vo(),n=new Ie("/pkcs8/self"),o;if(e==null&&r.datastore!=null)if(o=np(r.keychain)({datastore:r.datastore,logger:t}),r.libp2p=r.libp2p??{},await r.datastore.has(n))r.libp2p.privateKey=await o.exportKey("self");else{let a=await Hd("Ed25519");r.libp2p.privateKey=a,await o.importKey("self",a)}let i=zl(r);return i.datastore=i.datastore??r.datastore,r=r??{},await a0({...i,...r.libp2p,start:!1})}async function nv(r={}){let e=r.datastore??new Al,t=r.blockstore??new Sl,n;xL(r.libp2p)?n=r.libp2p:n=await rv({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e});let o=new u1({...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[ul(),tl()],routers:r.routers??[vl(n),xl()],metrics:n.metrics});return r.start!==!1&&await o.start(),o}function xL(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}function ov(){let r=zl();r.start=!1,r.addresses={listen:[]},r.transports=[xp(),_p()];let e={dcutr:r.services.dcutr,identify:r.services.identify,keychain:r.services.keychain,ping:r.services.ping};return{...r,start:!1,services:e}}var G4=ct(c0(),1);var W4=40;function Y4(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=G4.default.decode(r);return e.seek(G4.default.decode.bytes),t}function X4(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}var ci={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},Ql={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":ci.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(ci.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Ql["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=Ql["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:ci.Int,CarV1HeaderOrV2Pragma:r=>{if(ci.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=Ql["CarV1HeaderOrV2Pragma > roots (anon)"](r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Ql.Int(r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},jl={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":ci.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(ci.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=jl["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=jl["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:ci.Int,CarV1HeaderOrV2Pragma:r=>{if(ci.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=jl["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=jl.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},Q4={toTyped:Ql.CarV1HeaderOrV2Pragma,toRepresentation:jl.CarV1HeaderOrV2Pragma};var lge=Vm();var UL=ct(c0(),1);var pge=[new M(x.map,2),new M(x.string,"version"),new M(x.uint,1),new M(x.string,"roots")],mge=new M(x.tag,42);async function j4(r,e){let t=Y4(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),o=Wo(n);if(Q4.toTyped(o)===void 0)throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||e!==void 0&&o.version!==e)throw new Error(`Invalid CAR version: ${o.version}${e!==void 0?` (expected ${e})`:""}`);if(o.version===1){if(!Array.isArray(o.roots))throw new Error("Invalid CAR header format");return o}if(o.roots!==void 0)throw new Error("Invalid CAR header format");let i=X4(await r.exactly(W4,!0));r.seek(i.dataOffset-r.pos);let s=await j4(r,1);return Object.assign(s,i)}function Zl(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let o=r.subarray(e,e+t);return n&&(e+=t),o},seek(t){e+=t},get pos(){return e}}}var Z4=ct(c0(),1),gv=1;function J4(r){let e=ea({version:gv,roots:r}),t=Z4.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function yv(r){return{async setRoots(e){let t=J4(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(Z4.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return gv}}}function l0(){}function wv(){let r=[],e=null,t=l0,n=!1,o=null,i=l0,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=l0,l()}})),e),a={write(l){r.push(l);let d=s();return i(),d},async end(){n=!0;let l=s();i(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&t(),{done:!1,value:l}):n?(t(),{done:!0,value:void 0}):(o||(o=new Promise(d=>{i=()=>(o=null,i=l0,d(c.next()))})),o)}};return{writer:a,iterator:c}}var Jl=class r{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=K.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(e){e=VL(e);let{encoder:t,iterator:n}=bv(),o=new r(e,t),i=new u0(n);return{writer:o,out:i}}static createAppender(){let{encoder:e,iterator:t}=bv();e.setRoots=()=>Promise.resolve();let n=new r([],e),o=new u0(t);return{writer:n,out:o}}static async updateRootsInBytes(e,t){let n=Zl(e);await j4(n);let o=J4(t);if(Number(n.pos)!==o.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${o.length} bytes)`);return e.set(o,0),e}},u0=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function bv(){let r=wv(),{writer:e,iterator:t}=r;return{encoder:yv(e),iterator:t}}function VL(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=K.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=K.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var KL=1,e6=class{components;constructor(e,t){this.components=e}async import(e,t){await rt(this.components.blockstore.putMany(We(e.blocks(),({cid:n,bytes:o})=>({cid:n,block:o})),t))}async export(e,t,n){let o=ee(),i=Array.isArray(e)?e:[e],s=new mr({concurrency:KL});s.on("idle",()=>{o.resolve()}),s.on("error",a=>{s.clear(),o.reject(a)});for(let a of i)s.add(async()=>{await this.#e(a,s,async(c,l)=>{n?.blockFilter?.has(c.multihash.bytes)!==!0&&(n?.blockFilter?.add(c.multihash.bytes),await t.put({cid:c,bytes:l}))},n)}).catch(()=>{});try{await o.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:o}=Jl.create(e);this.export(e,n,t).catch(()=>{});for await(let i of o)yield i}async#e(e,t,n,o){let i=await this.components.getCodec(e.code),s=await this.components.blockstore.get(e,o);await n(e,s);let a=wf({bytes:s,cid:e,codec:i});for await(let[,c]of a.links())t.add(async()=>{await this.#e(c,t,n,o)})}};function Ev(r,e={}){return new e6(r,e)}function qL(r){return r[Symbol.asyncIterator]!=null}function zL(r){if(qL(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var xv=zL;var d0=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},Yr=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},f0=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},Et=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},h0=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},p0=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},m0=class r extends Error{static name="NoPropError";static code="ERR_NO_PROP";name=r.name;code=r.code;constructor(e="No Property found"){super(e)}},ms=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};function Ga(r,e,t,n,o,i,s){let a=r,c=o;for(;i.length>0;){let l=i[0];if(l in a){i.shift(),c=`${c}/${l}`;let d=K.asCID(a[l]);if(d!=null)return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:d,name:l,path:c,toResolve:i}};a=a[l]}else throw new m0(`No property named ${l} found in node ${t}`)}return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}}}}var GL=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=Wo(c);return Ga(l,c,r,e,t,n,i)},vv=GL;var WL=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=ra(c);return Ga(l,c,r,e,t,n,i)},Sv=WL;function YL(r,e,t,n){let o=BigInt(r.length),i=BigInt(e+o);return t>=i||n<e?new Uint8Array(0):(n>=e&&n<i&&(r=r.subarray(0,Number(n-e))),t>=e&&t<i&&(r=r.subarray(Number(t-e))),r)}var gs=YL;var XL=(r,e=0,t=r)=>{let n=BigInt(r),o=BigInt(e??0),i=BigInt(t);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw new ms("Offset must be greater than or equal to 0");if(o>n)throw new ms("Offset must be less than the file size");if(i<0n)throw new ms("Length must be greater than or equal to 0");if(i>n)throw new ms("Length must be less than the file size");return{start:o,end:i}},Wa=XL;var QL=r=>{async function*e(t={}){let{start:n,end:o}=Wa(r.length,t.offset,t.length),i=gs(r,0n,n,o);t.onProgress?.(new F("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},jL=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw new Yr(`No link named ${t} found in raw node ${r}`);let c=Ee(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:QL(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},_v=jL;var ZL=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=w2(c);return Ga(l,c,r,e,t,n,i)},Av=ZL;var JL=r=>{async function*e(t={}){let{start:n,end:o}=Wa(r.length,t.offset,t.length),i=gs(r,0n,n,o);t.onProgress?.(new F("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},eO=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw new Yr(`No link named ${t} found in raw node ${r}`);let c=await s.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:JL(c),depth:i,size:BigInt(c.length),node:c}}},Iv=eO;var eu=class r extends Error{static name="InvalidTypeError";static code="ERR_INVALID_TYPE";name=r.name;code=r.code;constructor(e="Invalid type"){super(e)}};var En;(function(r){let e;(function(o){o.Raw="Raw",o.Directory="Directory",o.File="File",o.Metadata="Metadata",o.Symlink="Symlink",o.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(o){o[o.Raw=0]="Raw",o[o.Directory=1]="Directory",o[o.File=2]="File",o[o.Metadata=3]="Metadata",o[o.Symlink=4]="Symlink",o[o.HAMTShard=5]="HAMTShard"})(t||(t={})),function(o){o.codec=()=>Me(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=ne((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),r.DataType.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),o.filesize!=null&&(i.uint32(24),i.uint64(o.filesize)),o.blocksizes!=null)for(let a of o.blocksizes)i.uint32(32),i.uint64(a);o.hashType!=null&&(i.uint32(40),i.uint64(o.hashType)),o.fanout!=null&&(i.uint32(48),i.uint64(o.fanout)),o.mode!=null&&(i.uint32(56),i.uint32(o.mode)),o.mtime!=null&&(i.uint32(66),g0.codec().encode(o.mtime,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let s={blocksizes:[]},a=i==null?o.len:o.pos+i;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:s.Type=r.DataType.codec().decode(o);break;case 2:s.Data=o.bytes();break;case 3:s.filesize=o.uint64();break;case 4:s.blocksizes.push(o.uint64());break;case 5:s.hashType=o.uint64();break;case 6:s.fanout=o.uint64();break;case 7:s.mode=o.uint32();break;case 8:s.mtime=g0.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>re(o,r.codec()),r.decode=o=>te(o,r.codec())})(En||(En={}));var g0;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Seconds=t.int64();break;case 2:o.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(g0||(g0={}));var Tv;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.MimeType=t.string();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Tv||(Tv={}));var kv={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},tO=["directory","hamt-sharded-directory"],Cv=parseInt("0644",8),Rv=parseInt("0755",8),Bn=class r{static unmarshal(e){let t=En.decode(e),n=new r({type:kv[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:o,hashType:i,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(kv).includes(t))throw new eu("Type: "+t+" is not valid");this.type=t??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?Rv:Cv:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return tO.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=En.DataType.Raw;break;case"directory":e=En.DataType.Directory;break;case"file":e=En.DataType.File;break;case"metadata":e=En.DataType.Metadata;break;case"symlink":e=En.DataType.Symlink;break;case"hamt-sharded-directory":e=En.DataType.HAMTShard;break;default:throw new eu(`Type: ${e} is not valid`)}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===Cv&&!this.isDirectory()&&(n=void 0),n===Rv&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),En.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var y0=ct(bm(),1);function rO(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var B4e=wi({name:"murmur3-32",code:35,encode:r=>rO(y0.default.x86.hash32(r))}),Pv=wi({name:"murmur3-128",code:34,encode:r=>gi.fromHex(y0.default.x64.hash128(r))}),M4e=wi({name:"murmur3-x64-64",code:34,encode:r=>gi.fromHex(y0.default.x64.hash128(r)).subarray(0,8)});var Ov=ct(Lv(),1);var ys=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new Ov.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof r?o.push(i.serialize(e,t)):o.push(e(i,s))),o),n))}async asyncTransform(e,t){return Bv(this,e,t)}toJSON(){return this.serialize(aO,cO)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?C(e):e),n=await t.take(this._options.bits),o=this._children.get(n);return o instanceof r?o._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:o}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let o=await n._findPlace(t.existingChild.hash);return o.bucket._putAt(o,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(sO);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function sO(r){return!!r}function aO(r,e){return r.key}function cO(r){return r}async function Bv(r,e,t){let n=[];for(let o of r._children.compactArray())if(o instanceof ys)await Bv(o,e,t);else{let i=await e(o);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var lO=[255,254,252,248,240,224,192,128],uO=[1,3,7,15,31,63,127,255],w0=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=dO(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function dO(r,e,t){let n=fO(e,t);return(r&n)>>>e}function fO(r,e){return lO[r]&uO[Math.min(e+r-1,7)]}function Mv(r){function e(t){return t instanceof b0?t:new b0(t,r)}return e}var b0=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?be([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new w0(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Uv(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:Mv(r.hashFn)};return new ys(e)}var hO=async function(r){return(await Pv.encode(r)).slice(0,8).reverse()},pO=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async o=>{if(o.Name==null)throw new Error("Unexpected Link without a Name");if(o.Name.length===n){let i=parseInt(o.Name,16);e._putObjectAt(i,new ys({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(o.Name.substring(2),!0)}))},Fv=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),mO=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},$v=async(r,e,t,n,o)=>{if(n==null){if(r.Data==null)throw new Et("no data in PBNode");let u;try{u=Bn.unmarshal(r.Data)}catch(h){throw new Et(h.message)}if(u.type!=="hamt-sharded-directory")throw new Et("not a HAMT");if(u.fanout==null)throw new Et("missing fanout");let f=Uv({hashFn:hO,bits:Math.log2(Number(u.fanout))});n={rootBucket:f,hamtDepth:1,lastBucket:f}}let i=(n.lastBucket.tableSize()-1).toString(16).length;await pO(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=Fv(s.pos,i),c=mO(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=Fv(n.lastBucket._posAtParent,i));let l=r.Links.find(u=>{if(u.Name==null)return!1;let f=u.Name.substring(0,i),h=u.Name.substring(i);return!(f!==a||h!==""&&h!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(i)===e)return l.Hash;n.hamtDepth++;let d=await t.get(l.Hash,o);return r=lo(d),$v(r,e,t,n,o)},Hv=$v;var gO=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=c.offset??0,d=c.length??e.Links.length,u=e.Links.slice(l,d);c.onProgress?.(new F("unixfs:exporter:walk:directory",{cid:r})),yield*Ne(u,f=>We(f,h=>async()=>{let p=h.Name??"",m=`${n}/${p}`;return(await o(h.Hash,p,m,[],i+1,s,c)).entry}),f=>bt(f,{ordered:!0,concurrency:c.blockReadConcurrency}),f=>dt(f,h=>h!=null))}return a},Vv=gO;async function Kv(r,e,t,n,o,i,s){if(e instanceof Uint8Array){let l=gs(e,n,o,i);t.push(l);return}if(e.Data==null)throw new Et("no data in PBNode");let a;try{a=Bn.unmarshal(e.Data)}catch(l){throw new Et(l.message)}if(a.data!=null){let l=a.data,d=gs(l,n,o,i);t.push(d),n+=BigInt(d.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new Et("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let d=e.Links[l],u=n,f=u+a.blockSizes[l];if((o>=u&&o<f||i>=u&&i<=f||o<u&&i>f)&&c.push({link:d,blockStart:n}),n=f,n>i)break}await Ne(c,l=>We(l,d=>async()=>{let u=await r.get(d.link.Hash,s);return{...d,block:u}}),l=>bt(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:d,block:u,blockStart:f}of l){let h;switch(d.Hash.code){case Kr:h=lo(u);break;case Ht:h=u;break;default:t.end(new Et(`Unsupported codec: ${d.Hash.code}`));return}let p=new mr({concurrency:1});p.on("error",m=>{t.end(m)}),p.add(async()=>{s.onProgress?.(new F("unixfs:exporter:walk:file",{cid:d.Hash})),await Kv(r,h,t,f,o,i,s)}),await p.onIdle()}}),n>=i&&t.end()}var yO=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:d,end:u}=Wa(l,c.offset,c.length);if(u===0n)return;let f=0n,h=u-d,p=xt();c.onProgress?.(new F("unixfs:exporter:walk:file",{cid:r})),Kv(s,e,p,0n,d,u,c).catch(m=>{p.end(m)});for await(let m of p)if(m!=null){if(f+=BigInt(m.byteLength),f>h)throw p.end(),new h0("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");f===h&&p.end(),c.onProgress?.(new F("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:h,fileSize:l})),yield m}if(f<h)throw new p0("Traversed entire DAG but did not read enough bytes")}return a},t6=yO;var wO=(r,e,t,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new F("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),qv(e,n,o,i,s,c)}return a};async function*qv(r,e,t,n,o,i){let s=r.Links;if(r.Data==null)throw new Et("no data in PBNode");let a;try{a=Bn.unmarshal(r.Data)}catch(d){throw new Et(d.message)}if(a.fanout==null)throw new Et("missing fanout");let c=(a.fanout-1n).toString(16).length,l=Ne(s,d=>We(d,u=>async()=>{let f=u.Name!=null?u.Name.substring(c):null;if(f!=null&&f!==""){let h=await t(u.Hash,f,`${e}/${f}`,[],n+1,o,i);return{entries:h.entry==null?[]:[h.entry]}}else{let h=await o.get(u.Hash,i);return r=lo(h),i.onProgress?.(new F("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:qv(r,e,t,n,o,i)}}}),d=>bt(d,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:d}of l)yield*d}var zv=wO;var bO=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,EO={raw:t6,file:t6,directory:Vv,"hamt-sharded-directory":zv,metadata:(r,e,t,n,o,i,s)=>()=>[],symlink:(r,e,t,n,o,i,s)=>()=>[]},xO=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=lo(c),d,u;if(e==null&&(e=r.toString()),l.Data==null)throw new Et("no data in PBNode");try{d=Bn.unmarshal(l.Data)}catch(h){throw new Et(h.message)}if(t==null&&(t=e),n.length>0){let h;if(d?.type==="hamt-sharded-directory"?h=await Hv(l,n[0],s):h=bO(l,n[0]),h==null)throw new Yr("file does not exist");let p=n.shift(),m=`${t}/${p}`;u={cid:h,toResolve:n,name:p??"",path:m}}let f=EO[d.type](r,l,d,t,o,i,s);if(f==null)throw new Yr("could not find content exporter");return d.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:f,unixfs:d,depth:i,node:l,size:d.fileSize()},next:u}:{entry:{type:"file",name:e,path:t,cid:r,content:f,unixfs:d,depth:i,node:l,size:d.fileSize()},next:u}},Gv=xO;var vO={[Kr]:Gv,[Ht]:Iv,[ao]:vv,[co]:Sv,[vt.code]:_v,[Hn]:Av},Wv=async(r,e,t,n,o,i,s)=>{let a=vO[r.code];if(a==null)throw new f0(`No resolver for code ${r.code}`);return a(r,e,t,n,Wv,o,i,s)},Yv=Wv;var SO=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),_O=r=>{if(r instanceof Uint8Array)return{cid:K.decode(r),toResolve:[]};let e=K.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=SO(r);return{cid:K.parse(t[0]),toResolve:t.slice(1)}}throw new d0(`Unknown path type ${r}`)};async function*r6(r,e,t={}){let{cid:n,toResolve:o}=_O(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await Yv(n,i,s,o,a,e,t);if(c.entry==null&&c.next==null)throw new Yr(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;o=c.next.toResolve,n=c.next.cid,i=c.next.name,s=c.next.path}}async function Ya(r,e,t={}){let n=await xv(r6(r,e,t));if(n==null)throw new Yr(`Could not resolve ${r}`);return n}async function*Xv(r,e,t={}){let n=await Ya(r,e,t);if(n==null)return;if(yield n,n.type==="directory")for await(let i of o(n,t))yield i;async function*o(i,s){for await(let a of i.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*o(a,s))}}function E0(r,e={}){let t=Ia(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:i,done:s}=await t.next();if(this._cancelled)return;if(s===!0){o.close();return}o.enqueue(i)}catch(i){o.error(i)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}var Xa=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,jv=new Set,n6=typeof process=="object"&&process?process:{},Zv=(r,e,t,n)=>{typeof n6.emitWarning=="function"?n6.emitWarning(r,e,t,n):console.error(`[${t}] ${e}: ${r}`)},x0=globalThis.AbortController,Qv=globalThis.AbortSignal;if(typeof x0>"u"){Qv=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,o){this._onabort.push(o)}},x0=class{constructor(){e()}signal=new Qv;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let o of this.signal._onabort)o(n);this.signal.onabort?.(n)}}};let r=n6.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=!1,Zv("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var AO=r=>!jv.has(r),e8e=Symbol("type"),li=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),Jv=r=>li(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?Qa:null:null,Qa=class extends Array{constructor(e){super(e),this.fill(0)}},o6=class r{heap;length;static#e=!1;static create(e){let t=Jv(e);if(!t)return[];r.#e=!0;let n=new r(e,t);return r.#e=!1,n}constructor(e,t){if(!r.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},v0=class r{#e;#r;#n;#c;#g;#S;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#y;#o;#s;#t;#f;#l;#h;#u;#b;#d;#E;#x;#m;#w;#_;#p;static unsafeExposeInternals(e){return{starts:e.#x,ttls:e.#m,sizes:e.#E,keyMap:e.#o,keyList:e.#s,valList:e.#t,next:e.#f,prev:e.#l,get head(){return e.#h},get tail(){return e.#u},free:e.#b,isBackgroundFetch:t=>e.#a(t),backgroundFetch:(t,n,o,i)=>e.#O(t,n,o,i),moveToTail:t=>e.#N(t),indexes:t=>e.#I(t),rindexes:t=>e.#T(t),isStale:t=>e.#v(t)}}get max(){return this.#e}get maxSize(){return this.#r}get calculatedSize(){return this.#y}get size(){return this.#i}get fetchMethod(){return this.#g}get memoMethod(){return this.#S}get dispose(){return this.#n}get disposeAfter(){return this.#c}constructor(e){let{max:t=0,ttl:n,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:l,disposeAfter:d,noDisposeOnSet:u,noUpdateTTL:f,maxSize:h=0,maxEntrySize:p=0,sizeCalculation:m,fetchMethod:g,memoMethod:y,noDeleteOnFetchRejection:w,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:A,ignoreFetchAbort:k}=e;if(t!==0&&!li(t))throw new TypeError("max option must be a nonnegative integer");let v=t?Jv(t):Array;if(!v)throw new Error("invalid max value: "+t);if(this.#e=t,this.#r=h,this.maxEntrySize=p||this.#r,this.sizeCalculation=m,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#S=y,g!==void 0&&typeof g!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#g=g,this.#_=!!g,this.#o=new Map,this.#s=new Array(t).fill(void 0),this.#t=new Array(t).fill(void 0),this.#f=new v(t),this.#l=new v(t),this.#h=0,this.#u=0,this.#b=o6.create(t),this.#i=0,this.#y=0,typeof l=="function"&&(this.#n=l),typeof d=="function"?(this.#c=d,this.#d=[]):(this.#c=void 0,this.#d=void 0),this.#w=!!this.#n,this.#p=!!this.#c,this.noDisposeOnSet=!!u,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!w,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!k,this.maxEntrySize!==0){if(this.#r!==0&&!li(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!li(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#H()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=li(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!li(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#R()}if(this.#e===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#r){let S="LRU_CACHE_UNBOUNDED";AO(S)&&(jv.add(S),Zv("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",S,r))}}getRemainingTTL(e){return this.#o.has(e)?1/0:0}#R(){let e=new Qa(this.#e),t=new Qa(this.#e);this.#m=e,this.#x=t,this.#B=(i,s,a=Xa.now())=>{if(t[i]=s!==0?a:0,e[i]=s,s!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#v(i)&&this.#k(this.#s[i],"expire")},s+1);c.unref&&c.unref()}},this.#A=i=>{t[i]=e[i]!==0?Xa.now():0},this.#C=(i,s)=>{if(e[s]){let a=e[s],c=t[s];if(!a||!c)return;i.ttl=a,i.start=c,i.now=n||o();let l=i.now-c;i.remainingTTL=a-l}};let n=0,o=()=>{let i=Xa.now();if(this.ttlResolution>0){n=i;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=this.#o.get(i);if(s===void 0)return 0;let a=e[s],c=t[s];if(!a||!c)return 1/0;let l=(n||o())-c;return a-l},this.#v=i=>{let s=t[i],a=e[i];return!!a&&!!s&&(n||o())-s>a}}#A=()=>{};#C=()=>{};#B=()=>{};#v=()=>!1;#H(){let e=new Qa(this.#e);this.#y=0,this.#E=e,this.#P=t=>{this.#y-=e[t],e[t]=0},this.#M=(t,n,o,i)=>{if(this.#a(n))return 0;if(!li(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(n,t),!li(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#D=(t,n,o)=>{if(e[t]=n,this.#r){let i=this.#r-e[t];for(;this.#y>i;)this.#L(!0)}this.#y+=e[t],o&&(o.entrySize=n,o.totalCalculatedSize=this.#y)}}#P=e=>{};#D=(e,t,n)=>{};#M=(e,t,n,o)=>{if(n||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#I({allowStale:e=this.allowStale}={}){if(this.#i)for(let t=this.#u;!(!this.#U(t)||((e||!this.#v(t))&&(yield t),t===this.#h));)t=this.#l[t]}*#T({allowStale:e=this.allowStale}={}){if(this.#i)for(let t=this.#h;!(!this.#U(t)||((e||!this.#v(t))&&(yield t),t===this.#u));)t=this.#f[t]}#U(e){return e!==void 0&&this.#o.get(this.#s[e])===e}*entries(){for(let e of this.#I())this.#t[e]!==void 0&&this.#s[e]!==void 0&&!this.#a(this.#t[e])&&(yield[this.#s[e],this.#t[e]])}*rentries(){for(let e of this.#T())this.#t[e]!==void 0&&this.#s[e]!==void 0&&!this.#a(this.#t[e])&&(yield[this.#s[e],this.#t[e]])}*keys(){for(let e of this.#I()){let t=this.#s[e];t!==void 0&&!this.#a(this.#t[e])&&(yield t)}}*rkeys(){for(let e of this.#T()){let t=this.#s[e];t!==void 0&&!this.#a(this.#t[e])&&(yield t)}}*values(){for(let e of this.#I())this.#t[e]!==void 0&&!this.#a(this.#t[e])&&(yield this.#t[e])}*rvalues(){for(let e of this.#T())this.#t[e]!==void 0&&!this.#a(this.#t[e])&&(yield this.#t[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#I()){let o=this.#t[n],i=this.#a(o)?o.__staleWhileFetching:o;if(i!==void 0&&e(i,this.#s[n],this))return this.get(this.#s[n],t)}}forEach(e,t=this){for(let n of this.#I()){let o=this.#t[n],i=this.#a(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#s[n],this)}}rforEach(e,t=this){for(let n of this.#T()){let o=this.#t[n],i=this.#a(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#s[n],this)}}purgeStale(){let e=!1;for(let t of this.#T({allowStale:!0}))this.#v(t)&&(this.#k(this.#s[t],"expire"),e=!0);return e}info(e){let t=this.#o.get(e);if(t===void 0)return;let n=this.#t[t],o=this.#a(n)?n.__staleWhileFetching:n;if(o===void 0)return;let i={value:o};if(this.#m&&this.#x){let s=this.#m[t],a=this.#x[t];if(s&&a){let c=s-(Xa.now()-a);i.ttl=c,i.start=Date.now()}}return this.#E&&(i.size=this.#E[t]),i}dump(){let e=[];for(let t of this.#I({allowStale:!0})){let n=this.#s[t],o=this.#t[t],i=this.#a(o)?o.__staleWhileFetching:o;if(i===void 0||n===void 0)continue;let s={value:i};if(this.#m&&this.#x){s.ttl=this.#m[t];let a=Xa.now()-this.#x[t];s.start=Math.floor(Date.now()-a)}this.#E&&(s.size=this.#E[t]),e.unshift([n,s])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let o=Date.now()-n.start;n.start=Xa.now()-o}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=n,{noUpdateTTL:l=this.noUpdateTTL}=n,d=this.#M(e,t,n.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#k(e,"set"),this;let u=this.#i===0?void 0:this.#o.get(e);if(u===void 0)u=this.#i===0?this.#u:this.#b.length!==0?this.#b.pop():this.#i===this.#e?this.#L(!1):this.#i,this.#s[u]=e,this.#t[u]=t,this.#o.set(e,u),this.#f[this.#u]=u,this.#l[u]=this.#u,this.#u=u,this.#i++,this.#D(u,d,c),c&&(c.set="add"),l=!1;else{this.#N(u);let f=this.#t[u];if(t!==f){if(this.#_&&this.#a(f)){f.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:h}=f;h!==void 0&&!s&&(this.#w&&this.#n?.(h,e,"set"),this.#p&&this.#d?.push([h,e,"set"]))}else s||(this.#w&&this.#n?.(f,e,"set"),this.#p&&this.#d?.push([f,e,"set"]));if(this.#P(u),this.#D(u,d,c),this.#t[u]=t,c){c.set="replace";let h=f&&this.#a(f)?f.__staleWhileFetching:f;h!==void 0&&(c.oldValue=h)}}else c&&(c.set="update")}if(o!==0&&!this.#m&&this.#R(),this.#m&&(l||this.#B(u,o,i),c&&this.#C(c,u)),!s&&this.#p&&this.#d){let f=this.#d,h;for(;h=f?.shift();)this.#c?.(...h)}return this}pop(){try{for(;this.#i;){let e=this.#t[this.#h];if(this.#L(!0),this.#a(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#p&&this.#d){let e=this.#d,t;for(;t=e?.shift();)this.#c?.(...t)}}}#L(e){let t=this.#h,n=this.#s[t],o=this.#t[t];return this.#_&&this.#a(o)?o.__abortController.abort(new Error("evicted")):(this.#w||this.#p)&&(this.#w&&this.#n?.(o,n,"evict"),this.#p&&this.#d?.push([o,n,"evict"])),this.#P(t),e&&(this.#s[t]=void 0,this.#t[t]=void 0,this.#b.push(t)),this.#i===1?(this.#h=this.#u=0,this.#b.length=0):this.#h=this.#f[t],this.#o.delete(n),this.#i--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:o}=t,i=this.#o.get(e);if(i!==void 0){let s=this.#t[i];if(this.#a(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#v(i))o&&(o.has="stale",this.#C(o,i));else return n&&this.#A(i),o&&(o.has="hit",this.#C(o,i)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,o=this.#o.get(e);if(o===void 0||!n&&this.#v(o))return;let i=this.#t[o];return this.#a(i)?i.__staleWhileFetching:i}#O(e,t,n,o){let i=t===void 0?void 0:this.#t[t];if(this.#a(i))return i;let s=new x0,{signal:a}=n;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:n,context:o},l=(m,g=!1)=>{let{aborted:y}=s.signal,w=n.ignoreFetchAbort&&m!==void 0;if(n.status&&(y&&!g?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,w&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),y&&!w&&!g)return u(s.signal.reason);let b=h;return this.#t[t]===h&&(m===void 0?b.__staleWhileFetching?this.#t[t]=b.__staleWhileFetching:this.#k(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,m,c.options))),m},d=m=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=m),u(m)),u=m=>{let{aborted:g}=s.signal,y=g&&n.allowStaleOnFetchAbort,w=y||n.allowStaleOnFetchRejection,b=w||n.noDeleteOnFetchRejection,E=h;if(this.#t[t]===h&&(!b||E.__staleWhileFetching===void 0?this.#k(e,"fetch"):y||(this.#t[t]=E.__staleWhileFetching)),w)return n.status&&E.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),E.__staleWhileFetching;if(E.__returned===E)throw m},f=(m,g)=>{let y=this.#g?.(e,i,c);y&&y instanceof Promise&&y.then(w=>m(w===void 0?void 0:w),g),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(m(void 0),n.allowStaleOnFetchAbort&&(m=w=>l(w,!0)))})};n.status&&(n.status.fetchDispatched=!0);let h=new Promise(f).then(l,d),p=Object.assign(h,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...c.options,status:void 0}),t=this.#o.get(e)):this.#t[t]=p,p}#a(e){if(!this.#_)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof x0}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:g=!1,status:y,signal:w}=t;if(!this.#_)return y&&(y.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:y});let b={allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:d,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:p,ignoreFetchAbort:h,status:y,signal:w},E=this.#o.get(e);if(E===void 0){y&&(y.fetch="miss");let A=this.#O(e,E,b,m);return A.__returned=A}else{let A=this.#t[E];if(this.#a(A)){let $=n&&A.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",$&&(y.returnedStale=!0)),$?A.__staleWhileFetching:A.__returned=A}let k=this.#v(E);if(!g&&!k)return y&&(y.fetch="hit"),this.#N(E),o&&this.#A(E),y&&this.#C(y,E),A;let v=this.#O(e,E,b,m),T=v.__staleWhileFetching!==void 0&&n;return y&&(y.fetch=k?"stale":"refresh",T&&k&&(y.returnedStale=!0)),T?v.__staleWhileFetching:v.__returned=v}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,t={}){let n=this.#S;if(!n)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...s}=t,a=this.get(e,s);if(!i&&a!==void 0)return a;let c=n(e,a,{options:s,context:o});return this.set(e,c,s),c}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,a=this.#o.get(e);if(a!==void 0){let c=this.#t[a],l=this.#a(c);return s&&this.#C(s,a),this.#v(a)?(s&&(s.get="stale"),l?(s&&n&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?c.__staleWhileFetching:void 0):(i||this.#k(e,"expire"),s&&n&&(s.returnedStale=!0),n?c:void 0)):(s&&(s.get="hit"),l?c.__staleWhileFetching:(this.#N(a),o&&this.#A(a),c))}else s&&(s.get="miss")}#F(e,t){this.#l[t]=e,this.#f[e]=t}#N(e){e!==this.#u&&(e===this.#h?this.#h=this.#f[e]:this.#F(this.#l[e],this.#f[e]),this.#F(this.#u,e),this.#u=e)}delete(e){return this.#k(e,"delete")}#k(e,t){let n=!1;if(this.#i!==0){let o=this.#o.get(e);if(o!==void 0)if(n=!0,this.#i===1)this.#$(t);else{this.#P(o);let i=this.#t[o];if(this.#a(i)?i.__abortController.abort(new Error("deleted")):(this.#w||this.#p)&&(this.#w&&this.#n?.(i,e,t),this.#p&&this.#d?.push([i,e,t])),this.#o.delete(e),this.#s[o]=void 0,this.#t[o]=void 0,o===this.#u)this.#u=this.#l[o];else if(o===this.#h)this.#h=this.#f[o];else{let s=this.#l[o];this.#f[s]=this.#f[o];let a=this.#f[o];this.#l[a]=this.#l[o]}this.#i--,this.#b.push(o)}}if(this.#p&&this.#d?.length){let o=this.#d,i;for(;i=o?.shift();)this.#c?.(...i)}return n}clear(){return this.#$("delete")}#$(e){for(let t of this.#T({allowStale:!0})){let n=this.#t[t];if(this.#a(n))n.__abortController.abort(new Error("deleted"));else{let o=this.#s[t];this.#w&&this.#n?.(n,o,e),this.#p&&this.#d?.push([n,o,e])}}if(this.#o.clear(),this.#t.fill(void 0),this.#s.fill(void 0),this.#m&&this.#x&&(this.#m.fill(0),this.#x.fill(0)),this.#E&&this.#E.fill(0),this.#h=0,this.#u=0,this.#b.length=0,this.#y=0,this.#i=0,this.#p&&this.#d){let t=this.#d,n;for(;n=t?.shift();)this.#c?.(...n)}}};var Nr=class extends Error{static name="InvalidRangeError";constructor(e="Invalid range request"){super(e),this.name="InvalidRangeError"}},S0=class extends Error{static name="NoContentError";constructor(e="No content found"){super(e),this.name="NoContentError"}},_0=class extends Error{static name="SubdomainNotSupportedError";constructor(e="Subdomain not supported"){super(e),this.name="SubdomainNotSupportedError"}};function eS(r,e){if(r==null)return;if(r instanceof Headers)return r.get(e)??void 0;if(Array.isArray(r))return r.find(([o])=>o.toLowerCase()===e.toLowerCase())?.[1];let t=Object.keys(r).find(n=>n.toLowerCase()===e.toLowerCase());if(t!=null)return r[t]}function tS(r,e,t){if((r??0)>(e??1/0))throw new Nr("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(e??0)>=(t??1/0))throw new Nr("Invalid range: Range-end index is greater than or equal to the size of the file.");if(r==null&&(e??0)>(t??1/0))throw new Nr("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new Nr("Invalid range: Range-start index cannot be negative.");if(r!=null&&e!=null)return{byteSize:e-r+1,start:r,end:e};if(r==null&&e!=null)return t==null?{end:e}:e===t?{byteSize:t,start:0,end:t-1}:{byteSize:e,start:t-e,end:t-1};if(r!=null&&e==null){if(t==null)return{start:r};let n=t-1;return{byteSize:t-r,start:r,end:n}}return{byteSize:t,start:0,end:t!=null?t-1:0}}function rS({ttl:r,protocol:e,response:t}){let n;e==="ipfs"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,t.headers.set("cache-control",n)}function nS({byteStart:r,byteEnd:e,byteSize:t}){let n=t??"*";if((e??0)>=(t??1/0))throw new Nr("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(t??1/0))throw new Nr("Invalid range: Range-start index is greater than or equal to the size of the file.");if(r!=null&&e==null)return t==null?`bytes */${n}`:`bytes ${r}-${t-1}/${t}`;if(r==null&&e!=null){if(t==null)return`bytes */${n}`;let o=t-1;return`bytes ${o-e+1}-${o}/${t}`}return r==null&&e==null?`bytes */${n}`:`bytes ${r}-${e}/${n}`}function i6(r,e){e!=null&&r.headers.set("X-Ipfs-Roots",e.map(t=>t.toV1().toString()).join(","))}function IO(r){return typeof r=="string"?r.length:r instanceof ArrayBuffer||r instanceof Uint8Array?r.byteLength:r instanceof Blob?r.size:(r instanceof ReadableStream,null)}function TO(r){let e=r.match(/^bytes=(?<start>\d+)?-(?<end>\d+)?$/);if(e?.groups==null)throw new Nr("Invalid range request");let{start:t,end:n}=e.groups;return{start:t,end:n}}var tu=class{headers;isRangeRequest;_fileSize;_body=null;rangeRequestHeader;log;requestRangeStart;requestRangeEnd;byteStart;byteEnd;byteSize;constructor(e,t){if(this.headers=t,this.log=e.forComponent("helia:verified-fetch:byte-range-context"),this.rangeRequestHeader=eS(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:o}=TO(this.rangeRequestHeader);this.requestRangeStart=n!=null?parseInt(n):null,this.requestRangeEnd=o!=null?parseInt(o):null}catch(n){this.log.error("error parsing range request header: %o",n),this.requestRangeStart=null,this.requestRangeEnd=null}this.setOffsetDetails()}else this.log.trace("no range request detected"),this.isRangeRequest=!1,this.requestRangeStart=null,this.requestRangeEnd=null}setBody(e){this._body=e,this.setFileSize(this._fileSize??IO(e)),this.log.trace("set request body with fileSize %o",this._fileSize)}getBody(){let e=this._body;if(e==null)return this.log.trace("body is null"),e;if(!this.isRangeRequest||!this.isValidRangeRequest)return this.log.trace("returning body unmodified for non-range, or invalid range, request"),e;let t=this.byteStart,n=this.byteEnd,o=this.byteSize;return t!=null||n!=null?(this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",t,n,o),e instanceof ReadableStream?e:this.getSlicedBody(e)):(this.log.error("returning unmodified body for valid range request"),e)}getSlicedBody(e){let t=this.byteStart??0,n=this.byteEnd==null?void 0:this.byteEnd+1;return this.log.trace("returning body with offset %o and length %o",t,n),e.slice(t,n)}setFileSize(e){this._fileSize=e!=null?Number(e):null,this.log.trace("set _fileSize to %o",this._fileSize),this.setOffsetDetails()}getFileSize(){return this._fileSize}isValidByteStart(){return!(this.byteStart!=null&&(this.byteStart<0||this._fileSize!=null&&this.byteStart>=this._fileSize||this.byteEnd!=null&&this.byteStart>this.byteEnd))}isValidByteEnd(){return!(this.byteEnd!=null&&(this.byteEnd<0||this._fileSize!=null&&this.byteEnd>=this._fileSize||this.byteStart!=null&&this.byteEnd<this.byteStart))}get isValidRangeRequest(){if(!this.isRangeRequest)return!1;if(this.requestRangeStart==null&&this.requestRangeEnd==null)return this.log.trace("invalid range request, range request values not provided"),!1;if(!this.isValidByteStart())return this.log.trace("invalid range request, byteStart is less than 0 or greater than fileSize"),!1;if(!this.isValidByteEnd())return this.log.trace("invalid range request, byteEnd is less than 0 or greater than fileSize"),!1;if(this.requestRangeEnd!=null&&this.requestRangeStart!=null){if(this.requestRangeStart>this.requestRangeEnd)return this.log.trace("invalid range request, start is greater than end"),!1;if(this.requestRangeStart<0)return this.log.trace("invalid range request, start is less than 0"),!1;if(this.requestRangeEnd<0)return this.log.trace("invalid range request, end is less than 0"),!1}return this.byteEnd==null&&this.byteStart==null&&this.byteSize==null?(this.log.trace("invalid range request, could not calculate byteStart, byteEnd, or byteSize"),!1):!0}get offset(){return this.byteStart??0}get length(){return this.byteEnd!=null&&this.byteStart!=null&&this.byteStart===this.byteEnd?1:this.byteEnd!=null?this.byteEnd+1:this.byteSize!=null?this.byteSize-1:void 0}setOffsetDetails(){if(this.requestRangeStart==null&&this.requestRangeEnd==null){this.log.trace("requestRangeStart and requestRangeEnd are null");return}try{let{start:e,end:t,byteSize:n}=tS(this.requestRangeStart??void 0,this.requestRangeEnd??void 0,this._fileSize??void 0);this.log.trace("set byteStart to %o, byteEnd to %o, byteSize to %o",e,t,n),this.byteStart=e,this.byteEnd=t,this.byteSize=n}catch(e){this.log.error("error setting offset details: %o",e),this.byteStart=void 0,this.byteEnd=void 0,this.byteSize=void 0}}get contentRangeHeaderValue(){if(!this.isValidRangeRequest)throw this.log.error("cannot get contentRangeHeaderValue for invalid range request"),new Nr("Invalid range request");return nS({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};function oS(r){let e=nr(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(Zc(e))}function iS(r){let e=kO(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function kO(r){return r.replace(/[^\x00-\x7F]/g,"_")}function sS({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:o}){let i=t===!0?"W/":"",s=e==null?"":`.${e}`;return(n!=null||o!=null)&&(s+=`.${n??"0"}-${o??"N"}`),`${i}"${r.toString()}${s}"`}function ru(r){return r.charAt(0)==="1"||r.charAt(0)==="Q"?De(r):$r(K.parse(r))}var CO={[ao]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[co]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Hn]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Kr]:["application/octet-stream","application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car","application/x-tar"],[Ht]:["application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.dag-json","application/vnd.ipld.car","application/x-tar"]};function aS(r,e){let t=CO[r.code];if(e!=null)return RO(e,t)}function RO(r,e){let t=r.split(",").map(n=>{let o=n.trim().split(";");return{mimeType:`${o[0]}`.trim(),weight:PO(o[1])}}).sort((n,o)=>n.weight===o.weight?0:n.weight>o.weight?-1:1).map(n=>n.mimeType);for(let n of t)for(let o of e)if(n.includes(o)||n==="*/*"||n.startsWith("*/")&&o.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&o.split("/")[0]===n.split("/")[0])return o}function PO(r){if(r!=null&&(r=r.trim()),r?.startsWith("q=")!==!0)return 1;let e=parseFloat(r.replace("q=",""));return isNaN(e)?0:e}var A0={raw:"application/vnd.ipld.raw",car:"application/vnd.ipld.car","dag-json":"application/vnd.ipld.dag-json","dag-cbor":"application/vnd.ipld.dag-cbor",json:"application/json",cbor:"application/cbor","ipns-record":"application/vnd.ipfs.ipns-record",tar:"application/x-tar"};function cS(r){if(r!=null)return A0[r]}function s6(r){let e=r.get("accept");return!!(e!=null&&Object.values(A0).includes(e))}function a6(r){let e=r?.format;return!!(e!=null&&Object.keys(A0).includes(e))}function lS({query:r,headers:e}){return s6(e)||a6(r)}function uS({query:r,headers:e,logger:t}){let n=t.forComponent("helia:verified-fetch:get-resolved-accept-header"),o=new Headers(e),i=o.get("accept")??void 0;if(i!=null&&n('incoming accept header "%s"',i),!lS({query:r,headers:o}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",i),i;let s=cS(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=i;return!s6(o)&&a6(r)&&(n("accept header not recognized, but query format provided, setting accept header to %s",s),a=s),n('resolved accept header to "%s"',a),a}async function dS(r,e,t,n){let o=t.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),i=r[Symbol.asyncIterator](),{value:s,done:a}=await i.next();if(a===!0)throw o.error("no content found for path",e),new S0;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new F("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:d,done:u}=await i.next();if(n?.signal?.aborted===!0){l.error(new lt(n.signal.reason??"signal aborted by user")),l.close();return}if(u===!0){d!=null&&(n?.onProgress?.(new F("verified-fetch:request:progress:chunk")),l.enqueue(d)),l.close();return}n?.onProgress?.(new F("verified-fetch:request:progress:chunk")),l.enqueue(d)}}),firstChunk:s}}var I0=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},nu=class extends I0{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}};var T0=class extends I0{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}};var F8e=C("ustar\0","binary"),$8e=C("ustar ","binary"),H8e=C(" \0","binary");var gS=ct(hS(),1);function DO(r){return r[Symbol.asyncIterator]!=null}function LO(r){if(DO(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=be([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return be(e,t)}var pS=LO;var OO="0000000000000000000",BO="7777777777777777777",MO=48,UO=C("ustar\0","binary"),FO=C("00","binary"),$O=parseInt("7777",8),HO=257,VO=263,KO=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},qO=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},ui=function(r,e){let t=r.toString(8);return t.length>e?C(BO.slice(0,e)+" "):C(OO.slice(0,e-t.length)+t+" ")},c6=function(r){let e=C(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function mS(r){let e="";r.name!=null&&(e+=c6(" path="+r.name+`
51
+ `),t),t.log('handle: responded with "na" for "%s"',o)}}var gL=500,K4=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:i,abort:s,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=i,this._abort=s,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[S6]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new du("the connection is being closed");if(this.status==="closed")throw new bs("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new vs("Cannot open protocol stream on limited connection");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(gL);H(1/0,t),e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}};function ev(r){return new K4(r)}function bL(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return $4}function EL(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??H4}function tv(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var i0=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;outboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=new Map,t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=new Map,t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??3e3,this.outboundUpgradeTimeout=t.outboundUpgradeTimeout??3e3,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??2e3,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??2e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Hp(`The multiaddr connection is blocked by gater.${e}`)}async upgradeInbound(e,t={}){let n=!1;try{if(this.metrics.dials?.increment({inbound:!0}),n=await this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Vp("Connection denied");await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",t)}catch(o){throw this.metrics.errors?.increment({inbound:!0}),o}finally{n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t={}){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),o;return n!=null&&(o=De(n),await this.shouldBlockConnection("denyOutboundConnection",o,e)),await this._performUpgrade(e,"outbound",t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),n}}async _performUpgrade(e,t,n){let o,i,s,a,c,l=AbortSignal.timeout(t==="inbound"?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),d=pe([l,n.signal]);H(1/0,l,d),n.signal=d,this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let u=e;if(n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),u=await f.protect(e,n))}try{if(o=u,n?.skipEncryption!==!0){n?.onProgress?.(new F(`upgrader:encrypt-${t}-connection`)),{conn:o,remotePeer:i,protocol:c}=await(t==="inbound"?this._encryptInbound(u,{...n,signal:d}):this._encryptOutbound(u,{...n,signal:d}));let f={...u,...o};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",i,f)}else{let f=e.remoteAddr.getPeerId();if(f==null)throw new vo(`${t} connection that skipped encryption must have a peer id`);let h=De(f);c="native",i=h}if(i.equals(this.components.peerId)){let f=new xs("Can not dial self");throw e.abort(f),f}if(s=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(this.streamMuxers.size>0){n?.onProgress?.(new F(`upgrader:multiplex-${t}-connection`));let f=await(t==="inbound"?this._multiplexInbound({...u,...o},this.streamMuxers,n):this._multiplexOutbound({...u,...o},this.streamMuxers,n));a=f.muxerFactory,s=f.stream}}catch(f){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,f),f}finally{d.clear()}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",i,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:s,muxerFactory:a,remotePeer:i,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:i,remotePeer:s,muxerFactory:a,limits:c}=e,l,d,u;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:p=>{u!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),g=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);H(1/0,g);let{stream:y,protocol:w}=await Xl(p,m,{signal:g,log:p.log,yieldBytes:!1});if(u==null)return;u.log("incoming stream opened on %s",w);let b=bL(w,this.components.registrar);if(tv(w,"inbound",u)===b){let A=new mu(`Too many inbound protocol streams for protocol "${w}" - limit ${b}`);throw p.abort(A),A}p.source=y.source,p.sink=y.sink,p.protocol=w,y.closeWrite!=null&&(p.closeWrite=y.closeWrite),y.closeRead!=null&&(p.closeRead=y.closeRead),y.close!=null&&(p.close=y.close),await this.components.peerStore.merge(s,{protocols:[w]}),this.components.metrics?.trackProtocolStream(p,u),this._onStream({connection:u,stream:p,protocol:w})}).catch(async m=>{u.log.error("error handling incoming stream id %s - %e",p.id,m),p.timeline.close==null&&await p.close()})}}),d=async(p,m={})=>{if(l==null)throw new ds("Connection is not multiplexed");u.log.trace("starting new stream for protocols %s",p);let g=await l.newStream();u.log.trace("started new stream %s for protocols %s",g.id,p);try{if(m.signal==null){g.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let A=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);H(1/0,A),m={...m,signal:A}}g.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:w}=await Yl(g,p,{...m,log:g.log,yieldBytes:!0});g.log.trace("selected protocol %s",w);let b=EL(w,this.components.registrar,m),E=tv(w,"outbound",u);if(E>=b){let A=new _o(`Too many outbound protocol streams for protocol "${w}" - ${E}/${b}`);throw g.abort(A),A}return await this.components.peerStore.merge(s,{protocols:[w]}),g.source=y.source,g.sink=y.sink,g.protocol=w,y.closeWrite!=null&&(g.closeWrite=y.closeWrite),y.closeRead!=null&&(g.closeRead=y.closeRead),y.close!=null&&(g.close=y.close),this.components.metrics?.trackProtocolStream(g,u),g}catch(y){throw u.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,p,y),g.timeline.close==null&&g.abort(y),y}},Promise.all([l.sink(i.source),i.sink(l.source)]).catch(p=>{u.log.error("error piping data through muxer - %e",p)}));let f=o.timeline;o.timeline=new Proxy(f,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&f.close==null&&(async()=>{try{u.status==="open"&&await u.close()}catch(m){u.log.error("error closing connection after timeline close %e",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(m=>{u.log.error("error thrown while dispatching connection:close event %e",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new ds("Connection is not multiplexed")};return u=ev({remoteAddr:o.remoteAddr,remotePeer:s,status:"open",direction:n,timeline:o.timeline,multiplexer:l?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:d??h,getStreams:()=>l?.streams??[],close:async p=>{await l?.close(p),await o.close(p)},abort:p=>{o.abort(p),l?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:u}),u.__maConnTimeline=f,u}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:i,options:s}=this.components.registrar.getHandler(o);if(t.limits!=null&&s.runOnLimitedConnection!==!0)throw new vs("Cannot open protocol stream on limited connection");i({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:i}=await Xl(e,n,{...t,log:e.log}),s=this.connectionEncrypters.get(i);if(s==null)throw new fs(`no crypto module found for ${i}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,i),{...await s.secureInbound(o,t),protocol:i}}catch(o){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,o),new fs(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:i}=await Yl(e,n,{...t,log:e.log,yieldBytes:!0}),s=this.connectionEncrypters.get(i);if(s==null)throw new fs(`no crypto module found for ${i}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,i),{...await s.secureOutbound(o,t),protocol:i}}catch(o){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,o),new fs(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let{stream:i,protocol:s}=await Yl(e,o,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let a=t.get(s);return{stream:i,muxerFactory:a}}catch(i){throw e.log.error("error multiplexing outbound connection",i),new ds(String(i))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{let{stream:i,protocol:s}=await Xl(e,o,{...n,log:e.log}),a=t.get(s);return{stream:i,muxerFactory:a}}catch(i){throw e.log.error("error multiplexing inbound connection",i),new ds(String(i))}}};var s0=class extends we{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new we,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),l=this.dispatchEvent(new CustomEvent(a.type,{detail:a.detail}));return c||l},H(1/0,t),this.peerId=e.peerId,this.logger=e.logger??Vo(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=Lx({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:Ip,version:Ap},logger:this.logger,events:t,datastore:e.datastore??new Lp,connectionGater:Bx(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",Px(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(l=>l.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new i0(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),streamMuxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,outboundUpgradeTimeout:e.connectionManager?.outboundUpgradeTimeout}),this.configureComponent("transportManager",new o0(this.components,e.transportManager)),this.configureComponent("connectionManager",new Zp(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new Jp(this.components,e.connectionMonitor)),this.configureComponent("registrar",new n0(this.components)),this.configureComponent("addressManager",new Op(this.components,e.addresses));let i=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new t0(this.components,{routers:i}));let s=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new e0(this.components,{routers:s})),this.configureComponent("randomWalk",new r0(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],l=c(this.components);if(l==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=l,this.configureComponent(a,l),l[xn]!=null&&(this.log("registering service %s for content routing",a),s.push(l[xn])),l[vn]!=null&&(this.log("registering service %s for peer routing",a),i.push(l[vn])),l[di]!=null&&(this.log("registering service %s for peer discovery",a),l[di].addEventListener?.("peer",d=>{this.#e(d)}))}Ox(o)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new hr;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new P("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new P("no protocols were provided to open a stream");return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Yo(e)&&(e=De(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.name!=="NotFoundError")throw s}let n=be([C("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),i=it(o);return await this.peerStore.patch(e,{publicKey:i}),i}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function a0(r={}){r.privateKey??=await Hd("Ed25519");let e=new s0({...await Ix(r),peerId:F5(r.privateKey)});return r.start!==!1&&await e.start(),e}async function rv(r){let e=r.libp2p?.privateKey,t=r.logger??Vo(),n=new Ie("/pkcs8/self"),o;if(e==null&&r.datastore!=null)if(o=np(r.keychain)({datastore:r.datastore,logger:t}),r.libp2p=r.libp2p??{},await r.datastore.has(n))r.libp2p.privateKey=await o.exportKey("self");else{let a=await Hd("Ed25519");r.libp2p.privateKey=a,await o.importKey("self",a)}let i=zl(r);return i.datastore=i.datastore??r.datastore,r=r??{},await a0({...i,...r.libp2p,start:!1})}async function nv(r={}){let e=r.datastore??new Al,t=r.blockstore??new Sl,n;xL(r.libp2p)?n=r.libp2p:n=await rv({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e});let o=new u1({...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[ul(),tl()],routers:r.routers??[vl(n),xl()],metrics:n.metrics});return r.start!==!1&&await o.start(),o}function xL(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}function ov(){let r=zl();r.start=!1,r.addresses={listen:[]},r.transports=[xp(),_p()],r.peerDiscovery=[];let e={dcutr:r.services.dcutr,identify:r.services.identify,keychain:r.services.keychain,ping:r.services.ping};return{...r,start:!1,services:e}}var G4=ct(c0(),1);var W4=40;function Y4(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=G4.default.decode(r);return e.seek(G4.default.decode.bytes),t}function X4(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}var ci={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},Ql={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":ci.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(ci.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Ql["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=Ql["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:ci.Int,CarV1HeaderOrV2Pragma:r=>{if(ci.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=Ql["CarV1HeaderOrV2Pragma > roots (anon)"](r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Ql.Int(r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},jl={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":ci.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(ci.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=jl["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=jl["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:ci.Int,CarV1HeaderOrV2Pragma:r=>{if(ci.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=jl["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=jl.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},Q4={toTyped:Ql.CarV1HeaderOrV2Pragma,toRepresentation:jl.CarV1HeaderOrV2Pragma};var lge=Vm();var UL=ct(c0(),1);var pge=[new M(x.map,2),new M(x.string,"version"),new M(x.uint,1),new M(x.string,"roots")],mge=new M(x.tag,42);async function j4(r,e){let t=Y4(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),o=Wo(n);if(Q4.toTyped(o)===void 0)throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||e!==void 0&&o.version!==e)throw new Error(`Invalid CAR version: ${o.version}${e!==void 0?` (expected ${e})`:""}`);if(o.version===1){if(!Array.isArray(o.roots))throw new Error("Invalid CAR header format");return o}if(o.roots!==void 0)throw new Error("Invalid CAR header format");let i=X4(await r.exactly(W4,!0));r.seek(i.dataOffset-r.pos);let s=await j4(r,1);return Object.assign(s,i)}function Zl(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let o=r.subarray(e,e+t);return n&&(e+=t),o},seek(t){e+=t},get pos(){return e}}}var Z4=ct(c0(),1),gv=1;function J4(r){let e=ea({version:gv,roots:r}),t=Z4.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function yv(r){return{async setRoots(e){let t=J4(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(Z4.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return gv}}}function l0(){}function wv(){let r=[],e=null,t=l0,n=!1,o=null,i=l0,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=l0,l()}})),e),a={write(l){r.push(l);let d=s();return i(),d},async end(){n=!0;let l=s();i(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&t(),{done:!1,value:l}):n?(t(),{done:!0,value:void 0}):(o||(o=new Promise(d=>{i=()=>(o=null,i=l0,d(c.next()))})),o)}};return{writer:a,iterator:c}}var Jl=class r{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=K.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(e){e=VL(e);let{encoder:t,iterator:n}=bv(),o=new r(e,t),i=new u0(n);return{writer:o,out:i}}static createAppender(){let{encoder:e,iterator:t}=bv();e.setRoots=()=>Promise.resolve();let n=new r([],e),o=new u0(t);return{writer:n,out:o}}static async updateRootsInBytes(e,t){let n=Zl(e);await j4(n);let o=J4(t);if(Number(n.pos)!==o.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${o.length} bytes)`);return e.set(o,0),e}},u0=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function bv(){let r=wv(),{writer:e,iterator:t}=r;return{encoder:yv(e),iterator:t}}function VL(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=K.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=K.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var KL=1,e6=class{components;constructor(e,t){this.components=e}async import(e,t){await rt(this.components.blockstore.putMany(We(e.blocks(),({cid:n,bytes:o})=>({cid:n,block:o})),t))}async export(e,t,n){let o=ee(),i=Array.isArray(e)?e:[e],s=new mr({concurrency:KL});s.on("idle",()=>{o.resolve()}),s.on("error",a=>{s.clear(),o.reject(a)});for(let a of i)s.add(async()=>{await this.#e(a,s,async(c,l)=>{n?.blockFilter?.has(c.multihash.bytes)!==!0&&(n?.blockFilter?.add(c.multihash.bytes),await t.put({cid:c,bytes:l}))},n)}).catch(()=>{});try{await o.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:o}=Jl.create(e);this.export(e,n,t).catch(()=>{});for await(let i of o)yield i}async#e(e,t,n,o){let i=await this.components.getCodec(e.code),s=await this.components.blockstore.get(e,o);await n(e,s);let a=wf({bytes:s,cid:e,codec:i});for await(let[,c]of a.links())t.add(async()=>{await this.#e(c,t,n,o)})}};function Ev(r,e={}){return new e6(r,e)}function qL(r){return r[Symbol.asyncIterator]!=null}function zL(r){if(qL(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var xv=zL;var d0=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},Yr=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},f0=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},Et=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},h0=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},p0=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},m0=class r extends Error{static name="NoPropError";static code="ERR_NO_PROP";name=r.name;code=r.code;constructor(e="No Property found"){super(e)}},ms=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};function Ga(r,e,t,n,o,i,s){let a=r,c=o;for(;i.length>0;){let l=i[0];if(l in a){i.shift(),c=`${c}/${l}`;let d=K.asCID(a[l]);if(d!=null)return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:d,name:l,path:c,toResolve:i}};a=a[l]}else throw new m0(`No property named ${l} found in node ${t}`)}return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}}}}var GL=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=Wo(c);return Ga(l,c,r,e,t,n,i)},vv=GL;var WL=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=ra(c);return Ga(l,c,r,e,t,n,i)},Sv=WL;function YL(r,e,t,n){let o=BigInt(r.length),i=BigInt(e+o);return t>=i||n<e?new Uint8Array(0):(n>=e&&n<i&&(r=r.subarray(0,Number(n-e))),t>=e&&t<i&&(r=r.subarray(Number(t-e))),r)}var gs=YL;var XL=(r,e=0,t=r)=>{let n=BigInt(r),o=BigInt(e??0),i=BigInt(t);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw new ms("Offset must be greater than or equal to 0");if(o>n)throw new ms("Offset must be less than the file size");if(i<0n)throw new ms("Length must be greater than or equal to 0");if(i>n)throw new ms("Length must be less than the file size");return{start:o,end:i}},Wa=XL;var QL=r=>{async function*e(t={}){let{start:n,end:o}=Wa(r.length,t.offset,t.length),i=gs(r,0n,n,o);t.onProgress?.(new F("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},jL=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw new Yr(`No link named ${t} found in raw node ${r}`);let c=Ee(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:QL(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},_v=jL;var ZL=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=w2(c);return Ga(l,c,r,e,t,n,i)},Av=ZL;var JL=r=>{async function*e(t={}){let{start:n,end:o}=Wa(r.length,t.offset,t.length),i=gs(r,0n,n,o);t.onProgress?.(new F("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},eO=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw new Yr(`No link named ${t} found in raw node ${r}`);let c=await s.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:JL(c),depth:i,size:BigInt(c.length),node:c}}},Iv=eO;var eu=class r extends Error{static name="InvalidTypeError";static code="ERR_INVALID_TYPE";name=r.name;code=r.code;constructor(e="Invalid type"){super(e)}};var En;(function(r){let e;(function(o){o.Raw="Raw",o.Directory="Directory",o.File="File",o.Metadata="Metadata",o.Symlink="Symlink",o.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(o){o[o.Raw=0]="Raw",o[o.Directory=1]="Directory",o[o.File=2]="File",o[o.Metadata=3]="Metadata",o[o.Symlink=4]="Symlink",o[o.HAMTShard=5]="HAMTShard"})(t||(t={})),function(o){o.codec=()=>Me(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=ne((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),r.DataType.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),o.filesize!=null&&(i.uint32(24),i.uint64(o.filesize)),o.blocksizes!=null)for(let a of o.blocksizes)i.uint32(32),i.uint64(a);o.hashType!=null&&(i.uint32(40),i.uint64(o.hashType)),o.fanout!=null&&(i.uint32(48),i.uint64(o.fanout)),o.mode!=null&&(i.uint32(56),i.uint32(o.mode)),o.mtime!=null&&(i.uint32(66),g0.codec().encode(o.mtime,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let s={blocksizes:[]},a=i==null?o.len:o.pos+i;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:s.Type=r.DataType.codec().decode(o);break;case 2:s.Data=o.bytes();break;case 3:s.filesize=o.uint64();break;case 4:s.blocksizes.push(o.uint64());break;case 5:s.hashType=o.uint64();break;case 6:s.fanout=o.uint64();break;case 7:s.mode=o.uint32();break;case 8:s.mtime=g0.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>re(o,r.codec()),r.decode=o=>te(o,r.codec())})(En||(En={}));var g0;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Seconds=t.int64();break;case 2:o.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(g0||(g0={}));var Tv;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.MimeType=t.string();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Tv||(Tv={}));var kv={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},tO=["directory","hamt-sharded-directory"],Cv=parseInt("0644",8),Rv=parseInt("0755",8),Bn=class r{static unmarshal(e){let t=En.decode(e),n=new r({type:kv[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:o,hashType:i,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(kv).includes(t))throw new eu("Type: "+t+" is not valid");this.type=t??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?Rv:Cv:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return tO.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=En.DataType.Raw;break;case"directory":e=En.DataType.Directory;break;case"file":e=En.DataType.File;break;case"metadata":e=En.DataType.Metadata;break;case"symlink":e=En.DataType.Symlink;break;case"hamt-sharded-directory":e=En.DataType.HAMTShard;break;default:throw new eu(`Type: ${e} is not valid`)}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===Cv&&!this.isDirectory()&&(n=void 0),n===Rv&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),En.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var y0=ct(bm(),1);function rO(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var B4e=wi({name:"murmur3-32",code:35,encode:r=>rO(y0.default.x86.hash32(r))}),Pv=wi({name:"murmur3-128",code:34,encode:r=>gi.fromHex(y0.default.x64.hash128(r))}),M4e=wi({name:"murmur3-x64-64",code:34,encode:r=>gi.fromHex(y0.default.x64.hash128(r)).subarray(0,8)});var Ov=ct(Lv(),1);var ys=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new Ov.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof r?o.push(i.serialize(e,t)):o.push(e(i,s))),o),n))}async asyncTransform(e,t){return Bv(this,e,t)}toJSON(){return this.serialize(aO,cO)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?C(e):e),n=await t.take(this._options.bits),o=this._children.get(n);return o instanceof r?o._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:o}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let o=await n._findPlace(t.existingChild.hash);return o.bucket._putAt(o,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(sO);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function sO(r){return!!r}function aO(r,e){return r.key}function cO(r){return r}async function Bv(r,e,t){let n=[];for(let o of r._children.compactArray())if(o instanceof ys)await Bv(o,e,t);else{let i=await e(o);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var lO=[255,254,252,248,240,224,192,128],uO=[1,3,7,15,31,63,127,255],w0=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=dO(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function dO(r,e,t){let n=fO(e,t);return(r&n)>>>e}function fO(r,e){return lO[r]&uO[Math.min(e+r-1,7)]}function Mv(r){function e(t){return t instanceof b0?t:new b0(t,r)}return e}var b0=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?be([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new w0(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Uv(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:Mv(r.hashFn)};return new ys(e)}var hO=async function(r){return(await Pv.encode(r)).slice(0,8).reverse()},pO=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async o=>{if(o.Name==null)throw new Error("Unexpected Link without a Name");if(o.Name.length===n){let i=parseInt(o.Name,16);e._putObjectAt(i,new ys({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(o.Name.substring(2),!0)}))},Fv=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),mO=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},$v=async(r,e,t,n,o)=>{if(n==null){if(r.Data==null)throw new Et("no data in PBNode");let u;try{u=Bn.unmarshal(r.Data)}catch(h){throw new Et(h.message)}if(u.type!=="hamt-sharded-directory")throw new Et("not a HAMT");if(u.fanout==null)throw new Et("missing fanout");let f=Uv({hashFn:hO,bits:Math.log2(Number(u.fanout))});n={rootBucket:f,hamtDepth:1,lastBucket:f}}let i=(n.lastBucket.tableSize()-1).toString(16).length;await pO(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=Fv(s.pos,i),c=mO(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=Fv(n.lastBucket._posAtParent,i));let l=r.Links.find(u=>{if(u.Name==null)return!1;let f=u.Name.substring(0,i),h=u.Name.substring(i);return!(f!==a||h!==""&&h!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(i)===e)return l.Hash;n.hamtDepth++;let d=await t.get(l.Hash,o);return r=lo(d),$v(r,e,t,n,o)},Hv=$v;var gO=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=c.offset??0,d=c.length??e.Links.length,u=e.Links.slice(l,d);c.onProgress?.(new F("unixfs:exporter:walk:directory",{cid:r})),yield*Ne(u,f=>We(f,h=>async()=>{let p=h.Name??"",m=`${n}/${p}`;return(await o(h.Hash,p,m,[],i+1,s,c)).entry}),f=>bt(f,{ordered:!0,concurrency:c.blockReadConcurrency}),f=>dt(f,h=>h!=null))}return a},Vv=gO;async function Kv(r,e,t,n,o,i,s){if(e instanceof Uint8Array){let l=gs(e,n,o,i);t.push(l);return}if(e.Data==null)throw new Et("no data in PBNode");let a;try{a=Bn.unmarshal(e.Data)}catch(l){throw new Et(l.message)}if(a.data!=null){let l=a.data,d=gs(l,n,o,i);t.push(d),n+=BigInt(d.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new Et("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let d=e.Links[l],u=n,f=u+a.blockSizes[l];if((o>=u&&o<f||i>=u&&i<=f||o<u&&i>f)&&c.push({link:d,blockStart:n}),n=f,n>i)break}await Ne(c,l=>We(l,d=>async()=>{let u=await r.get(d.link.Hash,s);return{...d,block:u}}),l=>bt(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:d,block:u,blockStart:f}of l){let h;switch(d.Hash.code){case Kr:h=lo(u);break;case Ht:h=u;break;default:t.end(new Et(`Unsupported codec: ${d.Hash.code}`));return}let p=new mr({concurrency:1});p.on("error",m=>{t.end(m)}),p.add(async()=>{s.onProgress?.(new F("unixfs:exporter:walk:file",{cid:d.Hash})),await Kv(r,h,t,f,o,i,s)}),await p.onIdle()}}),n>=i&&t.end()}var yO=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:d,end:u}=Wa(l,c.offset,c.length);if(u===0n)return;let f=0n,h=u-d,p=xt();c.onProgress?.(new F("unixfs:exporter:walk:file",{cid:r})),Kv(s,e,p,0n,d,u,c).catch(m=>{p.end(m)});for await(let m of p)if(m!=null){if(f+=BigInt(m.byteLength),f>h)throw p.end(),new h0("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");f===h&&p.end(),c.onProgress?.(new F("unixfs:exporter:progress:unixfs:file",{bytesRead:f,totalBytes:h,fileSize:l})),yield m}if(f<h)throw new p0("Traversed entire DAG but did not read enough bytes")}return a},t6=yO;var wO=(r,e,t,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new F("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),qv(e,n,o,i,s,c)}return a};async function*qv(r,e,t,n,o,i){let s=r.Links;if(r.Data==null)throw new Et("no data in PBNode");let a;try{a=Bn.unmarshal(r.Data)}catch(d){throw new Et(d.message)}if(a.fanout==null)throw new Et("missing fanout");let c=(a.fanout-1n).toString(16).length,l=Ne(s,d=>We(d,u=>async()=>{let f=u.Name!=null?u.Name.substring(c):null;if(f!=null&&f!==""){let h=await t(u.Hash,f,`${e}/${f}`,[],n+1,o,i);return{entries:h.entry==null?[]:[h.entry]}}else{let h=await o.get(u.Hash,i);return r=lo(h),i.onProgress?.(new F("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:qv(r,e,t,n,o,i)}}}),d=>bt(d,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:d}of l)yield*d}var zv=wO;var bO=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,EO={raw:t6,file:t6,directory:Vv,"hamt-sharded-directory":zv,metadata:(r,e,t,n,o,i,s)=>()=>[],symlink:(r,e,t,n,o,i,s)=>()=>[]},xO=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=lo(c),d,u;if(e==null&&(e=r.toString()),l.Data==null)throw new Et("no data in PBNode");try{d=Bn.unmarshal(l.Data)}catch(h){throw new Et(h.message)}if(t==null&&(t=e),n.length>0){let h;if(d?.type==="hamt-sharded-directory"?h=await Hv(l,n[0],s):h=bO(l,n[0]),h==null)throw new Yr("file does not exist");let p=n.shift(),m=`${t}/${p}`;u={cid:h,toResolve:n,name:p??"",path:m}}let f=EO[d.type](r,l,d,t,o,i,s);if(f==null)throw new Yr("could not find content exporter");return d.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:f,unixfs:d,depth:i,node:l,size:d.fileSize()},next:u}:{entry:{type:"file",name:e,path:t,cid:r,content:f,unixfs:d,depth:i,node:l,size:d.fileSize()},next:u}},Gv=xO;var vO={[Kr]:Gv,[Ht]:Iv,[ao]:vv,[co]:Sv,[vt.code]:_v,[Hn]:Av},Wv=async(r,e,t,n,o,i,s)=>{let a=vO[r.code];if(a==null)throw new f0(`No resolver for code ${r.code}`);return a(r,e,t,n,Wv,o,i,s)},Yv=Wv;var SO=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),_O=r=>{if(r instanceof Uint8Array)return{cid:K.decode(r),toResolve:[]};let e=K.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=SO(r);return{cid:K.parse(t[0]),toResolve:t.slice(1)}}throw new d0(`Unknown path type ${r}`)};async function*r6(r,e,t={}){let{cid:n,toResolve:o}=_O(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await Yv(n,i,s,o,a,e,t);if(c.entry==null&&c.next==null)throw new Yr(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;o=c.next.toResolve,n=c.next.cid,i=c.next.name,s=c.next.path}}async function Ya(r,e,t={}){let n=await xv(r6(r,e,t));if(n==null)throw new Yr(`Could not resolve ${r}`);return n}async function*Xv(r,e,t={}){let n=await Ya(r,e,t);if(n==null)return;if(yield n,n.type==="directory")for await(let i of o(n,t))yield i;async function*o(i,s){for await(let a of i.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*o(a,s))}}function E0(r,e={}){let t=Ia(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:i,done:s}=await t.next();if(this._cancelled)return;if(s===!0){o.close();return}o.enqueue(i)}catch(i){o.error(i)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}var Xa=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,jv=new Set,n6=typeof process=="object"&&process?process:{},Zv=(r,e,t,n)=>{typeof n6.emitWarning=="function"?n6.emitWarning(r,e,t,n):console.error(`[${t}] ${e}: ${r}`)},x0=globalThis.AbortController,Qv=globalThis.AbortSignal;if(typeof x0>"u"){Qv=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,o){this._onabort.push(o)}},x0=class{constructor(){e()}signal=new Qv;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let o of this.signal._onabort)o(n);this.signal.onabort?.(n)}}};let r=n6.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=!1,Zv("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var AO=r=>!jv.has(r),e8e=Symbol("type"),li=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),Jv=r=>li(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?Qa:null:null,Qa=class extends Array{constructor(e){super(e),this.fill(0)}},o6=class r{heap;length;static#e=!1;static create(e){let t=Jv(e);if(!t)return[];r.#e=!0;let n=new r(e,t);return r.#e=!1,n}constructor(e,t){if(!r.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},v0=class r{#e;#r;#n;#c;#g;#S;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#y;#o;#s;#t;#f;#l;#h;#u;#b;#d;#E;#x;#m;#w;#_;#p;static unsafeExposeInternals(e){return{starts:e.#x,ttls:e.#m,sizes:e.#E,keyMap:e.#o,keyList:e.#s,valList:e.#t,next:e.#f,prev:e.#l,get head(){return e.#h},get tail(){return e.#u},free:e.#b,isBackgroundFetch:t=>e.#a(t),backgroundFetch:(t,n,o,i)=>e.#O(t,n,o,i),moveToTail:t=>e.#N(t),indexes:t=>e.#I(t),rindexes:t=>e.#T(t),isStale:t=>e.#v(t)}}get max(){return this.#e}get maxSize(){return this.#r}get calculatedSize(){return this.#y}get size(){return this.#i}get fetchMethod(){return this.#g}get memoMethod(){return this.#S}get dispose(){return this.#n}get disposeAfter(){return this.#c}constructor(e){let{max:t=0,ttl:n,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:l,disposeAfter:d,noDisposeOnSet:u,noUpdateTTL:f,maxSize:h=0,maxEntrySize:p=0,sizeCalculation:m,fetchMethod:g,memoMethod:y,noDeleteOnFetchRejection:w,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:A,ignoreFetchAbort:k}=e;if(t!==0&&!li(t))throw new TypeError("max option must be a nonnegative integer");let v=t?Jv(t):Array;if(!v)throw new Error("invalid max value: "+t);if(this.#e=t,this.#r=h,this.maxEntrySize=p||this.#r,this.sizeCalculation=m,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#S=y,g!==void 0&&typeof g!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#g=g,this.#_=!!g,this.#o=new Map,this.#s=new Array(t).fill(void 0),this.#t=new Array(t).fill(void 0),this.#f=new v(t),this.#l=new v(t),this.#h=0,this.#u=0,this.#b=o6.create(t),this.#i=0,this.#y=0,typeof l=="function"&&(this.#n=l),typeof d=="function"?(this.#c=d,this.#d=[]):(this.#c=void 0,this.#d=void 0),this.#w=!!this.#n,this.#p=!!this.#c,this.noDisposeOnSet=!!u,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!w,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!k,this.maxEntrySize!==0){if(this.#r!==0&&!li(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!li(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#H()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=li(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!li(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#R()}if(this.#e===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#r){let S="LRU_CACHE_UNBOUNDED";AO(S)&&(jv.add(S),Zv("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",S,r))}}getRemainingTTL(e){return this.#o.has(e)?1/0:0}#R(){let e=new Qa(this.#e),t=new Qa(this.#e);this.#m=e,this.#x=t,this.#B=(i,s,a=Xa.now())=>{if(t[i]=s!==0?a:0,e[i]=s,s!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#v(i)&&this.#k(this.#s[i],"expire")},s+1);c.unref&&c.unref()}},this.#A=i=>{t[i]=e[i]!==0?Xa.now():0},this.#C=(i,s)=>{if(e[s]){let a=e[s],c=t[s];if(!a||!c)return;i.ttl=a,i.start=c,i.now=n||o();let l=i.now-c;i.remainingTTL=a-l}};let n=0,o=()=>{let i=Xa.now();if(this.ttlResolution>0){n=i;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=this.#o.get(i);if(s===void 0)return 0;let a=e[s],c=t[s];if(!a||!c)return 1/0;let l=(n||o())-c;return a-l},this.#v=i=>{let s=t[i],a=e[i];return!!a&&!!s&&(n||o())-s>a}}#A=()=>{};#C=()=>{};#B=()=>{};#v=()=>!1;#H(){let e=new Qa(this.#e);this.#y=0,this.#E=e,this.#P=t=>{this.#y-=e[t],e[t]=0},this.#M=(t,n,o,i)=>{if(this.#a(n))return 0;if(!li(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(n,t),!li(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#D=(t,n,o)=>{if(e[t]=n,this.#r){let i=this.#r-e[t];for(;this.#y>i;)this.#L(!0)}this.#y+=e[t],o&&(o.entrySize=n,o.totalCalculatedSize=this.#y)}}#P=e=>{};#D=(e,t,n)=>{};#M=(e,t,n,o)=>{if(n||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#I({allowStale:e=this.allowStale}={}){if(this.#i)for(let t=this.#u;!(!this.#U(t)||((e||!this.#v(t))&&(yield t),t===this.#h));)t=this.#l[t]}*#T({allowStale:e=this.allowStale}={}){if(this.#i)for(let t=this.#h;!(!this.#U(t)||((e||!this.#v(t))&&(yield t),t===this.#u));)t=this.#f[t]}#U(e){return e!==void 0&&this.#o.get(this.#s[e])===e}*entries(){for(let e of this.#I())this.#t[e]!==void 0&&this.#s[e]!==void 0&&!this.#a(this.#t[e])&&(yield[this.#s[e],this.#t[e]])}*rentries(){for(let e of this.#T())this.#t[e]!==void 0&&this.#s[e]!==void 0&&!this.#a(this.#t[e])&&(yield[this.#s[e],this.#t[e]])}*keys(){for(let e of this.#I()){let t=this.#s[e];t!==void 0&&!this.#a(this.#t[e])&&(yield t)}}*rkeys(){for(let e of this.#T()){let t=this.#s[e];t!==void 0&&!this.#a(this.#t[e])&&(yield t)}}*values(){for(let e of this.#I())this.#t[e]!==void 0&&!this.#a(this.#t[e])&&(yield this.#t[e])}*rvalues(){for(let e of this.#T())this.#t[e]!==void 0&&!this.#a(this.#t[e])&&(yield this.#t[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#I()){let o=this.#t[n],i=this.#a(o)?o.__staleWhileFetching:o;if(i!==void 0&&e(i,this.#s[n],this))return this.get(this.#s[n],t)}}forEach(e,t=this){for(let n of this.#I()){let o=this.#t[n],i=this.#a(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#s[n],this)}}rforEach(e,t=this){for(let n of this.#T()){let o=this.#t[n],i=this.#a(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#s[n],this)}}purgeStale(){let e=!1;for(let t of this.#T({allowStale:!0}))this.#v(t)&&(this.#k(this.#s[t],"expire"),e=!0);return e}info(e){let t=this.#o.get(e);if(t===void 0)return;let n=this.#t[t],o=this.#a(n)?n.__staleWhileFetching:n;if(o===void 0)return;let i={value:o};if(this.#m&&this.#x){let s=this.#m[t],a=this.#x[t];if(s&&a){let c=s-(Xa.now()-a);i.ttl=c,i.start=Date.now()}}return this.#E&&(i.size=this.#E[t]),i}dump(){let e=[];for(let t of this.#I({allowStale:!0})){let n=this.#s[t],o=this.#t[t],i=this.#a(o)?o.__staleWhileFetching:o;if(i===void 0||n===void 0)continue;let s={value:i};if(this.#m&&this.#x){s.ttl=this.#m[t];let a=Xa.now()-this.#x[t];s.start=Math.floor(Date.now()-a)}this.#E&&(s.size=this.#E[t]),e.unshift([n,s])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let o=Date.now()-n.start;n.start=Xa.now()-o}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=n,{noUpdateTTL:l=this.noUpdateTTL}=n,d=this.#M(e,t,n.size||0,a);if(this.maxEntrySize&&d>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#k(e,"set"),this;let u=this.#i===0?void 0:this.#o.get(e);if(u===void 0)u=this.#i===0?this.#u:this.#b.length!==0?this.#b.pop():this.#i===this.#e?this.#L(!1):this.#i,this.#s[u]=e,this.#t[u]=t,this.#o.set(e,u),this.#f[this.#u]=u,this.#l[u]=this.#u,this.#u=u,this.#i++,this.#D(u,d,c),c&&(c.set="add"),l=!1;else{this.#N(u);let f=this.#t[u];if(t!==f){if(this.#_&&this.#a(f)){f.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:h}=f;h!==void 0&&!s&&(this.#w&&this.#n?.(h,e,"set"),this.#p&&this.#d?.push([h,e,"set"]))}else s||(this.#w&&this.#n?.(f,e,"set"),this.#p&&this.#d?.push([f,e,"set"]));if(this.#P(u),this.#D(u,d,c),this.#t[u]=t,c){c.set="replace";let h=f&&this.#a(f)?f.__staleWhileFetching:f;h!==void 0&&(c.oldValue=h)}}else c&&(c.set="update")}if(o!==0&&!this.#m&&this.#R(),this.#m&&(l||this.#B(u,o,i),c&&this.#C(c,u)),!s&&this.#p&&this.#d){let f=this.#d,h;for(;h=f?.shift();)this.#c?.(...h)}return this}pop(){try{for(;this.#i;){let e=this.#t[this.#h];if(this.#L(!0),this.#a(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#p&&this.#d){let e=this.#d,t;for(;t=e?.shift();)this.#c?.(...t)}}}#L(e){let t=this.#h,n=this.#s[t],o=this.#t[t];return this.#_&&this.#a(o)?o.__abortController.abort(new Error("evicted")):(this.#w||this.#p)&&(this.#w&&this.#n?.(o,n,"evict"),this.#p&&this.#d?.push([o,n,"evict"])),this.#P(t),e&&(this.#s[t]=void 0,this.#t[t]=void 0,this.#b.push(t)),this.#i===1?(this.#h=this.#u=0,this.#b.length=0):this.#h=this.#f[t],this.#o.delete(n),this.#i--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:o}=t,i=this.#o.get(e);if(i!==void 0){let s=this.#t[i];if(this.#a(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#v(i))o&&(o.has="stale",this.#C(o,i));else return n&&this.#A(i),o&&(o.has="hit",this.#C(o,i)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,o=this.#o.get(e);if(o===void 0||!n&&this.#v(o))return;let i=this.#t[o];return this.#a(i)?i.__staleWhileFetching:i}#O(e,t,n,o){let i=t===void 0?void 0:this.#t[t];if(this.#a(i))return i;let s=new x0,{signal:a}=n;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:n,context:o},l=(m,g=!1)=>{let{aborted:y}=s.signal,w=n.ignoreFetchAbort&&m!==void 0;if(n.status&&(y&&!g?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,w&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),y&&!w&&!g)return u(s.signal.reason);let b=h;return this.#t[t]===h&&(m===void 0?b.__staleWhileFetching?this.#t[t]=b.__staleWhileFetching:this.#k(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,m,c.options))),m},d=m=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=m),u(m)),u=m=>{let{aborted:g}=s.signal,y=g&&n.allowStaleOnFetchAbort,w=y||n.allowStaleOnFetchRejection,b=w||n.noDeleteOnFetchRejection,E=h;if(this.#t[t]===h&&(!b||E.__staleWhileFetching===void 0?this.#k(e,"fetch"):y||(this.#t[t]=E.__staleWhileFetching)),w)return n.status&&E.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),E.__staleWhileFetching;if(E.__returned===E)throw m},f=(m,g)=>{let y=this.#g?.(e,i,c);y&&y instanceof Promise&&y.then(w=>m(w===void 0?void 0:w),g),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(m(void 0),n.allowStaleOnFetchAbort&&(m=w=>l(w,!0)))})};n.status&&(n.status.fetchDispatched=!0);let h=new Promise(f).then(l,d),p=Object.assign(h,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...c.options,status:void 0}),t=this.#o.get(e)):this.#t[t]=p,p}#a(e){if(!this.#_)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof x0}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:f=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:g=!1,status:y,signal:w}=t;if(!this.#_)return y&&(y.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:y});let b={allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:d,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:f,allowStaleOnFetchAbort:p,ignoreFetchAbort:h,status:y,signal:w},E=this.#o.get(e);if(E===void 0){y&&(y.fetch="miss");let A=this.#O(e,E,b,m);return A.__returned=A}else{let A=this.#t[E];if(this.#a(A)){let $=n&&A.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",$&&(y.returnedStale=!0)),$?A.__staleWhileFetching:A.__returned=A}let k=this.#v(E);if(!g&&!k)return y&&(y.fetch="hit"),this.#N(E),o&&this.#A(E),y&&this.#C(y,E),A;let v=this.#O(e,E,b,m),T=v.__staleWhileFetching!==void 0&&n;return y&&(y.fetch=k?"stale":"refresh",T&&k&&(y.returnedStale=!0)),T?v.__staleWhileFetching:v.__returned=v}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,t={}){let n=this.#S;if(!n)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...s}=t,a=this.get(e,s);if(!i&&a!==void 0)return a;let c=n(e,a,{options:s,context:o});return this.set(e,c,s),c}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,a=this.#o.get(e);if(a!==void 0){let c=this.#t[a],l=this.#a(c);return s&&this.#C(s,a),this.#v(a)?(s&&(s.get="stale"),l?(s&&n&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?c.__staleWhileFetching:void 0):(i||this.#k(e,"expire"),s&&n&&(s.returnedStale=!0),n?c:void 0)):(s&&(s.get="hit"),l?c.__staleWhileFetching:(this.#N(a),o&&this.#A(a),c))}else s&&(s.get="miss")}#F(e,t){this.#l[t]=e,this.#f[e]=t}#N(e){e!==this.#u&&(e===this.#h?this.#h=this.#f[e]:this.#F(this.#l[e],this.#f[e]),this.#F(this.#u,e),this.#u=e)}delete(e){return this.#k(e,"delete")}#k(e,t){let n=!1;if(this.#i!==0){let o=this.#o.get(e);if(o!==void 0)if(n=!0,this.#i===1)this.#$(t);else{this.#P(o);let i=this.#t[o];if(this.#a(i)?i.__abortController.abort(new Error("deleted")):(this.#w||this.#p)&&(this.#w&&this.#n?.(i,e,t),this.#p&&this.#d?.push([i,e,t])),this.#o.delete(e),this.#s[o]=void 0,this.#t[o]=void 0,o===this.#u)this.#u=this.#l[o];else if(o===this.#h)this.#h=this.#f[o];else{let s=this.#l[o];this.#f[s]=this.#f[o];let a=this.#f[o];this.#l[a]=this.#l[o]}this.#i--,this.#b.push(o)}}if(this.#p&&this.#d?.length){let o=this.#d,i;for(;i=o?.shift();)this.#c?.(...i)}return n}clear(){return this.#$("delete")}#$(e){for(let t of this.#T({allowStale:!0})){let n=this.#t[t];if(this.#a(n))n.__abortController.abort(new Error("deleted"));else{let o=this.#s[t];this.#w&&this.#n?.(n,o,e),this.#p&&this.#d?.push([n,o,e])}}if(this.#o.clear(),this.#t.fill(void 0),this.#s.fill(void 0),this.#m&&this.#x&&(this.#m.fill(0),this.#x.fill(0)),this.#E&&this.#E.fill(0),this.#h=0,this.#u=0,this.#b.length=0,this.#y=0,this.#i=0,this.#p&&this.#d){let t=this.#d,n;for(;n=t?.shift();)this.#c?.(...n)}}};var Nr=class extends Error{static name="InvalidRangeError";constructor(e="Invalid range request"){super(e),this.name="InvalidRangeError"}},S0=class extends Error{static name="NoContentError";constructor(e="No content found"){super(e),this.name="NoContentError"}},_0=class extends Error{static name="SubdomainNotSupportedError";constructor(e="Subdomain not supported"){super(e),this.name="SubdomainNotSupportedError"}};function eS(r,e){if(r==null)return;if(r instanceof Headers)return r.get(e)??void 0;if(Array.isArray(r))return r.find(([o])=>o.toLowerCase()===e.toLowerCase())?.[1];let t=Object.keys(r).find(n=>n.toLowerCase()===e.toLowerCase());if(t!=null)return r[t]}function tS(r,e,t){if((r??0)>(e??1/0))throw new Nr("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(e??0)>=(t??1/0))throw new Nr("Invalid range: Range-end index is greater than or equal to the size of the file.");if(r==null&&(e??0)>(t??1/0))throw new Nr("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new Nr("Invalid range: Range-start index cannot be negative.");if(r!=null&&e!=null)return{byteSize:e-r+1,start:r,end:e};if(r==null&&e!=null)return t==null?{end:e}:e===t?{byteSize:t,start:0,end:t-1}:{byteSize:e,start:t-e,end:t-1};if(r!=null&&e==null){if(t==null)return{start:r};let n=t-1;return{byteSize:t-r,start:r,end:n}}return{byteSize:t,start:0,end:t!=null?t-1:0}}function rS({ttl:r,protocol:e,response:t}){let n;e==="ipfs"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,t.headers.set("cache-control",n)}function nS({byteStart:r,byteEnd:e,byteSize:t}){let n=t??"*";if((e??0)>=(t??1/0))throw new Nr("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(t??1/0))throw new Nr("Invalid range: Range-start index is greater than or equal to the size of the file.");if(r!=null&&e==null)return t==null?`bytes */${n}`:`bytes ${r}-${t-1}/${t}`;if(r==null&&e!=null){if(t==null)return`bytes */${n}`;let o=t-1;return`bytes ${o-e+1}-${o}/${t}`}return r==null&&e==null?`bytes */${n}`:`bytes ${r}-${e}/${n}`}function i6(r,e){e!=null&&r.headers.set("X-Ipfs-Roots",e.map(t=>t.toV1().toString()).join(","))}function IO(r){return typeof r=="string"?r.length:r instanceof ArrayBuffer||r instanceof Uint8Array?r.byteLength:r instanceof Blob?r.size:(r instanceof ReadableStream,null)}function TO(r){let e=r.match(/^bytes=(?<start>\d+)?-(?<end>\d+)?$/);if(e?.groups==null)throw new Nr("Invalid range request");let{start:t,end:n}=e.groups;return{start:t,end:n}}var tu=class{headers;isRangeRequest;_fileSize;_body=null;rangeRequestHeader;log;requestRangeStart;requestRangeEnd;byteStart;byteEnd;byteSize;constructor(e,t){if(this.headers=t,this.log=e.forComponent("helia:verified-fetch:byte-range-context"),this.rangeRequestHeader=eS(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:o}=TO(this.rangeRequestHeader);this.requestRangeStart=n!=null?parseInt(n):null,this.requestRangeEnd=o!=null?parseInt(o):null}catch(n){this.log.error("error parsing range request header: %o",n),this.requestRangeStart=null,this.requestRangeEnd=null}this.setOffsetDetails()}else this.log.trace("no range request detected"),this.isRangeRequest=!1,this.requestRangeStart=null,this.requestRangeEnd=null}setBody(e){this._body=e,this.setFileSize(this._fileSize??IO(e)),this.log.trace("set request body with fileSize %o",this._fileSize)}getBody(){let e=this._body;if(e==null)return this.log.trace("body is null"),e;if(!this.isRangeRequest||!this.isValidRangeRequest)return this.log.trace("returning body unmodified for non-range, or invalid range, request"),e;let t=this.byteStart,n=this.byteEnd,o=this.byteSize;return t!=null||n!=null?(this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",t,n,o),e instanceof ReadableStream?e:this.getSlicedBody(e)):(this.log.error("returning unmodified body for valid range request"),e)}getSlicedBody(e){let t=this.byteStart??0,n=this.byteEnd==null?void 0:this.byteEnd+1;return this.log.trace("returning body with offset %o and length %o",t,n),e.slice(t,n)}setFileSize(e){this._fileSize=e!=null?Number(e):null,this.log.trace("set _fileSize to %o",this._fileSize),this.setOffsetDetails()}getFileSize(){return this._fileSize}isValidByteStart(){return!(this.byteStart!=null&&(this.byteStart<0||this._fileSize!=null&&this.byteStart>=this._fileSize||this.byteEnd!=null&&this.byteStart>this.byteEnd))}isValidByteEnd(){return!(this.byteEnd!=null&&(this.byteEnd<0||this._fileSize!=null&&this.byteEnd>=this._fileSize||this.byteStart!=null&&this.byteEnd<this.byteStart))}get isValidRangeRequest(){if(!this.isRangeRequest)return!1;if(this.requestRangeStart==null&&this.requestRangeEnd==null)return this.log.trace("invalid range request, range request values not provided"),!1;if(!this.isValidByteStart())return this.log.trace("invalid range request, byteStart is less than 0 or greater than fileSize"),!1;if(!this.isValidByteEnd())return this.log.trace("invalid range request, byteEnd is less than 0 or greater than fileSize"),!1;if(this.requestRangeEnd!=null&&this.requestRangeStart!=null){if(this.requestRangeStart>this.requestRangeEnd)return this.log.trace("invalid range request, start is greater than end"),!1;if(this.requestRangeStart<0)return this.log.trace("invalid range request, start is less than 0"),!1;if(this.requestRangeEnd<0)return this.log.trace("invalid range request, end is less than 0"),!1}return this.byteEnd==null&&this.byteStart==null&&this.byteSize==null?(this.log.trace("invalid range request, could not calculate byteStart, byteEnd, or byteSize"),!1):!0}get offset(){return this.byteStart??0}get length(){return this.byteEnd!=null&&this.byteStart!=null&&this.byteStart===this.byteEnd?1:this.byteEnd!=null?this.byteEnd+1:this.byteSize!=null?this.byteSize-1:void 0}setOffsetDetails(){if(this.requestRangeStart==null&&this.requestRangeEnd==null){this.log.trace("requestRangeStart and requestRangeEnd are null");return}try{let{start:e,end:t,byteSize:n}=tS(this.requestRangeStart??void 0,this.requestRangeEnd??void 0,this._fileSize??void 0);this.log.trace("set byteStart to %o, byteEnd to %o, byteSize to %o",e,t,n),this.byteStart=e,this.byteEnd=t,this.byteSize=n}catch(e){this.log.error("error setting offset details: %o",e),this.byteStart=void 0,this.byteEnd=void 0,this.byteSize=void 0}}get contentRangeHeaderValue(){if(!this.isValidRangeRequest)throw this.log.error("cannot get contentRangeHeaderValue for invalid range request"),new Nr("Invalid range request");return nS({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};function oS(r){let e=nr(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(Zc(e))}function iS(r){let e=kO(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function kO(r){return r.replace(/[^\x00-\x7F]/g,"_")}function sS({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:o}){let i=t===!0?"W/":"",s=e==null?"":`.${e}`;return(n!=null||o!=null)&&(s+=`.${n??"0"}-${o??"N"}`),`${i}"${r.toString()}${s}"`}function ru(r){return r.charAt(0)==="1"||r.charAt(0)==="Q"?De(r):$r(K.parse(r))}var CO={[ao]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[co]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Hn]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Kr]:["application/octet-stream","application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car","application/x-tar"],[Ht]:["application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.dag-json","application/vnd.ipld.car","application/x-tar"]};function aS(r,e){let t=CO[r.code];if(e!=null)return RO(e,t)}function RO(r,e){let t=r.split(",").map(n=>{let o=n.trim().split(";");return{mimeType:`${o[0]}`.trim(),weight:PO(o[1])}}).sort((n,o)=>n.weight===o.weight?0:n.weight>o.weight?-1:1).map(n=>n.mimeType);for(let n of t)for(let o of e)if(n.includes(o)||n==="*/*"||n.startsWith("*/")&&o.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&o.split("/")[0]===n.split("/")[0])return o}function PO(r){if(r!=null&&(r=r.trim()),r?.startsWith("q=")!==!0)return 1;let e=parseFloat(r.replace("q=",""));return isNaN(e)?0:e}var A0={raw:"application/vnd.ipld.raw",car:"application/vnd.ipld.car","dag-json":"application/vnd.ipld.dag-json","dag-cbor":"application/vnd.ipld.dag-cbor",json:"application/json",cbor:"application/cbor","ipns-record":"application/vnd.ipfs.ipns-record",tar:"application/x-tar"};function cS(r){if(r!=null)return A0[r]}function s6(r){let e=r.get("accept");return!!(e!=null&&Object.values(A0).includes(e))}function a6(r){let e=r?.format;return!!(e!=null&&Object.keys(A0).includes(e))}function lS({query:r,headers:e}){return s6(e)||a6(r)}function uS({query:r,headers:e,logger:t}){let n=t.forComponent("helia:verified-fetch:get-resolved-accept-header"),o=new Headers(e),i=o.get("accept")??void 0;if(i!=null&&n('incoming accept header "%s"',i),!lS({query:r,headers:o}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",i),i;let s=cS(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=i;return!s6(o)&&a6(r)&&(n("accept header not recognized, but query format provided, setting accept header to %s",s),a=s),n('resolved accept header to "%s"',a),a}async function dS(r,e,t,n){let o=t.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),i=r[Symbol.asyncIterator](),{value:s,done:a}=await i.next();if(a===!0)throw o.error("no content found for path",e),new S0;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new F("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:d,done:u}=await i.next();if(n?.signal?.aborted===!0){l.error(new lt(n.signal.reason??"signal aborted by user")),l.close();return}if(u===!0){d!=null&&(n?.onProgress?.(new F("verified-fetch:request:progress:chunk")),l.enqueue(d)),l.close();return}n?.onProgress?.(new F("verified-fetch:request:progress:chunk")),l.enqueue(d)}}),firstChunk:s}}var I0=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},nu=class extends I0{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}};var T0=class extends I0{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}};var F8e=C("ustar\0","binary"),$8e=C("ustar ","binary"),H8e=C(" \0","binary");var gS=ct(hS(),1);function DO(r){return r[Symbol.asyncIterator]!=null}function LO(r){if(DO(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=be([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return be(e,t)}var pS=LO;var OO="0000000000000000000",BO="7777777777777777777",MO=48,UO=C("ustar\0","binary"),FO=C("00","binary"),$O=parseInt("7777",8),HO=257,VO=263,KO=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},qO=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},ui=function(r,e){let t=r.toString(8);return t.length>e?C(BO.slice(0,e)+" "):C(OO.slice(0,e-t.length)+t+" ")},c6=function(r){let e=C(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function mS(r){let e="";r.name!=null&&(e+=c6(" path="+r.name+`
52
52
  `)),r.linkname!=null&&(e+=c6(" linkpath="+r.linkname+`
53
53
  `));let t=r.pax;if(t!=null)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e+=c6(" "+n+"="+t[n]+`
54
54
  `));return C(e)}function k0(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),C(t).byteLength!==t.length)return null;for(;C(t).byteLength>100;){let o=t.indexOf("/");if(o===-1)return null;n+=n!==""?"/"+t.slice(0,o):t.slice(0,o),t=t.slice(o+1)}return C(t).byteLength>100||C(n).byteLength>155||r.linkname!=null&&C(r.linkname).byteLength>100?null:(e.set(C(t),0),e.set(ui(r.mode&$O,6),100),e.set(ui(r.uid,6),108),e.set(ui(r.gid,6),116),e.set(ui(r.size,11),124),e.set(ui(r.mtime.getTime()/1e3|0,11),136),e[156]=MO+KO(r.type),r.linkname!=null&&e.set(C(r.linkname),157),e.set(UO,HO),e.set(FO,VO),r.uname!=null&&e.set(C(r.uname),265),r.gname!=null&&e.set(C(r.gname),297),e.set(ui(r.devmajor??0,6),329),e.set(ui(r.devminor??0,6),337),n!=null&&e.set(C(n),345),e.set(ui(qO(e),6),148),e)}var{S_IFMT:GO,S_IFBLK:WO,S_IFCHR:YO,S_IFDIR:XO,S_IFIFO:QO,S_IFLNK:jO}=gS.default,ZO=parseInt("755",8),JO=parseInt("644",8),yS=new Uint8Array(1024);function eB(r=0){switch(r&GO){case WO:return"block-device";case YO:return"character-device";case XO:return"directory";case QO:return"fifo";case jO:return"symlink";default:return"file"}}function u6(r){return r&=511,r!==0?yS.subarray(0,512-r):new Uint8Array(0)}function l6(r){if(r.pax==null){let e=k0(r);if(e!=null)return e}return tB(r)}function tB(r){let e=mS(r),t={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:e.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new le(k0(t)??new Uint8Array(0),e,u6(e.length),k0({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function C0(){return async function*(r){for await(let{header:e,body:t}of r){let n={...e,size:e.type==="symlink"?0:e.size??0,type:e.type??eB(e.mode),mode:e.mode??(e.type==="directory"?ZO:JO),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=C(t)),t instanceof Uint8Array||An(t)){n.size=t.length,yield l6(n),yield An(t)?t.subarray():t,yield u6(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(t==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=V(await pS(t)),yield l6(n);continue}if(yield l6(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of t??[])o+=i.length,yield An(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield u6(n.size)}yield yS}}var rB=["file","raw","directory"];function nB(r){let e,t;return(r.type==="file"||r.type==="directory")&&(e=r.unixfs.mode,t=r.unixfs.mtime!=null?new Date(Number(r.unixfs.mtime.secs*1000n)):void 0),{name:r.path,mode:e,mtime:t,size:Number(r.size),type:r.type==="directory"?"directory":"file"}}function wS(r){if(!rB.includes(r.type))throw new nu(`${r.type} is not a UnixFS node`);let e={header:nB(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*bS(r,e,t){let n=await Ya(r,e,t);if(n.type==="file"||n.type==="raw"){yield*Ne([wS(n)],C0());return}if(n.type==="directory"){yield*Ne(Xv(r,e,t),o=>We(o,i=>wS(i)),C0());return}throw new nu("Not a UnixFS node")}var ES=ct(Dm(),1),R0=class{lru;constructor(e){this.lru=(0,ES.default)(e)}get(e){let t=this.lru.get(e);if(t!=null){if(t.expire!=null&&t.expire<Date.now()){this.lru.remove(e);return}return t.value}}set(e,t,n){this.lru.set(e,{value:t,expire:Date.now()+n})}has(e){return this.get(e)!=null}remove(e){this.lru.remove(e)}clear(){this.lru.clear()}};var xS=new R0(1e3),oB=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,iB=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,sB=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,aB=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function cB(r){let e=r?.protocol;if(e==null)return!1;let t=r?.cidOrPeerIdOrDnsLink;if(t==null)return!1;let n=r?.path,o=r?.queryString;return["ipns","ipfs"].includes(e)&&typeof t=="string"&&(n==null||typeof n=="string")&&(o==null||typeof o=="string")}function ou(r){for(let e of[aB,oB,sB,iB]){let t=r.match(e);if(cB(t?.groups))return t.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function lB(r){if(r==null)return;let e=r.answer?.TTL,t=r.record?.ttl,n=t!=null?Number(t/BigInt(1e9)):void 0;return e??n}var uB=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function dB(r){return uB.test(r)&&r.includes("-")&&!r.includes(".")}function fB(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function vS({urlString:r,ipns:e,logger:t},n){let o=t.forComponent("helia:verified-fetch:parse-url-string"),{protocol:i,cidOrPeerIdOrDnsLink:s,path:a,queryString:c}=ou(r),l,d,u=[],f;if(i==="ipfs")try{l=K.parse(s)}catch(m){o.error(m),u.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(f=xS.get(s),f!=null)l=f.cid,d=f.path,o.trace("resolved %s to %c from cache",s,l);else{o.trace("Attempting to resolve PeerId for %s",s);let m;try{if(m=ru(s),m.publicKey==null)throw new TypeError("cidOrPeerIdOrDnsLink contains no public key");f=await e.resolve(m.publicKey,n),l=f?.cid,d=f?.path,o.trace("resolved %s to %c",s,l)}catch(g){n?.signal?.throwIfAborted(),m==null?(o.error('could not parse PeerId string "%s"',s,g),u.push(new TypeError(`Could not parse PeerId in ipns url "${s}", ${g.message}`))):(o.error("could not resolve PeerId %c",m,g),u.push(new TypeError(`Could not resolve PeerId "${s}", ${g.message}`)))}if(l==null){let g=s;dB(s)&&(g=fB(s),o.trace('decoded dnslink from "%s" to "%s"',s,g)),o.trace("Attempting to resolve DNSLink for %s",g);try{f=await e.resolveDNSLink(g,n),l=f?.cid,d=f?.path,o.trace("resolved %s to %c",g,l)}catch(y){n?.signal?.throwIfAborted(),o.error('could not resolve DnsLink for "%s"',s,y),u.push(y)}}}if(l==null)throw u.length===1?u[0]:new AggregateError(u,`Invalid resource. Cannot determine CID from URL "${r}"`);let h=lB(f);f!=null&&(h=h??60*2,o.trace("caching %s resolved to %s with TTL: %s",s,l,h),xS.set(s,f,h*1e3));let p={};if(c!=null&&c.length>0){let m=c.split("&");for(let g of m){let[y,w]=g.split("=");p[y]=decodeURIComponent(w)}p.download!=null&&(p.download=p.download==="true"),p.filename!=null&&(p.filename=p.filename.toString())}return{protocol:i,cid:l,path:hB(d,a??""),query:p,ttl:h,ipfsPath:`/${i}/${s}${a!=null&&a!==""?`/${a}`:""}`}}function hB(r,e){let t="";return r!=null&&(t+=r),e.length>0&&(t=`${t.length>0?`${t}/`:t}${e}`),t=t.replace(/\/(\/)+/g,"/"),t.startsWith("/")&&(t=t.substring(1)),t.split("/").map(decodeURIComponent).join("/")}function d6(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function yo(r,e){d6(r,"type",e)}function wo(r,e){d6(r,"url",e)}function SS(r){d6(r,"redirected",!0)}function ws(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&SS(n),yo(n,"basic"),wo(n,r),n.headers.set("Accept-Ranges","bytes"),n}function N0(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return yo(n,"basic"),wo(n,r),n}function D0(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),yo(n,"basic"),wo(n,r),n}function ja(r,e,t){let n=new Response(e,{...t??{},status:406,statusText:"Not Acceptable"});return yo(n,"basic"),wo(n,r),n}function L0(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return yo(n,"basic"),wo(n,r),n}function O0(r,e,t){e instanceof Error&&(e=e.message);let n=new Response(e,{...t??{},status:400,statusText:"Bad Request"});return yo(n,"basic"),wo(n,r),n}function iu(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return yo(n,"basic"),wo(n,r),n}function f6(r,e,{byteRangeContext:t,log:n},o){if(!t.isRangeRequest)return ws(r,e,o);if(!t.isValidRangeRequest)return P0(r,e,o);let i;try{i=new Response(e,{...o??{},status:206,statusText:"Partial Content",headers:{...o?.headers??{},"content-range":t.contentRangeHeaderValue}})}catch(s){return n?.error("failed to create range response",s),P0(r,e,o)}return o?.redirected===!0&&SS(i),yo(i,"basic"),wo(i,r),i.headers.set("Accept-Ranges","bytes"),i}function P0(r,e,t){let n=new Response(e,{...t??{},status:416,statusText:"Requested Range Not Satisfiable"});return yo(n,"basic"),wo(n,r),n}function _S(r){return r.match(/\.[a-zA-Z0-9]{1,4}$/)!=null||r.endsWith("/")?r:`${r}/`}async function AS({resource:r,options:e,logger:t,cid:n,fetch:o=globalThis.fetch}){let i=t.forComponent("helia:verified-fetch:get-redirect-response");if(typeof r!="string"||e==null||["ipfs://","ipns://"].some(d=>r.startsWith(d)))return null;let s=new Headers(e?.headers),a=s.get("x-forwarded-host"),c=s.get("host");if(s.get("x-forwarded-for")==null&&a==null&&c==null)return i.trace("no redirect info found in headers"),null;i.trace("checking for redirect info");try{let d=ou(r),u=new URL(r),f=a??u.host,h=new URL(u);if(d.protocol==="ipfs"&&n.version===0?h.host=`${n.toV1()}.ipfs.${f}`:h.host=`${d.cidOrPeerIdOrDnsLink}.${d.protocol}.${f}`,c?.includes(d.protocol)===!0&&h.host.includes(c))return i.trace("request was for a subdomain already, not setting location header"),null;if(c!=null&&!h.host.includes(c))return i.trace("host header is not the same as the subdomain url host, not setting location header"),null;if(u.host===h.host)return i.trace("req url is the same as the subdomain url, not setting location header"),null;h.pathname=_S(u.pathname.replace(`/${d.cidOrPeerIdOrDnsLink}`,"").replace(`/${d.protocol}`,"")),i.trace("subdomain url %s",h.href);let p=new URL(u,`${u.protocol}//${f}`);p.pathname=_S(u.pathname),i.trace("path url %s",p.href);try{let m=await o(h,{method:"HEAD"});if(m.ok)return i("subdomain supported, redirecting to subdomain"),iu(r.toString(),h.href);throw i("subdomain not supported, subdomain failed with status %s %s",m.status,m.statusText),new _0("subdomain not supported")}catch(m){return i("subdomain not supported",m),p.href===u.href?(i("path url is the same as the request url, not setting location header"),null):iu(r.toString(),p.href)}}catch(d){i.error("error setting location header for x-forwarded-host",d)}return null}async function IS(r,{ipns:e,logger:t},n){if(typeof r=="string")return vS({urlString:r,ipns:e,logger:t},n);let o=K.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ipfsPath:`/ipfs/${o.toString()}`,ttl:29030400};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function TS(r){let e=K.asCID(r);if(e!=null)return`ipfs://${e}`;try{return`ipfs://${K.parse(r.toString())}`}catch{}let{protocol:t,cidOrPeerIdOrDnsLink:n}=ou(r.toString());return`${t}://${n}`}async function pB(r,e,t){let n=[],o;for await(let i of r6(e,r,t))n.push(i.cid),o=i;if(o==null)throw new T0("No terminal element found");return{ipfsRoots:n,terminalElement:o}}function kS(r){return r.type==="object"}async function h6({cid:r,path:e,resource:t,options:n,blockstore:o,log:i}){try{return await pB(o,`${r.toString()}/${e}`,n)}catch(s){return n?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(s.code)?L0(t):(i.error("error walking path %s",e,s),N0(t,"Error walking path"))}}var mB=100,gB=60*1e3;function yB(r){if(r==null)return;let e;return r?.signal===null?e=void 0:e=r?.signal,{...r,signal:e}}var wB=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function bB({headers:r,accept:e}){let n=(e??new Headers(r).get("accept")??"").split(",").map(o=>o.split(";")[0]).map(o=>o.trim());for(let o of n){if(o==="*/*")return;if(wB.includes(o??""))return o}}var B0=class{helia;ipns;log;contentTypeParser;blockstoreSessions;constructor({helia:e,ipns:t},n){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipns=t??fw(e),this.contentTypeParser=n?.contentTypeParser,this.blockstoreSessions=new v0({max:n?.sessionCacheSize??mB,ttl:n?.sessionTTLms??gB,dispose:o=>{o.close()}}),this.log.trace("created VerifiedFetch instance")}getBlockstore(e,t,n,o){let i=TS(t);if(!n)return this.helia.blockstore;let s=this.blockstoreSessions.get(i);return s==null&&(s=this.helia.blockstore.createSession(e,o),this.blockstoreSessions.set(i,s)),s}async handleIPNSRecord({resource:e,cid:t,path:n,options:o}){if(n!==""||!(e.startsWith("ipns://")||e.includes(".ipns.")))return this.log.error('invalid request for IPNS name "%s" and path "%s"',e,n),O0(e,"Invalid IPNS name");let i;try{if(e.startsWith("ipns://")){let u=e.replace("ipns://","");this.log.trace('trying to parse peer id from "%s"',u),i=ru(u)}else{let u=e.split(".ipns.")[0].split("://")[1];this.log.trace('trying to parse peer id from "%s"',u),i=ru(u)}}catch(u){return this.log.error("could not parse peer id from IPNS url %s",e,u),O0(e,u)}let s=be([C("/ipns/"),i.toMultihash().bytes]),a=new Ie("/dht/record/"+V(s,"base32"),!1),c=await this.helia.datastore.get(a,o),l=Xe.deserialize(c),d=ws(e,l.value);return d.headers.set("content-type","application/vnd.ipfs.ipns-record"),d}async handleCar({resource:e,cid:t,session:n,options:o}){let i=this.getBlockstore(t,e,n,o),s=Ev({blockstore:i,getCodec:this.helia.getCodec}),a=E0(s.stream(t,o)),c=ws(e,a);return c.headers.set("content-type","application/vnd.ipld.car; version=1"),c}async handleTar({resource:e,cid:t,path:n,session:o,options:i}){if(t.code!==Kr&&t.code!==Ht)return ja("only UnixFS data can be returned in a TAR file");let s=this.getBlockstore(t,e,o,i),a=E0(bS(`/ipfs/${t}/${n}`,s,i)),c=ws(e,a);return c.headers.set("content-type","application/x-tar"),c}async handleJson({resource:e,cid:t,path:n,accept:o,session:i,options:s}){this.log.trace("fetching %c/%s",t,n);let c=await this.getBlockstore(t,e,i,s).get(t,s),l;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let u=ra(c);l=ea(u)}catch(u){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",u),ja(e)}else l=c;let d=ws(e,l);return d.headers.set("content-type",o??"application/json"),d}async handleDagCbor({resource:e,cid:t,path:n,accept:o,session:i,options:s}){this.log.trace("fetching %c/%s",t,n);let a,c=this.getBlockstore(t,e,i,s),l=await h6({cid:t,path:n,resource:e,options:s,blockstore:c,log:this.log});if(l instanceof Response)return l;let d=l.ipfsRoots;if(kS(l.terminalElement))a=l.terminalElement;else return this.log.error("terminal element is not a dag-cbor node"),D0(e,"Terminal element is not a dag-cbor node");let u=a.node,f;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")f=u;else if(o==="application/vnd.ipld.dag-json")try{let p=Wo(u);f=kf(p)}catch(p){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",p),ja(e)}else try{f=oS(u)}catch(p){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',p),ja(e);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",p),f=u}let h=ws(e,f);return o==null&&(o=f instanceof Uint8Array?"application/octet-stream":"application/json"),h.headers.set("content-type",o),i6(h,d),h}async handleDagPb({cid:e,path:t,resource:n,session:o,options:i}){let s=!1,a=new tu(this.helia.logger,i?.headers),c=this.getBlockstore(e,n,o,i),l=await h6({cid:e,path:t,resource:n,options:i,blockstore:c,log:this.log});if(l instanceof Response)return l;let d=l.ipfsRoots,u=l.terminalElement,f=u.cid;if(u?.type==="directory"){let m=u.cid;if(t===""?!n.toString().endsWith("/"):!t.endsWith("/")){if(i?.redirect==="error")throw this.log('could not redirect to %s/ as redirect option was set to "error"',n),new TypeError("Failed to fetch");if(i?.redirect==="manual")return this.log("returning 301 permanent redirect to %s/",n),iu(n,`${n}/`);n=`${n}/`,s=!0}let y="index.html";try{this.log.trace("found directory at %c/%s, looking for index.html",e,t);let w=await Ya(`/ipfs/${m}/${y}`,this.helia.blockstore,{signal:i?.signal,onProgress:i?.onProgress});this.log.trace("found root file at %c/%s with cid %c",m,y,w.cid),t=y,f=w.cid}catch(w){return i?.signal?.throwIfAborted(),this.log("error loading path %c/%s",m,y,w),D0("Unable to find index.html for directory at given path. Support for directories with implicit root is not implemented")}finally{i?.onProgress?.(new F("verified-fetch:request:end",{cid:m,path:y}))}}a.isRangeRequest&&a.isValidRangeRequest&&u.type==="file"&&(a.setFileSize(u.unixfs.fileSize()),this.log.trace("fileSize for rangeRequest %d",a.getFileSize()));let h=a.offset,p=a.length;this.log.trace("calling exporter for %c/%s with offset=%o & length=%o",f,t,h,p);try{let g=(await Ya(f,this.helia.blockstore,{signal:i?.signal,onProgress:i?.onProgress})).content({signal:i?.signal,onProgress:i?.onProgress,offset:h,length:p});this.log("got async iterator for %c/%s",e,t);let{stream:y,firstChunk:w}=await dS(g,t??"",this.helia.logger,{onProgress:i?.onProgress,signal:i?.signal});a.setBody(y);let b=f6(n,a.getBody(),{byteRangeContext:a,log:this.log},{redirected:s});return await this.setContentType(w,t,b),i6(b,d),b}catch(m){return i?.signal?.throwIfAborted(),this.log.error("error streaming %c/%s",e,t,m),a.isRangeRequest&&m.code==="ERR_INVALID_PARAMS"?P0(n):N0(n.toString(),"Unable to stream content")}}async handleRaw({resource:e,cid:t,path:n,session:o,options:i,accept:s}){if(n!=="")return this.log.trace("404-ing raw codec request for %c/%s",t,n),L0(e,"Raw codec does not support paths");let a=new tu(this.helia.logger,i?.headers),l=await this.getBlockstore(t,e,o,i).get(t,i);a.setBody(l);let d=f6(e,a.getBody(),{byteRangeContext:a,log:this.log},{redirected:!1});return await this.setContentType(l,n,d,bB({headers:i?.headers,accept:s})),d}async setContentType(e,t,n,o="application/octet-stream"){let i;if(this.contentTypeParser!=null)try{let s=t.split("/").pop()?.trim();s=s===""?void 0:s;let a=this.contentTypeParser(e,s);if(EB(a)){let c=await a;c!=null&&(i=c)}else a!=null&&(i=a)}catch(s){this.log.error("error parsing content type",s)}this.log.trace('setting content type to "%s"',i??o),n.headers.set("content-type",i??o)}codecHandlers={[Kr]:this.handleDagPb,[co]:this.handleJson,[Hn]:this.handleJson,[ao]:this.handleDagCbor,[Ht]:this.handleRaw,[vt.code]:this.handleRaw};async fetch(e,t){this.log("fetch %s",e);let n=yB(t);n?.onProgress?.(new F("verified-fetch:request:start",{resource:e}));let o,i,s,a,c,l;try{let y=await IS(e,{ipns:this.ipns,logger:this.helia.logger},n);o=y.cid,i=y.path,s=y.query,a=y.ttl,c=y.protocol,l=y.ipfsPath}catch(y){return n?.signal?.throwIfAborted(),this.log.error("error parsing resource %s",e,y),O0(e.toString(),y)}n?.onProgress?.(new F("verified-fetch:request:resolve",{cid:o,path:i}));let d=uS({query:s,headers:n?.headers,logger:this.helia.logger}),u=aS(o,d);if(this.log("output type %s",u),d!=null&&u==null)return ja(e.toString());let f,h,p=await AS({resource:e,options:n,logger:this.helia.logger,cid:o});if(p!=null)return p;let m={resource:e.toString(),cid:o,path:i,accept:u,session:n?.session??!0,options:n};if(u==="application/vnd.ipfs.ipns-record")h="ipns-record",f=await this.handleIPNSRecord(m);else if(u==="application/vnd.ipld.car")h="car",s.download=!0,s.filename=s.filename??`${o.toString()}.car`,f=await this.handleCar(m);else if(u==="application/vnd.ipld.raw")h="raw",s.download=!0,s.filename=s.filename??`${o.toString()}.bin`,f=await this.handleRaw(m);else if(u==="application/x-tar")h="tar",s.download=!0,s.filename=s.filename??`${o.toString()}.tar`,f=await this.handleTar(m);else{this.log.trace('finding handler for cid code "%s" and output type "%s"',o.code,u);let y=this.codecHandlers[o.code];if(y==null)return D0(`Support for codec with code ${o.code} is not yet implemented. Please open an issue at https://github.com/ipfs/helia-verified-fetch/issues/new`);this.log.trace('calling handler "%s"',y.name),f=await y.call(this,m)}f.headers.set("etag",sS({cid:o,reqFormat:h,weak:!1})),rS({response:f,ttl:a,protocol:c}),f.headers.set("X-Ipfs-Path",l);let g;return s.download===!0&&(g="attachment"),s.filename!=null&&(g==null&&(g="inline"),g=`${g}; ${iS(s.filename)}`),g!=null&&f.headers.set("Content-Disposition",g),n?.onProgress?.(new F("verified-fetch:request:end",{cid:o,path:i})),f}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function EB(r){return r?.then!=null}var su,M0=async function(e,t){return su==null&&(su=await p6()),su(e,t)};M0.start=async function(){await su?.start()};M0.stop=async function(){await su?.stop()};async function p6(r,e){let t;if(!xB(r)){let i=vB(r?.dnsResolvers),s=ov();s.dns=i;let a=r?.routers??["https://delegated-ipfs.dev"];for(let d=0;d<a.length;d++){let u=a[d];s.services[`delegatedRouting${d}`]=()=>ph(u)}r?.libp2pConfig!=null&&Object.assign(s,r.libp2pConfig),t=await a0(s);let c=[tl()],l=[vl(t)];(r?.gateways==null||r.gateways.length>0)&&(c.push(ul({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})),l.push(xl({gateways:r?.gateways??["https://trustless-gateway.link"]}))),r=await nv({libp2p:t,blockBrokers:c,dns:i,routers:l})}let n=new B0({helia:r},e);async function o(i,s){return n.fetch(i,s)}return o.start=n.start.bind(n),o.stop=n.stop.bind(n),o}function xB(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function vB(r){if(r!=null)return Array.isArray(r)?Oi({resolvers:{".":r}}):Oi({resolvers:r})}return VS(SB);})();
@@ -1 +1 @@
1
- {"version":3,"file":"libp2p-defaults.browser.d.ts","sourceRoot":"","sources":["../../../src/utils/libp2p-defaults.browser.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAA;AAI3C,wBAAgB,eAAe,IAAK,aAAa,GAAG,QAAQ,CAAC,IAAI,CAAC,aAAa,EAAE,UAAU,CAAC,CAAC,CAmB5F"}
1
+ {"version":3,"file":"libp2p-defaults.browser.d.ts","sourceRoot":"","sources":["../../../src/utils/libp2p-defaults.browser.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAA;AAI3C,wBAAgB,eAAe,IAAK,aAAa,GAAG,QAAQ,CAAC,IAAI,CAAC,aAAa,EAAE,UAAU,CAAC,CAAC,CAoB5F"}
@@ -6,6 +6,7 @@ export function getLibp2pConfig() {
6
6
  libp2pDefaultOptions.start = false;
7
7
  libp2pDefaultOptions.addresses = { listen: [] };
8
8
  libp2pDefaultOptions.transports = [webRTCDirect(), webSockets()];
9
+ libp2pDefaultOptions.peerDiscovery = []; // Avoid connecting to bootstrap nodes
9
10
  const services = {
10
11
  dcutr: libp2pDefaultOptions.services.dcutr,
11
12
  identify: libp2pDefaultOptions.services.identify,
@@ -1 +1 @@
1
- {"version":3,"file":"libp2p-defaults.browser.js","sourceRoot":"","sources":["../../../src/utils/libp2p-defaults.browser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAA;AAC/C,OAAO,EAAE,cAAc,EAA8B,MAAM,OAAO,CAAA;AAMlE,MAAM,UAAU,eAAe;IAC7B,MAAM,oBAAoB,GAAG,cAAc,EAAE,CAAA;IAE7C,oBAAoB,CAAC,KAAK,GAAG,KAAK,CAAA;IAClC,oBAAoB,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,CAAA;IAC/C,oBAAoB,CAAC,UAAU,GAAG,CAAC,YAAY,EAAE,EAAE,UAAU,EAAE,CAAC,CAAA;IAEhE,MAAM,QAAQ,GAAkC;QAC9C,KAAK,EAAE,oBAAoB,CAAC,QAAQ,CAAC,KAAK;QAC1C,QAAQ,EAAE,oBAAoB,CAAC,QAAQ,CAAC,QAAQ;QAChD,QAAQ,EAAE,oBAAoB,CAAC,QAAQ,CAAC,QAAQ;QAChD,IAAI,EAAE,oBAAoB,CAAC,QAAQ,CAAC,IAAI;KACzC,CAAA;IAED,OAAO;QACL,GAAG,oBAAoB;QACvB,KAAK,EAAE,KAAK;QACZ,QAAQ;KACT,CAAA;AACH,CAAC"}
1
+ {"version":3,"file":"libp2p-defaults.browser.js","sourceRoot":"","sources":["../../../src/utils/libp2p-defaults.browser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAA;AAC/C,OAAO,EAAE,cAAc,EAA8B,MAAM,OAAO,CAAA;AAMlE,MAAM,UAAU,eAAe;IAC7B,MAAM,oBAAoB,GAAG,cAAc,EAAE,CAAA;IAE7C,oBAAoB,CAAC,KAAK,GAAG,KAAK,CAAA;IAClC,oBAAoB,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,CAAA;IAC/C,oBAAoB,CAAC,UAAU,GAAG,CAAC,YAAY,EAAE,EAAE,UAAU,EAAE,CAAC,CAAA;IAChE,oBAAoB,CAAC,aAAa,GAAG,EAAE,CAAA,CAAC,sCAAsC;IAE9E,MAAM,QAAQ,GAAkC;QAC9C,KAAK,EAAE,oBAAoB,CAAC,QAAQ,CAAC,KAAK;QAC1C,QAAQ,EAAE,oBAAoB,CAAC,QAAQ,CAAC,QAAQ;QAChD,QAAQ,EAAE,oBAAoB,CAAC,QAAQ,CAAC,QAAQ;QAChD,IAAI,EAAE,oBAAoB,CAAC,QAAQ,CAAC,IAAI;KACzC,CAAA;IAED,OAAO;QACL,GAAG,oBAAoB;QACvB,KAAK,EAAE,KAAK;QACZ,QAAQ;KACT,CAAA;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@helia/verified-fetch",
3
- "version": "2.2.0",
3
+ "version": "2.2.1",
4
4
  "description": "A fetch-like API for obtaining verified & trustless IPFS content on the web",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/ipfs/helia-verified-fetch/tree/main/packages/verified-fetch#readme",
@@ -12,6 +12,7 @@ export function getLibp2pConfig (): Libp2pOptions & Required<Pick<Libp2pOptions,
12
12
  libp2pDefaultOptions.start = false
13
13
  libp2pDefaultOptions.addresses = { listen: [] }
14
14
  libp2pDefaultOptions.transports = [webRTCDirect(), webSockets()]
15
+ libp2pDefaultOptions.peerDiscovery = [] // Avoid connecting to bootstrap nodes
15
16
 
16
17
  const services: ServiceFactoryMap<ServiceMap> = {
17
18
  dcutr: libp2pDefaultOptions.services.dcutr,