@helia/verified-fetch 2.6.19 → 3.0.0
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/README.md +5 -3
- package/dist/index.min.js +4 -4
- package/dist/index.min.js.map +3 -3
- package/dist/src/index.d.ts +5 -3
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +5 -3
- package/dist/src/index.js.map +1 -1
- package/dist/src/plugins/plugin-base.d.ts +8 -5
- package/dist/src/plugins/plugin-base.d.ts.map +1 -1
- package/dist/src/plugins/plugin-base.js +10 -11
- package/dist/src/plugins/plugin-base.js.map +1 -1
- package/dist/src/plugins/plugin-handle-byte-range-context.d.ts +1 -0
- package/dist/src/plugins/plugin-handle-byte-range-context.d.ts.map +1 -1
- package/dist/src/plugins/plugin-handle-byte-range-context.js +1 -0
- package/dist/src/plugins/plugin-handle-byte-range-context.js.map +1 -1
- package/dist/src/plugins/plugin-handle-car.d.ts +1 -0
- package/dist/src/plugins/plugin-handle-car.d.ts.map +1 -1
- package/dist/src/plugins/plugin-handle-car.js +1 -0
- package/dist/src/plugins/plugin-handle-car.js.map +1 -1
- package/dist/src/plugins/plugin-handle-dag-cbor.d.ts +1 -0
- package/dist/src/plugins/plugin-handle-dag-cbor.d.ts.map +1 -1
- package/dist/src/plugins/plugin-handle-dag-cbor.js +1 -0
- package/dist/src/plugins/plugin-handle-dag-cbor.js.map +1 -1
- package/dist/src/plugins/plugin-handle-dag-pb.d.ts +1 -0
- package/dist/src/plugins/plugin-handle-dag-pb.d.ts.map +1 -1
- package/dist/src/plugins/plugin-handle-dag-pb.js +1 -0
- package/dist/src/plugins/plugin-handle-dag-pb.js.map +1 -1
- package/dist/src/plugins/plugin-handle-dag-walk.d.ts +1 -0
- package/dist/src/plugins/plugin-handle-dag-walk.d.ts.map +1 -1
- package/dist/src/plugins/plugin-handle-dag-walk.js +1 -0
- package/dist/src/plugins/plugin-handle-dag-walk.js.map +1 -1
- package/dist/src/plugins/plugin-handle-dir-index-html.d.ts +1 -0
- package/dist/src/plugins/plugin-handle-dir-index-html.d.ts.map +1 -1
- package/dist/src/plugins/plugin-handle-dir-index-html.js +1 -0
- package/dist/src/plugins/plugin-handle-dir-index-html.js.map +1 -1
- package/dist/src/plugins/plugin-handle-ipns-record.d.ts +1 -0
- package/dist/src/plugins/plugin-handle-ipns-record.d.ts.map +1 -1
- package/dist/src/plugins/plugin-handle-ipns-record.js +1 -0
- package/dist/src/plugins/plugin-handle-ipns-record.js.map +1 -1
- package/dist/src/plugins/plugin-handle-json.d.ts +1 -0
- package/dist/src/plugins/plugin-handle-json.d.ts.map +1 -1
- package/dist/src/plugins/plugin-handle-json.js +1 -0
- package/dist/src/plugins/plugin-handle-json.js.map +1 -1
- package/dist/src/plugins/plugin-handle-raw.d.ts +1 -0
- package/dist/src/plugins/plugin-handle-raw.d.ts.map +1 -1
- package/dist/src/plugins/plugin-handle-raw.js +1 -0
- package/dist/src/plugins/plugin-handle-raw.js.map +1 -1
- package/dist/src/plugins/plugin-handle-tar.d.ts +1 -0
- package/dist/src/plugins/plugin-handle-tar.d.ts.map +1 -1
- package/dist/src/plugins/plugin-handle-tar.js +1 -0
- package/dist/src/plugins/plugin-handle-tar.js.map +1 -1
- package/dist/src/plugins/types.d.ts +1 -0
- package/dist/src/plugins/types.d.ts.map +1 -1
- package/dist/src/verified-fetch.js +9 -9
- package/dist/src/verified-fetch.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +5 -3
- package/src/plugins/plugin-base.ts +16 -12
- package/src/plugins/plugin-handle-byte-range-context.ts +2 -0
- package/src/plugins/plugin-handle-car.ts +2 -0
- package/src/plugins/plugin-handle-dag-cbor.ts +1 -0
- package/src/plugins/plugin-handle-dag-pb.ts +1 -0
- package/src/plugins/plugin-handle-dag-walk.ts +1 -0
- package/src/plugins/plugin-handle-dir-index-html.ts +1 -0
- package/src/plugins/plugin-handle-ipns-record.ts +1 -0
- package/src/plugins/plugin-handle-json.ts +1 -0
- package/src/plugins/plugin-handle-raw.ts +1 -0
- package/src/plugins/plugin-handle-tar.ts +1 -0
- package/src/plugins/types.ts +1 -0
- package/src/verified-fetch.ts +9 -9
package/dist/index.min.js
CHANGED
|
@@ -79,11 +79,11 @@ a=end-of-candidates
|
|
|
79
79
|
`;return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
|
80
80
|
a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
81
81
|
a=ice-pwd:`+e+t),r}var oE=R("libp2p-webrtc-noise:");function IB(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),i=R(n,"hex"),o=Qr($e.code,i),s=rE.decode(nE(e)),a=oE.byteLength+o.bytes.byteLength+s.byteLength;return t==="server"?Ve([oE,s,o.bytes],a):Ve([oE,o.bytes,s],a)}var UY=I1?"iceconnectionstatechange":"connectionstatechange";async function TB(r,e,t){let n=r.createDataChannel("",{negotiated:!0,id:0});try{if(t.role==="client"){t.log.trace("client creating local offer");let f=await r.createOffer();t.log.trace("client created local offer %s",f.sdp);let h=iE(f,e);t.log.trace("client setting local offer %s",h.sdp),await r.setLocalDescription(h);let d=SB(t.remoteAddr,e);t.log.trace("client setting server description %s",d.sdp),await r.setRemoteDescription(d)}else{let f=AB(t.remoteAddr,e);t.log.trace("server setting client %s %s",f.type,f.sdp),await r.setRemoteDescription(f),t.log.trace("server creating local answer");let h=await r.createAnswer();t.log.trace("server created local answer");let d=iE(h,e);t.log.trace("server setting local description %s",h.sdp),await r.setLocalDescription(d)}if(n.readyState!=="open"&&(t.log.trace("%s wait for handshake channel to open, starting status %s",t.role,n.readyState),await Er(n,"open",t.signal)),t.log.trace("%s handshake channel opened",t.role),t.role==="server"){let f=r.remoteFingerprint()?.value??"";t.remoteAddr=t.remoteAddr.encapsulate(EB(f))}let i=vB(r.localDescription?.sdp);if(i==null)throw new Za("Could not get fingerprint from local description sdp");t.log.trace("%s performing noise handshake",t.role);let o=IB(i,t.remoteAddr,t.role),s=s3({prologueBytes:o})(t),a=xd({channel:n,direction:"outbound",handshake:!0,logger:t.logger,...t.dataChannel??{}}),c=new Yl(t,{peerConnection:r,remoteAddr:t.remoteAddr,timeline:{open:Date.now()},metrics:t.events});r.addEventListener(UY,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":c.close().catch(f=>{t.log.error("error closing connection",f),c.abort(f)});break;default:break}}),t.events?.increment({peer_connection:!0});let l=new Qa(t,{peerConnection:r,metrics:t.events,dataChannelOptions:t.dataChannel});if(t.role==="client")return t.log.trace("%s secure inbound",t.role),await s.secureInbound(a,{remotePeer:t.remotePeerId,signal:t.signal,skipStreamMuxerNegotiation:!0}),t.log.trace("%s upgrade outbound",t.role),await t.upgrader.upgradeOutbound(c,{skipProtection:!0,skipEncryption:!0,muxerFactory:l,signal:t.signal});t.log.trace("%s secure outbound",t.role);let u=await s.secureOutbound(a,{remotePeer:t.remotePeerId,signal:t.signal,skipStreamMuxerNegotiation:!0});c.remoteAddr=c.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),t.log.trace("%s upgrade inbound",t.role),await t.upgrader.upgradeInbound(c,{skipProtection:!0,skipEncryption:!0,muxerFactory:l,signal:t.signal})}catch(i){throw n.close(),i}}async function CB(r,e,t,n){n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let i=typeof t=="function"?await t():t;return new RTCPeerConnection({...i??{},certificates:[n]})}async function kB(r){let e=await t2(r),t=await crypto.subtle.exportKey("pkcs8",e.privateKey);return["-----BEGIN PRIVATE KEY-----",...q(new Uint8Array(t),"base64pad").split(/(.{64})/).filter(Boolean),"-----END PRIVATE KEY-----"].join(`
|
|
82
|
-
`)}var L6=class{log;metrics;components;init;certificate;privateKey;emitter;renewCertificateTask;constructor(e,t={}){if(this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,this.emitter=new Ue,t.certificateLifespan!=null&&t.certificateRenewalThreshold!=null&&t.certificateRenewalThreshold>=t.certificateLifespan)throw new z("Certificate renewal threshold must be less than certificate lifespan");e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[ca]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[tt]=["@libp2p/transport"];async start(){this.certificate=await this.getCertificate()}async stop(){this.renewCertificateTask!=null&&clearTimeout(this.renewCertificateTask),this.certificate=void 0}async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,i=e.getPeerId();i!=null&&(n=ot(i));let o=FD(),s=await CB("client",o,typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{});try{return await TB(s,o,{role:"client",log:this.log,logger:this.components.logger,metrics:this.components.metrics,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeerId:n,privateKey:this.components.privateKey})}catch(a){throw s.close(),a}}createListener(e){if(this.certificate==null)throw new Jn;return new B6(this.components,{...this.init,...e,certificate:this.certificate,emitter:this.emitter})}listenFilter(e){return e.filter(kp.exactMatch)}dialFilter(e){return this.listenFilter(e)}async getCertificate(e){if(FY(this.init.certificate))return this.log("using provided TLS certificate"),this.init.certificate;let t=await this.loadOrCreatePrivateKey(),{pem:n,certhash:i}=await this.loadOrCreateCertificate(t,e);return{privateKey:await kB(t),pem:n,certhash:i}}async loadOrCreatePrivateKey(){if(this.privateKey!=null)return this.privateKey;let e=this.init.certificateKeychainName??PD,t=this.getKeychain();try{if(t==null)throw this.log("no keychain configured - not checking for stored private key"),new Qe;this.log.trace("checking for stored private key"),this.privateKey=await t.exportKey(e)}catch(n){if(n.name!=="NotFoundError")throw n;this.log.trace("generating private key"),this.privateKey=await yf("ECDSA","P-256"),t!=null?(this.log.trace("storing private key"),await t.importKey(e,this.privateKey)):this.log("no keychain configured - not storing private key")}return this.privateKey}async loadOrCreateCertificate(e,t){if(this.certificate!=null&&t!==!0)return this.certificate;let n,i=new nt(this.init.certificateDatastoreKey??kD),o=await t2(e);try{if(t===!0)throw this.log.trace("forcing renewal of TLS certificate"),new Qe;this.log.trace("checking for stored TLS certificate"),n=await this.loadCertificate(i,o)}catch(a){if(a.name!=="NotFoundError")throw a;this.log.trace("generating new TLS certificate"),n=await this.createCertificate(i,o)}let s=n.notAfter.getTime()-(this.init.certificateRenewalThreshold??fb)-Date.now();return s<0&&(s=100),this.log("will renew TLS certificate after %d ms",s),this.renewCertificateTask=setTimeout(()=>{this.log("renewing TLS certificate"),this.getCertificate(!0).then(a=>{this.certificate=a,this.emitter.safeDispatchEvent("certificate:renew",{detail:a})}).catch(a=>{this.log.error("could not renew certificate - %e",a)})},s),{pem:n.toString("pem"),certhash:Oc.encode((await $e.digest(new Uint8Array(n.rawData))).bytes)}}async loadCertificate(e,t){let n=await this.components.datastore.get(e),i=new th(n),o=i.notAfter.getTime()-(this.init.certificateRenewalThreshold??fb);if(Date.now()>o)throw this.log("stored TLS certificate has expired"),new Qe;this.log("loaded certificate, expires in %d ms",o);let s=await i.publicKey.export(crypto),a=await crypto.subtle.exportKey("raw",s),c=await crypto.subtle.exportKey("raw",t.publicKey);if(!pe(new Uint8Array(a,0,a.byteLength),new Uint8Array(c,0,c.byteLength)))throw this.log("stored TLS certificate public key did not match public key from private key"),new Qe;return this.log("loaded certificate, expiry time is %o",o),i}async createCertificate(e,t){let n=new Date,i=new Date(Date.now()+(this.init.certificateLifespan??RD));n.setMilliseconds(0),i.setMilliseconds(0);let o=await O6.createSelfSigned({serialNumber:(BigInt(Math.random().toString().replace(".",""))*100000n).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:n,notAfter:i,keys:t,extensions:[new Zd(!1,void 0,!0)]},crypto);return this.getKeychain()!=null?(this.log.trace("storing TLS certificate"),await this.components.datastore.put(e,R(o.toString("pem")))):this.log("no keychain is configured so not storing TLS certificate since the private key will not be reused"),o}getKeychain(){try{return this.components.keychain}catch{}}};function FY(r){return r==null?!1:typeof r.privateKey=="string"&&typeof r.pem=="string"&&typeof r.certhash=="string"}function M6(r){return e=>new L6(e,r)}function PB(r){return e=>new R4(e,r)}var RB=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",o)}function i(){n(),e()}function o(s){n(),t(s.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",o)})};var DB=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await RB(r)}catch(o){if(o.message==="socket closed")break;throw o}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(i)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((i,o)=>{r.addEventListener("close",s=>{if(s.wasClean||s.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:s});o(a)}}),setTimeout(()=>{r.close()})})});var LB=ht(OB(),1);function BB(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var MB=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((o,s)=>{if(n){o();return}if(i!=null){s(i);return}let a=u=>{r.removeEventListener("open",c),r.removeEventListener("error",l),u()},c=()=>{a(o)},l=u=>{a(()=>{s(u.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let o=new LB.EventIterator(({push:s,stop:a,fail:c})=>{let l=f=>{let h=null;typeof f.data=="string"&&(h=R(f.data)),BB(f.data)&&(h=new Uint8Array(f.data)),f.data instanceof Uint8Array&&(h=f.data),h!=null&&s(h)},u=f=>{c(f.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",u),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",u),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let s of o)yield BB(s)?new Uint8Array(s):s}(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",o=>{n||(i=o.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var UB=(r,e)=>{e=e??{};let t=MB(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let s=new URL(r.url);n=s.hostname,i=parseInt(s.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:DB(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(s=>{r.addEventListener("close",()=>{s()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var FB=WebSocket;var HY={"http:":"ws:","https:":"wss:"},$B="ws:",HB=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??$B}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??$B,i=e.host,o=e.port!=null&&i?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${i}${o}${r}`}let t=new URL(r);for(let[n,i]of Object.entries(HY))t.protocol===n&&(t.protocol=i);return t};function VB(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=HB(r,t),i=new FB(n.toString(),e.websocket);return UB(i,e)}function zB(r){return r.filter(e=>wl.exactMatch(e)||Cs.exactMatch(e))}function KB(){throw new Error("WebSocket Servers can not be created in the browser!")}function qB(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),i=t.metrics,o=t.metricPrefix??"",s={log:n,async sink(a){try{await r.sink(async function*(){for await(let c of a)c instanceof Uint8Array?yield c:yield c.subarray()}())}catch(c){c.type!=="aborted"&&n.error(c)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(a={}){let c=Date.now();if(a.signal==null){let u=AbortSignal.timeout(500);a={...a,signal:u}}let l=()=>{let{host:u,port:f}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",u,f,Date.now()-c),this.abort(new ft("Socket close timeout"))};a.signal?.addEventListener("abort",l);try{await r.close()}catch(u){n.error("error closing WebSocket gracefully",u),this.abort(u)}finally{a.signal?.removeEventListener("abort",l),s.timeline.close=Date.now()}},abort(a){let{host:c,port:l}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",c,l,a),r.destroy(),s.timeline.close=Date.now(),i?.increment({[`${o}error`]:!0})}};return r.socket.addEventListener("close",()=>{i?.increment({[`${o}close`]:!0}),s.timeline.close==null&&(s.timeline.close=Date.now())},{once:!0}),s}var cE=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[ca]=!0;[Symbol.toStringTag]="@libp2p/websockets";[tt]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=qB(n,e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",i.remoteAddr);let o=await t.upgrader.upgradeOutbound(i,t);return this.log("outbound connection %s upgraded",i.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let i=Ee(),o=VB(Lf(e),this.init);o.socket.addEventListener("error",()=>{let s=new Ku(`Could not connect to ${e.toString()}`);this.log.error("connection error:",s),this.metrics?.dialerEvents.increment({error:!0}),i.reject(s)});try{t.onProgress?.(new X("websockets:open-connection")),await Kt(Promise.race([o.connected(),i.promise]),t.signal)}catch(s){throw t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),o.close().catch(a=>{this.log.error("error closing raw socket",a)}),s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return KB({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):zB(e)}dialFilter(e){return this.listenFilter(e)}};function $6(r={}){return e=>new cE(e,r)}var lE=ht(hg(),1);function H6(r,e){let t=e.map((n,i)=>({record:Nn(n),index:i}));return t.sort((n,i)=>{let o=n.record.sequence,s=i.record.sequence;if(o>s)return-1;if(o<s)return 1;if(n.record.validityType===Nr.ValidityType.EOL&&i.record.validityType===Nr.ValidityType.EOL){let a=lE.default.fromString(n.record.validity).toDate(),c=lE.default.fromString(i.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var jB="5.4.2",WB="helia";var GB={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function km(r={}){let e=`${WB}/${jB} ${Xy()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[qx(),PB(),M6(),$6()],connectionEncrypters:[s3()],streamMuxers:[zP(),mD()],peerDiscovery:[oR(GB)],services:{autoNAT:GP(),dcutr:xR(),delegatedRouting:()=>Ig("https://delegated-ipfs.dev",x9()),dht:cD({clientMode:!0,validators:{ipns:Oa},selectors:{ipns:H6}}),identify:IR(),identifyPush:TR(),keychain:Jg(r.keychain),ping:xD()}}}async function XB(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await $9(r.datastore,r.keychain));let t=km(e);return t.datastore=t.datastore??r.datastore,await Qy({...t,...e,start:!1})}async function YB(r={}){let e=r.datastore??new bl,t=r.blockstore??new Up,n;return zY(r.libp2p)?n=r.libp2p:n=await XB({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Rp(),Sp()],routers:r.routers??[Mp(n),Lp()],metrics:n.metrics,start:r.start??!0}}function zY(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}async function QB(r={}){let e=await YB(r),t=new Cg(e);return r.start!==!1&&await t.start(),t}function ZB(){let r=km();r.start=!1,r.addresses={listen:[]},r.transports=[M6(),$6()],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 V6=class extends Error{static name="DNSLinkNotFoundError";constructor(e="DNSLink not found"){super(e),this.name="DNSLinkNotFoundError"}},z6=class extends Error{static name="RecordsFailedValidationError";constructor(e="Records failed validation"){super(e),this.name="RecordsFailedValidationError"}},K6=class extends Error{static name="UnsupportedMultibasePrefixError";constructor(e="Unsupported multibase prefix"){super(e),this.name="UnsupportedMultibasePrefixError"}},q6=class extends Error{static name="UnsupportedMultihashCodecError";constructor(e="Unsupported multihash codec"){super(e),this.name="UnsupportedMultihashCodecError"}},j6=class extends Error{static name="InvalidValueError";constructor(e="Invalid value"){super(e),this.name="InvalidValueError"}};var KY=32;async function JB(r,e,t,n,i={}){if(e===0)throw new Error("recursion limit exceeded");n("query %s for TXT and CNAME records",r);let s=((await t.query(r,{...i,types:[rn.TXT]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d TXT records for %s",s.length,r);for(let l of s)try{let u=l.data;if(u.startsWith('"')&&u.endsWith('"')&&(u=u.substring(1,u.length-1)),!u.startsWith("dnslink="))continue;n("%s TXT %s",l.name,u),u=u.replace("dnslink=","");let[,f,h,...d]=u.split("/");if(f==="ipfs")try{return{value:`/ipfs/${W.parse(h)}${d.length>0?`/${d.join("/")}`:""}`,answer:l}}catch{}else if(f==="ipns"){try{let m;return h.charAt(0)==="1"||h.charAt(0)==="Q"?m=ot(h):m=wn(W.parse(h)),{value:`/ipns/${m}${d.length>0?`/${d.join("/")}`:""}`,answer:l}}catch{}return await W6(h,e-1,t,n,i)}else{if(f==="dnslink")return await W6(h,e-1,t,n,i);n('unknown protocol "%s" in DNSLink record for domain: %s',f,r);continue}}catch(u){n.error("could not parse DNS link record for domain %s, %s",r,l.data,u)}n("no DNSLink records found for %s, falling back to CNAME",r);let c=((await t.query(r,{...i,types:[rn.CNAME]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d CNAME records for %s",c.length,r);for(let l of c)try{return await W6(l.data,e-1,t,n,i)}catch(u){n.error("domain %s cname %s had no DNSLink records",r,l.data,u)}throw new V6(`No DNSLink records found for domain: ${r}`)}async function W6(r,e,t,n,i={}){if(e===0)throw new Error("recursion limit exceeded");r.startsWith("_dnslink.")||(r=`_dnslink.${r}`);try{return await JB(r,e,t,n,i)}catch(o){if(o.code!=="ENOTFOUND"&&o.code!=="ENODATA"&&o.name!=="DNSLinkNotFoundError"&&o.name!=="NotFoundError")throw o;return r.startsWith("_dnslink.")?r=r.replace("_dnslink.",""):r=`_dnslink.${r}`,JB(r,e,t,n,i)}}async function eL(r,e,t,n={}){return W6(r,n.maxRecursiveDepth??KY,e,t,n)}var uE=class{routing;constructor(e){this.routing=e}async put(e,t,n={}){try{await this.routing.put(e,t,n)}catch(i){throw n.onProgress?.(new X("ipns:routing:helia:error",i)),i}}async get(e,t={}){try{return await this.routing.get(e,t)}catch(n){throw t.onProgress?.(new X("ipns:routing:helia:error",n)),n}}};function tL(r){return new uE(r)}function G6(r){return new nt("/dht/record/"+q(r,"base32"),!1)}function rL(r){return{async put(e,t,n={}){try{let i=G6(e);try{let s=await r.get(i),a=Ot.deserialize(s);if(pe(a.value,t))return}catch(s){if(s.name!=="NotFoundError")throw s}let o=new Ot(e,t,new Date);n.onProgress?.(new X("ipns:routing:datastore:put")),await r.put(i,o.serialize(),n)}catch(i){throw n.onProgress?.(new X("ipns:routing:datastore:error",i)),i}},async get(e,t={}){try{let n=G6(e);t.onProgress?.(new X("ipns:routing:datastore:get"));let i=await r.get(n,t),o=Ot.deserialize(i);return{record:o.value,created:o.timeReceived}}catch(n){throw t.onProgress?.(new X("ipns:routing:datastore:error",n)),n}},async has(e,t={}){let n=G6(e);return r.has(n,t)},async delete(e,t){let n=G6(e);return r.delete(n,t)}}}var fE="/ipns/";function dE(r,e){return r.code===e}var Js=ze("helia:ipns"),oL=60*1e3,sL=60*oL,WY=48*sL,hE=23*sL,nL=BigInt(oL)*5000000n,iL={[hn.prefix]:hn,[Le.prefix]:Le},pE=class{routers;localStore;timeout;dns;log;constructor(e,t=[]){this.routers=[tL(e.routing),...t],this.localStore=rL(e.datastore),this.dns=e.dns,this.log=e.logger.forComponent("helia:ipns")}async publish(e,t,n={}){try{let i=1n,o=ks(e.publicKey.toMultihash());if(await this.localStore.has(o,n)){let{record:l}=await this.localStore.get(o,n);i=Nn(l).sequence+1n}let s=n.ttl!=null?BigInt(n.ttl)*1000000n:nL,a=await eC(e,t,i,n.lifetime??WY,{...n,ttlNs:s}),c=Na(a);return await this.localStore.put(o,c,n),n.offline!==!0&&await Promise.all(this.routers.map(async l=>{await l.put(o,c,n)})),a}catch(i){throw n.onProgress?.(new X("ipns:publish:error",i)),i}}async resolve(e,t={}){let n=rS(e)?e.toMultihash():e,i=ks(n),o=await this.#t(i,t);return{...await this.#e(o.value,t),record:o}}async resolveDNSLink(e,t={}){let n=await eL(e,this.dns,this.log,t);return{...await this.#e(n.value,t),answer:n.answer}}republish(e={}){if(this.timeout!=null)throw new Error("Republish is already running");e.signal?.addEventListener("abort",()=>{clearTimeout(this.timeout)});async function t(){let n=Date.now();e.onProgress?.(new X("ipns:republish:start"));let o=Date.now()-n,s=hE-o;s<0&&(s=e.interval??hE),setTimeout(()=>{t().catch(a=>{Js.error("error republishing",a)})},s)}this.timeout=setTimeout(()=>{t().catch(n=>{Js.error("error republishing",n)})},e.interval??hE)}async#e(e,t={}){let n=e.split("/");try{let i=n[1];if(i==="ipns"){let o=n[2],s=o.substring(0,1),a;if(s==="1"||s==="Q")a=Le.decode(`z${o}`);else if(iL[s]!=null)a=iL[s].decode(o);else throw new K6(`Unsupported multibase prefix "${s}"`);let c;try{c=Fe(a)}catch{c=W.decode(a).multihash}if(!dE(c,0)&&!dE(c,18))throw new q6(`Unsupported multihash codec "${c.code}"`);let{cid:l}=await this.resolve(c,t),u=n.slice(3).join("/");return{cid:l,path:u}}else if(i==="ipfs"){let o=W.parse(n[2]),s=n.slice(3).join("/");return{cid:o,path:s}}}catch(i){Js.error("error parsing ipfs path",i)}throw Js.error("invalid ipfs path %s",e),new j6("Invalid value")}async#t(e,t={}){let n=[];if(await this.localStore.has(e,t))if(Js("record is present in the cache"),t.nocache!==!0)try{let{record:a,created:c}=await this.localStore.get(e,t);this.log("record retrieved from cache"),await Oa(e,a),this.log("record was valid");let l=Nn(a),u=Number((l.ttl??nL)/1000000n);if(c.getTime()+u>Date.now())return this.log("record TTL was valid"),l;if(t.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),l;this.log("record TTL has been reached, searching routing for updates"),n.push(a)}catch(a){this.log("cached record was invalid",a),await this.localStore.delete(e,t)}else Js("ignoring local cache due to nocache=true option");if(t.offline===!0)throw new Qe("Record was not present in the cache or has expired");Js("did not have record locally");let o=0;if(await Promise.all(this.routers.map(async a=>{let c;try{c=await a.get(e,{...t,validate:!1})}catch(l){Js.error("error finding IPNS record",l);return}try{await Oa(e,c),n.push(c)}catch(l){o++,Js.error("error finding IPNS record",l)}})),n.length===0)throw o>0?new z6(`${o>1?`${o} records`:"Record"} found for routing key ${o>1?"were":"was"} invalid`):new Qe("Could not find record for routing key");let s=n[H6(e,n)];return await this.localStore.put(e,s,t),Nn(s)}async republishRecord(e,t,n={}){let i;try{if(i=Op(t)?.toMultihash(),i==null)if(typeof e=="string"){e.startsWith(fE)&&(e=e.slice(fE.length));try{i=ot(e).toMultihash()}catch(a){throw new Error(`Invalid string key: ${a.message}`)}}else i=e;if(i==null)throw new Error("No public key multihash found to determine the routing key");let o=ks(i),s=Na(t);await Oa(o,s),await this.localStore.put(o,s,n),n.offline!==!0&&await Promise.all(this.routers.map(async a=>{await a.put(o,s,n)}))}catch(o){throw n.onProgress?.(new X("ipns:republish:error",{key:i,record:t,err:o})),o}}};function aL(r,{routers:e=[]}={}){return new pE(r,e)}var Ru=class extends Map{#e=0;#t=new Map;#r=new Map;#n;#c;#l;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.#n=e.maxSize,this.#c=e.maxAge||Number.POSITIVE_INFINITY,this.#l=e.onEviction}get __oldCache(){return this.#r}#s(e){if(typeof this.#l=="function")for(let[t,n]of e)this.#l(t,n.value)}#i(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.#l=="function"&&this.#l(e,t.value),this.delete(e)):!1}#o(e,t){if(this.#i(e,t)===!1)return t.value}#d(e,t){return t.expiry?this.#o(e,t):t.value}#a(e,t){let n=t.get(e);return this.#d(e,n)}#f(e,t){this.#t.set(e,t),this.#e++,this.#e>=this.#n&&(this.#e=0,this.#s(this.#r),this.#r=this.#t,this.#t=new Map)}#u(e,t){this.#r.delete(e),this.#f(e,t)}*#h(){for(let e of this.#r){let[t,n]=e;this.#t.has(t)||this.#i(t,n)===!1&&(yield e)}for(let e of this.#t){let[t,n]=e;this.#i(t,n)===!1&&(yield e)}}get(e){if(this.#t.has(e)){let t=this.#t.get(e);return this.#d(e,t)}if(this.#r.has(e)){let t=this.#r.get(e);if(this.#i(e,t)===!1)return this.#u(e,t),t.value}}set(e,t,{maxAge:n=this.#c}={}){let i=typeof n=="number"&&n!==Number.POSITIVE_INFINITY?Date.now()+n:void 0;return this.#t.has(e)?this.#t.set(e,{value:t,expiry:i}):this.#f(e,{value:t,expiry:i}),this}has(e){return this.#t.has(e)?!this.#i(e,this.#t.get(e)):this.#r.has(e)?!this.#i(e,this.#r.get(e)):!1}peek(e){if(this.#t.has(e))return this.#a(e,this.#t);if(this.#r.has(e))return this.#a(e,this.#r)}delete(e){let t=this.#t.delete(e);return t&&this.#e--,this.#r.delete(e)||t}clear(){this.#t.clear(),this.#r.clear(),this.#e=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this.#h()],n=t.length-e;n<0?(this.#t=new Map(t),this.#r=new Map,this.#e=t.length):(n>0&&this.#s(t.slice(0,n)),this.#r=new Map(t.slice(n)),this.#t=new Map,this.#e=0),this.#n=e}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.#t){let[t,n]=e;this.#i(t,n)===!1&&(yield[t,n.value])}for(let e of this.#r){let[t,n]=e;this.#t.has(t)||this.#i(t,n)===!1&&(yield[t,n.value])}}*entriesDescending(){let e=[...this.#t];for(let t=e.length-1;t>=0;--t){let n=e[t],[i,o]=n;this.#i(i,o)===!1&&(yield[i,o.value])}e=[...this.#r];for(let t=e.length-1;t>=0;--t){let n=e[t],[i,o]=n;this.#t.has(i)||this.#i(i,o)===!1&&(yield[i,o.value])}}*entriesAscending(){for(let[e,t]of this.#h())yield[e,t.value]}get size(){if(!this.#e)return this.#r.size;let e=0;for(let t of this.#r.keys())this.#t.has(t)||e++;return Math.min(this.#e+e,this.#n)}get maxSize(){return this.#n}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,i]of this.entriesAscending())e.call(t,i,n,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};var mi=class extends Error{static name="InvalidRangeError";constructor(e="Invalid range request"){super(e),this.name="InvalidRangeError"}},X6=class extends Error{static name="NoContentError";constructor(e="No content found"){super(e),this.name="NoContentError"}},Y6=class extends Error{static name="SubdomainNotSupportedError";constructor(e="Subdomain not supported"){super(e),this.name="SubdomainNotSupportedError"}};function cL(r,e){if(r==null)return;if(r instanceof Headers)return r.get(e)??void 0;if(Array.isArray(r))return r.find(([i])=>i.toLowerCase()===e.toLowerCase())?.[1];let t=Object.keys(r).find(n=>n.toLowerCase()===e.toLowerCase());if(t!=null)return r[t]}function lL(r,e,t){if((r??0)>(e??1/0))throw new mi("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(e??0)>=(t??1/0))throw new mi("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 mi("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new mi("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 uL({ttl:r,protocol:e,response:t}){if(t.headers.has("cache-control"))return;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 fL({byteStart:r,byteEnd:e,byteSize:t}){let n=t??"*";if((e??0)>=(t??1/0))throw new mi("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(t??1/0))throw new mi("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 i=t-1;return`bytes ${i-e+1}-${i}/${t}`}return r==null&&e==null?`bytes */${n}`:`bytes ${r}-${e}/${n}`}function Q6(r,e){e!=null&&r.headers.set("X-Ipfs-Roots",mE(e))}function mE(r){return r.map(e=>e.toV1().toString()).join(",")}function GY(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 XY(r){let e=r.match(/^bytes=(?<start>\d+)?-(?<end>\d+)?$/);if(e?.groups==null)throw new mi("Invalid range request");let{start:t,end:n}=e.groups;return{start:t,end:n}}var Z6=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=cL(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:i}=XY(this.rangeRequestHeader);this.requestRangeStart=n!=null?parseInt(n):null,this.requestRangeEnd=i!=null?parseInt(i):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??GY(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,i=this.byteSize;return t!=null||n!=null?(this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",t,n,i),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;return this.byteEnd!=null&&this.byteStart!=null?n=this.byteEnd-this.byteStart+1:n=void 0,this.log.trace("slicing body with offset=%o and length=%o",t,n),typeof e=="string"||e instanceof Blob||e instanceof ArrayBuffer||e instanceof Uint8Array?e.slice(t,n!==void 0?t+n:void 0):e}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.byteEnd-this.byteStart+1:this.byteEnd!=null?this.byteEnd+1:this.byteSize}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}=lL(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 mi("Invalid range request");return fL({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};var Lt=class{codes=[];log;pluginOptions;constructor(e){let t=this.constructor.name.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();this.log=e.logger.forComponent(t),this.pluginOptions=e}canHandle(e){throw new Error("Not implemented")}async handle(e){throw new Error("Not implemented")}};var J6=class extends Lt{canHandle(e){return e.byteRangeContext==null}async handle(e){return e.byteRangeContext=new Z6(this.pluginOptions.logger,e.options?.headers),e.modified++,null}};var wE=ht(e5(),1);var xE=40;function bE(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=wE.default.decode(r);return e.seek(wE.default.decode.bytes),t}function vE(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 bc={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},Pm={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":bc.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(bc.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Pm["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let i=e;i<r.length;i++){let o=r[i];if(o=Pm["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:bc.Int,CarV1HeaderOrV2Pragma:r=>{if(bc.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let i=0;i<e.length;i++){let[o,s]=e[i];switch(o){case"roots":{let a=Pm["CarV1HeaderOrV2Pragma > roots (anon)"](r[o]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Pm.Int(r[o]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},Rm={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":bc.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(bc.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Rm["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let i=e;i<r.length;i++){let o=r[i];if(o=Rm["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:bc.Int,CarV1HeaderOrV2Pragma:r=>{if(bc.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let i=0;i<e.length;i++){let[o,s]=e[i];switch(o){case"roots":{let a=Rm["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Rm.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},EE={toTyped:Pm.CarV1HeaderOrV2Pragma,toRepresentation:Rm.CarV1HeaderOrV2Pragma};var PGe=g7();var dQ=ht(e5(),1);var BGe=[new Q(I.map,2),new Q(I.string,"version"),new Q(I.uint,1),new Q(I.string,"roots")],LGe=new Q(I.tag,42);async function SE(r,e){let t=bE(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),i=Pa(n);if(EE.toTyped(i)===void 0)throw new Error("Invalid CAR header format");if(i.version!==1&&i.version!==2||e!==void 0&&i.version!==e)throw new Error(`Invalid CAR version: ${i.version}${e!==void 0?` (expected ${e})`:""}`);if(i.version===1){if(!Array.isArray(i.roots))throw new Error("Invalid CAR header format");return i}if(i.roots!==void 0)throw new Error("Invalid CAR header format");let o=vE(await r.exactly(xE,!0));r.seek(o.dataOffset-r.pos);let s=await SE(r,1);return Object.assign(s,o)}function Dm(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 i=r.subarray(e,e+t);return n&&(e+=t),i},seek(t){e+=t},get pos(){return e}}}var AE=ht(e5(),1),SL=1;function _E(r){let e=Tf({version:SL,roots:r}),t=AE.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function AL(r){return{async setRoots(e){let t=_E(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(AE.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 SL}}}function t5(){}function _L(){let r=[],e=null,t=t5,n=!1,i=null,o=t5,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=t5,l()}})),e),a={write(l){r.push(l);let u=s();return o(),u},async end(){n=!0;let l=s();o(),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}):(i||(i=new Promise(u=>{o=()=>(i=null,o=t5,u(c.next()))})),i)}};return{writer:a,iterator:c}}var Nm=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=W.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=gQ(e);let{encoder:t,iterator:n}=IL(),i=new r(e,t),o=new r5(n);return{writer:i,out:o}}static createAppender(){let{encoder:e,iterator:t}=IL();e.setRoots=()=>Promise.resolve();let n=new r([],e),i=new r5(t);return{writer:n,out:i}}static async updateRootsInBytes(e,t){let n=Dm(e);await SE(n);let i=_E(t);if(Number(n.pos)!==i.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${i.length} bytes)`);return e.set(i,0),e}},r5=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 IL(){let r=_L(),{writer:e,iterator:t}=r;return{encoder:AL(e),iterator:t}}function gQ(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=W.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=W.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var n5=class{async*export(e,t){for(let[,n]of t.links())yield n}};var i5=class{target;constructor(e){this.target=e}isTarget(e){return this.target.equals(e)}async*traverse(e,t){for(let[,n]of t.links())yield n}};var o5=class{components;log;constructor(e,t){this.components=e,this.log=e.logger.forComponent("helia:car")}async import(e,t){await Sr(this.components.blockstore.putMany(qt(e.blocks(),({cid:n,bytes:i})=>({cid:n,block:i})),t))}async export(e,t,n){let i=Ee(),o=Array.isArray(e)?e:[e],s={currentPath:[],pathsToTarget:null},a=n?.traversal,c=n?.exporter??new n5,l=new Pn({concurrency:1}),u=!1;l.on("idle",()=>{if(u)i.resolve();else if(!u&&s.pathsToTarget?.length===o.length){this.log.trace("starting export of blocks to the car file"),u=!0;for(let f of s.pathsToTarget){let h=f.length-1,d=f[h];f.slice(0,-1).forEach(m=>{l.add(async()=>{await this.#t({cid:m,queue:l,writer:t,strategy:c,options:n,recursive:!1})}).catch(g=>{this.log.error("error during queue operation - %e",g)})}),l.add(async()=>{await this.#t({cid:d,queue:l,writer:t,strategy:c,options:n})}).catch(m=>{this.log.error("error during queue operation - %e",m)})}}else this.log.trace("no paths to target, skipping export"),i.reject(new Error("Could not traverse to target CID(s)"))}),l.on("error",f=>{l.clear(),i.reject(f)});for(let f of o)l.add(async()=>{this.log.trace("traversing dag from %c",f),await this.#e({cid:f,queue:l,strategy:a??new i5(f),traversalContext:s,parentPath:[],options:n})}).catch(h=>{this.log.error("error during queue operation - %e",h)});try{await i.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:i}=Nm.create(e);this.export(e,n,t).catch(o=>{this.log.error("error during streaming export - %e",o)});for await(let o of i)yield o}async#e({cid:e,queue:t,strategy:n,traversalContext:i,parentPath:o,options:s}){let a=[...o,e];if(n.isTarget(e)){i.pathsToTarget=i.pathsToTarget??[],i.pathsToTarget.push([...a]),this.log.trace("found path to target %c",e);return}let c=await this.components.getCodec(e.code),l=await this.components.blockstore.get(e,s),u=bp({bytes:l,cid:e,codec:c});for await(let f of n.traverse(e,u))t.add(async()=>{await this.#e({cid:f,queue:t,strategy:n,traversalContext:i,parentPath:a??[],options:s})}).catch(h=>{this.log.error("error during traversal queue operation - %e",h)})}async#t({cid:e,queue:t,writer:n,strategy:i,options:o,recursive:s=!0}){if(o?.blockFilter?.has(e.multihash.bytes)===!0)return;let a=await this.components.getCodec(e.code),c=await this.components.blockstore.get(e,o);if(o?.blockFilter?.add(e.multihash.bytes),await n.put({cid:e,bytes:c}),s){let l=bp({bytes:c,cid:e,codec:a});for await(let u of i.export(e,l))t.add(async()=>{await this.#t({cid:u,queue:t,writer:n,strategy:i,options:o})}).catch(f=>{this.log.error("error during export queue operation - %e",f)})}}};var Om=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 Ao;(function(r){let e;(function(i){i.Raw="Raw",i.Directory="Directory",i.File="File",i.Metadata="Metadata",i.Symlink="Symlink",i.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(i){i[i.Raw=0]="Raw",i[i.Directory=1]="Directory",i[i.File=2]="File",i[i.Metadata=3]="Metadata",i[i.Symlink=4]="Symlink",i[i.HAMTShard=5]="HAMTShard"})(t||(t={})),function(i){i.codec=()=>At(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=ve((i,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),r.DataType.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),i.filesize!=null&&(o.uint32(24),o.uint64(i.filesize)),i.blocksizes!=null)for(let a of i.blocksizes)o.uint32(32),o.uint64(a);i.hashType!=null&&(o.uint32(40),o.uint64(i.hashType)),i.fanout!=null&&(o.uint32(48),o.uint64(i.fanout)),i.mode!=null&&(o.uint32(56),o.uint32(i.mode)),i.mtime!=null&&(o.uint32(66),s5.codec().encode(i.mtime,o)),s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={blocksizes:[]},a=o==null?i.len:i.pos+o;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:s.Type=r.DataType.codec().decode(i);break;case 2:s.Data=i.bytes();break;case 3:s.filesize=i.uint64();break;case 4:s.blocksizes.push(i.uint64());break;case 5:s.hashType=i.uint64();break;case 6:s.fanout=i.uint64();break;case 7:s.mode=i.uint32();break;case 8:s.mtime=s5.codec().decode(i,i.uint32());break;default:i.skipType(c&7);break}}return s})),n),r.encode=i=>be(i,r.codec()),r.decode=i=>xe(i,r.codec())})(Ao||(Ao={}));var s5;(function(r){let e;r.codec=()=>(e==null&&(e=ve((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let s=t.uint32();switch(s>>>3){case 1:i.Seconds=t.int64();break;case 2:i.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>be(t,r.codec()),r.decode=t=>xe(t,r.codec())})(s5||(s5={}));var TL;(function(r){let e;r.codec=()=>(e==null&&(e=ve((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let s=t.uint32();switch(s>>>3){case 1:i.MimeType=t.string();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>be(t,r.codec()),r.decode=t=>xe(t,r.codec())})(TL||(TL={}));var CL={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},yQ=["directory","hamt-sharded-directory"],kL=parseInt("0644",8),PL=parseInt("0755",8),Te=class r{static unmarshal(e){let t=Ao.decode(e),n=new r({type:CL[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:i,hashType:o,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(CL).includes(t))throw new Om("Type: "+t+" is not valid");this.type=t??"file",this.data=n,this.hashType=o,this.fanout=s,this.blockSizes=i??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?PL:kL:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return yQ.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=Ao.DataType.Raw;break;case"directory":e=Ao.DataType.Directory;break;case"file":e=Ao.DataType.File;break;case"metadata":e=Ao.DataType.Metadata;break;case"symlink":e=Ao.DataType.Symlink;break;case"hamt-sharded-directory":e=Ao.DataType.HAMTShard;break;default:throw new Om(`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===kL&&!this.isDirectory()&&(n=void 0),n===PL&&this.isDirectory()&&(n=void 0));let i;return this.mtime!=null&&(i={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Ao.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:i})}};function RL(r,e={}){return new o5(r,e)}function Bm(r,e={}){let t=sd(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(i){try{let{value:o,done:s}=await t.next();if(this._cancelled)return;if(s===!0){i.close();return}i.enqueue(o)}catch(o){i.error(o)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}function IE(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function ea(r,e){IE(r,"type",e)}function ta(r,e){IE(r,"url",e)}function DL(r){IE(r,"redirected",!0)}function wQ(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&DL(n),ea(n,"basic"),ta(n,r),n}function rh(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return ea(n,"basic"),ta(n,r),n}function c5(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),ea(n,"basic"),ta(n,r),n}function ra(r,e,t){let n=new Response(e,{...t??{},status:406,statusText:"Not Acceptable"});return ea(n,"basic"),ta(n,r),n}function l5(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return ea(n,"basic"),ta(n,r),n}function xQ(r){return Array.isArray(r)&&r.every(e=>e instanceof Error)}function Lm(r,e,t){let n,i;xQ(e)?(n=e[e.length-1].stack,i=e.map(a=>({message:a.message,stack:a.stack??""}))):e instanceof Error&&(n=e.stack,i=[{message:e.message,stack:e.stack??""}]);let o=JSON.stringify({stack:n,errors:i}),s=new Response(o,{status:400,statusText:"Bad Request",...t??{},headers:{...t?.headers??{},"Content-Type":"application/json"}});return ea(s,"basic"),ta(s,r),s}function Mm(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return ea(n,"basic"),ta(n,r),n}function cn(r,e,{byteRangeContext:t,log:n},i){if(!t.isRangeRequest)return wQ(r,e,i);if(!t.isValidRangeRequest)return a5(r,e,i);let o;try{o=new Response(e,{...i??{},status:206,statusText:"Partial Content",headers:{...i?.headers??{},"content-range":t.contentRangeHeaderValue}})}catch(s){return n?.error("failed to create range response",s),a5(r,e,i)}return i?.redirected===!0&&DL(o),ea(o,"basic"),ta(o,r),o}function a5(r,e,t){let n=new Response(e,{...t??{},status:416,statusText:"Requested Range Not Satisfiable"});return ea(n,"basic"),ta(n,r),n}function bQ({cid:r,ipfsPath:e,query:t}){return t.filename!=null?t.filename:`${e.replace(/\/ipfs\//,"").replace(/\/ipns\//,"").replace(/\//g,"_")}.car`}var u5=class extends Lt{canHandle(e){return this.log("checking if we can handle %c with accept %s",e.cid,e.accept),e.byteRangeContext==null?!1:e.accept?.startsWith("application/vnd.ipld.car")===!0||e.query.format==="car"}async handle(e){let{options:t,pathDetails:n,cid:i}=e,{getBlockstore:o,helia:s}=this.pluginOptions;e.reqFormat="car",e.query.download=!0,e.query.filename=bQ(e);let a=o(i,e.resource,t?.session??!0,t),c=RL({blockstore:a,getCodec:s.getCodec,logger:s.logger}),l=Bm(c.stream(n?.terminalElement.cid??i,t));e.byteRangeContext.setBody(l);let u=cn(e.resource,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:this.log});return u.headers.set("content-type","application/vnd.ipld.car; version=1"),u}};function NL(r){let e=bn(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(vp(e))}var _o=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},gi=class extends _o{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}},Xn=class extends _o{constructor(e="invalid PBNode"){super(e,"InvalidPBNodeError","ERR_INVALID_PB_NODE")}},vc=class extends _o{constructor(e="unknown error"){super(e,"InvalidPBNodeError","ERR_UNKNOWN_ERROR")}},Um=class extends _o{constructor(e="path already exists"){super(e,"AlreadyExistsError","ERR_ALREADY_EXISTS")}},nh=class extends _o{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}},ih=class extends _o{constructor(e="no content"){super(e,"NoContentError","ERR_NO_CONTENT")}},f5=class extends _o{constructor(e="not a file"){super(e,"NotAFileError","ERR_NOT_A_FILE")}},Ec=class extends _o{constructor(e="not a directory"){super(e,"NotADirectoryError","ERR_NOT_A_DIRECTORY")}},br=class extends _o{constructor(e="invalid parameters"){super(e,"InvalidParametersError","ERR_INVALID_PARAMETERS")}};function vQ(r){return r[Symbol.asyncIterator]!=null}function EQ(r){if(vQ(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 Io=EQ;var d5=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},qi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},h5=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},vr=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},p5=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},m5=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},g5=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)}},Du=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 oh(r,e,t,n,i,o,s){let a=r,c=i;for(;o.length>0;){let l=o[0];if(l in a){o.shift(),c=`${c}/${l}`;let u=W.asCID(a[l]);if(u!=null)return{entry:{type:"object",name:n,path:i,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:u,name:l,path:c,toResolve:o}};a=a[l]}else throw new g5(`No property named ${l} found in node ${t}`)}return{entry:{type:"object",name:n,path:i,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}}}}var SQ=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=Pa(c);return oh(l,c,r,e,t,n,o)},OL=SQ;var AQ=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=kf(c);return oh(l,c,r,e,t,n,o)},BL=AQ;function _Q(r,e,t,n){let i=BigInt(r.length),o=BigInt(e+i);return t>=o||n<e?new Uint8Array(0):(n>=e&&n<o&&(r=r.subarray(0,Number(n-e))),t>=e&&t<o&&(r=r.subarray(Number(t-e))),r)}var Nu=_Q;var IQ=(r,e=0,t=r)=>{let n=BigInt(r),i=BigInt(e??0),o=BigInt(t);if(o!==n&&(o=i+o),o>n&&(o=n),i<0n)throw new Du("Offset must be greater than or equal to 0");if(i>n)throw new Du("Offset must be less than the file size");if(o<0n)throw new Du("Length must be greater than or equal to 0");if(o>n)throw new Du("Length must be less than the file size");return{start:i,end:o}},sh=IQ;var TQ=r=>{async function*e(t={}){let{start:n,end:i}=sh(r.length,t.offset,t.length),o=Nu(r,0n,n,i);t.onProgress?.(new X("unixfs:exporter:progress:identity",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield o}return e},CQ=async(r,e,t,n,i,o,s,a)=>{if(n.length>0)throw new qi(`No link named ${t} found in raw node ${r}`);let c=Fe(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:TQ(c.digest),depth:o,size:BigInt(c.digest.length),node:c.digest}}},LL=CQ;var kQ=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=V8(c);return oh(l,c,r,e,t,n,o)},ML=kQ;var PQ=r=>{async function*e(t={}){let{start:n,end:i}=sh(r.length,t.offset,t.length),o=Nu(r,0n,n,i);t.onProgress?.(new X("unixfs:exporter:progress:raw",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield o}return e},RQ=async(r,e,t,n,i,o,s,a)=>{if(n.length>0)throw new qi(`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:PQ(c),depth:o,size:BigInt(c.length),node:c}}},UL=RQ;var w5=ht(HL(),1);function DQ(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 _Ye=Lc({name:"murmur3-32",code:35,encode:r=>DQ(w5.default.x86.hash32(r))}),Ou=Lc({name:"murmur3-128",code:34,encode:r=>Nc.fromHex(w5.default.x64.hash128(r))}),IYe=Lc({name:"murmur3-x64-64",code:34,encode:r=>Nc.fromHex(w5.default.x64.hash128(r)).subarray(0,8)});var KL=ht(x5(),1);var yi=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 KL.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((i,o,s)=>(o!=null&&(o instanceof r?i.push(o.serialize(e,t)):i.push(e(o,s))),i),n))}async asyncTransform(e,t){return qL(this,e,t)}toJSON(){return this.serialize(MQ,UQ)}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"?R(e):e),n=await t.take(this._options.bits),i=this._children.get(n);return i instanceof r?i._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:i}}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 i=await n._findPlace(t.existingChild.hash);return i.bucket._putAt(i,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(LQ);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 LQ(r){return!!r}function MQ(r,e){return r.key}function UQ(r){return r}async function qL(r,e,t){let n=[];for(let i of r._children.compactArray())if(i instanceof yi)await qL(i,e,t);else{let o=await e(i);n.push({bitField:r._children.bitField(),children:o})}return t(n)}var FQ=[255,254,252,248,240,224,192,128],$Q=[1,3,7,15,31,63,127,255],b5=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 i=this._value[this._currentBytePos],o=this._currentBitPos+1,s=Math.min(o,t),a=HQ(i,o-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 HQ(r,e,t){let n=VQ(e,t);return(r&n)>>>e}function VQ(r,e){return FQ[r]&$Q[Math.min(e+r-1,7)]}function jL(r){function e(t){return t instanceof v5?t:new v5(t,r)}return e}var v5=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 i=this._buffers[this._currentBufferIndex],o=Math.min(i.availableBits(),t),s=i.take(o);n=(n<<o)+s,t-=o,this._availableBits-=o,i.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?Ve([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new b5(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function ah(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:jL(r.hashFn)};return new yi(e)}var zQ=async function(r){return(await Ou.encode(r)).slice(0,8).reverse()},KQ=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async i=>{if(i.Name==null)throw new Error("Unexpected Link without a Name");if(i.Name.length===n){let o=parseInt(i.Name,16);e._putObjectAt(o,new yi({hash:t._options.hash,bits:t._options.bits},e,o));return}await t.put(i.Name.substring(2),!0)}))},WL=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),qQ=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},GL=async(r,e,t,n,i)=>{if(n==null){if(r.Data==null)throw new vr("no data in PBNode");let f;try{f=Te.unmarshal(r.Data)}catch(d){throw new vr(d.message)}if(f.type!=="hamt-sharded-directory")throw new vr("not a HAMT");if(f.fanout==null)throw new vr("missing fanout");let h=ah({hashFn:zQ,bits:Math.log2(Number(f.fanout))});n={rootBucket:h,hamtDepth:1,lastBucket:h}}let o=(n.lastBucket.tableSize()-1).toString(16).length;await KQ(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=WL(s.pos,o),c=qQ(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=WL(n.lastBucket._posAtParent,o));let l=r.Links.find(f=>{if(f.Name==null)return!1;let h=f.Name.substring(0,o),d=f.Name.substring(o);return!(h!==a||d!==""&&d!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(o)===e)return l.Hash;n.hamtDepth++;let u=await t.get(l.Hash,i);return r=nr(u),GL(r,e,t,n,i)},XL=GL;var jQ=(r,e,t,n,i,o,s)=>{async function*a(c={}){let l=c.offset??0,u=c.length??e.Links.length,f=e.Links.slice(l,u);c.onProgress?.(new X("unixfs:exporter:walk:directory",{cid:r})),yield*pt(f,h=>qt(h,d=>async()=>{let m=d.Name??"",g=`${n}/${m}`;return(await i(d.Hash,m,g,[],o+1,s,c)).entry}),h=>An(h,{ordered:!0,concurrency:c.blockReadConcurrency}),h=>ai(h,d=>d!=null))}return a},YL=jQ;async function QL(r,e,t,n,i,o,s){if(e instanceof Uint8Array){let l=Nu(e,n,i,o);t.push(l);return}if(e.Data==null)throw new vr("no data in PBNode");let a;try{a=Te.unmarshal(e.Data)}catch(l){throw new vr(l.message)}if(a.data!=null){let l=a.data,u=Nu(l,n,i,o);t.push(u),n+=BigInt(u.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new vr("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let u=e.Links[l],f=n,h=f+a.blockSizes[l];if((i>=f&&i<h||o>=f&&o<=h||i<f&&o>h)&&c.push({link:u,blockStart:n}),n=h,n>o)break}await pt(c,l=>qt(l,u=>async()=>{let f=await r.get(u.link.Hash,s);return{...u,block:f}}),l=>An(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:u,block:f,blockStart:h}of l){let d;switch(u.Hash.code){case st:d=nr(f);break;case Et:d=f;break;default:t.end(new vr(`Unsupported codec: ${u.Hash.code}`));return}let m=new Pn({concurrency:1});m.on("error",g=>{t.end(g)}),m.add(async()=>{s.onProgress?.(new X("unixfs:exporter:walk:file",{cid:u.Hash})),await QL(r,d,t,h,i,o,s)}),await m.onIdle()}}),n>=o&&t.end()}var WQ=(r,e,t,n,i,o,s)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:u,end:f}=sh(l,c.offset,c.length);if(f===0n)return;let h=0n,d=f-u,m=cr();c.onProgress?.(new X("unixfs:exporter:walk:file",{cid:r})),QL(s,e,m,0n,u,f,c).catch(g=>{m.end(g)});for await(let g of m)if(g!=null){if(h+=BigInt(g.byteLength),h>d)throw m.end(),new p5("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");h===d&&m.end(),c.onProgress?.(new X("unixfs:exporter:progress:unixfs:file",{bytesRead:h,totalBytes:d,fileSize:l})),yield g}if(h<d)throw new m5("Traversed entire DAG but did not read enough bytes")}return a},TE=WQ;var GQ=(r,e,t,n,i,o,s)=>{function a(c={}){return c.onProgress?.(new X("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),ZL(e,n,i,o,s,c)}return a};async function*ZL(r,e,t,n,i,o){let s=r.Links;if(r.Data==null)throw new vr("no data in PBNode");let a;try{a=Te.unmarshal(r.Data)}catch(u){throw new vr(u.message)}if(a.fanout==null)throw new vr("missing fanout");let c=(a.fanout-1n).toString(16).length,l=pt(s,u=>qt(u,f=>async()=>{let h=f.Name!=null?f.Name.substring(c):null;if(h!=null&&h!==""){let d=await t(f.Hash,h,`${e}/${h}`,[],n+1,i,o);return{entries:d.entry==null?[]:[d.entry]}}else{let d=await i.get(f.Hash,o);return r=nr(d),o.onProgress?.(new X("unixfs:exporter:walk:hamt-sharded-directory",{cid:f.Hash})),{entries:ZL(r,e,t,n,i,o)}}}),u=>An(u,{ordered:!0,concurrency:o.blockReadConcurrency}));for await(let{entries:u}of l)yield*u}var JL=GQ;var XQ=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,YQ={raw:TE,file:TE,directory:YL,"hamt-sharded-directory":JL,metadata:(r,e,t,n,i,o,s)=>()=>[],symlink:(r,e,t,n,i,o,s)=>()=>[]},QQ=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=nr(c),u,f;if(e==null&&(e=r.toString()),l.Data==null)throw new vr("no data in PBNode");try{u=Te.unmarshal(l.Data)}catch(d){throw new vr(d.message)}if(t==null&&(t=e),n.length>0){let d;if(u?.type==="hamt-sharded-directory"?d=await XL(l,n[0],s):d=XQ(l,n[0]),d==null)throw new qi("file does not exist");let m=n.shift(),g=`${t}/${m}`;f={cid:d,toResolve:n,name:m??"",path:g}}let h=YQ[u.type](r,l,u,t,i,o,s);if(h==null)throw new qi("could not find content exporter");return u.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:h,unixfs:u,depth:o,node:l,size:u.fileSize()},next:f}:{entry:{type:"file",name:e,path:t,cid:r,content:h,unixfs:u,depth:o,node:l,size:u.fileSize()},next:f}},eM=QQ;var ZQ={[st]:eM,[Et]:UL,[Rn]:OL,[so]:BL,[ur.code]:LL,[Bo]:ML},tM=async(r,e,t,n,i,o,s)=>{let a=ZQ[r.code];if(a==null)throw new h5(`No resolver for code ${r.code}`);return a(r,e,t,n,tM,i,o,s)},rM=tM;var JQ=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),eZ=r=>{if(r instanceof Uint8Array)return{cid:W.decode(r),toResolve:[]};let e=W.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=JQ(r);return{cid:W.parse(t[0]),toResolve:t.slice(1)}}throw new d5(`Unknown path type ${r}`)};async function*$m(r,e,t={}){let{cid:n,toResolve:i}=eZ(r),o=n.toString(),s=o,a=i.length;for(;;){let c=await rM(n,o,s,i,a,e,t);if(c.entry==null&&c.next==null)throw new qi(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;i=c.next.toResolve,n=c.next.cid,o=c.next.name,s=c.next.path}}async function gr(r,e,t={}){let n=await Io($m(r,e,t));if(n==null)throw new qi(`Could not resolve ${r}`);return n}async function*ch(r,e,t={}){let n=await gr(r,e,t);if(n==null)return;if(yield n,n.type==="directory")for await(let o of i(n,t))yield o;async function*i(o,s){for await(let a of o.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*i(a,s))}}async function tZ(r,e,t){let n=[],i;for await(let o of $m(e,r,t))n.push(o.cid),i=o;if(i==null)throw new nh("No terminal element found");return{ipfsRoots:n,terminalElement:i}}function CE(r){return r.type==="object"}async function nM({cid:r,path:e,resource:t,options:n,blockstore:i,log:o}){try{return await tZ(i,`${r.toString()}/${e}`,n)}catch(s){if(n?.signal?.aborted)throw new ft(n?.signal?.reason);return["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(s.code)?l5(t):(o.error("error walking path %s",e,s),rh(t,"Error walking path"))}}var E5=class extends Lt{codes=[Rn];canHandle({cid:e,accept:t,pathDetails:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),n==null||!CE(n.terminalElement)||e.code!==Rn||i==null?!1:CE(n.terminalElement)}async handle(e){let{cid:t,path:n,resource:i,accept:o,pathDetails:s}=e;this.log.trace("fetching %c/%s",t,n);let a=s.ipfsRoots,l=s.terminalElement.node,u;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")u=l;else if(o==="application/vnd.ipld.dag-json")try{let d=Pa(l);u=U2(d)}catch(d){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",d),ra(i)}else try{u=NL(l)}catch(d){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',d),ra(i);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",d),u=l}e.byteRangeContext.setBody(u);let f=cn(i,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:this.log}),h=o??(u instanceof Uint8Array?"application/octet-stream":"application/json");return f.headers.set("content-type",h),Q6(f,a),f}};function rZ(r){return r[Symbol.asyncIterator]!=null}function nZ(r,e=1){return e=Number(e),rZ(r)?async function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}():function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}()}var S5=nZ;async function*Hm(r,e=1){for await(let t of S5(r,e)){let n=t.map(async i=>i().then(o=>({ok:!0,value:o}),o=>({ok:!1,err:o})));for(let i=0;i<n.length;i++){let o=await n[i];if(o.ok)yield o.value;else throw o.err}}}var iZ=262144,Vm=(r={})=>{let e=r.chunkSize??iZ;return async function*(n){let i=new ge,o=0,s=!1;for await(let a of n)for(i.append(a),o+=a.length;o>=e;)if(yield i.slice(0,e),s=!0,e===i.length)i=new ge,o=0;else{let c=new ge;c.append(i.sublist(e)),i=c,o-=e}(!s||o>0)&&(yield i.subarray(0,o))}};var To=async(r,e,t)=>{t.codec==null&&(t.codec=ir);let n=await $e.digest(r),i=W.create(t.cidVersion,t.codec.code,n);return await e.put(i,r,t),i};function iM(r){return async function*(t,n){let i=0n;for await(let o of t.content)yield async()=>{let s,a={codec:ir,cidVersion:r.cidVersion,onProgress:r.onProgress};r.rawLeaves?(a.codec=Tn,a.cidVersion=1):(s=new Te({type:r.leafType,data:o}),o=Je({Data:s.marshal(),Links:[]}));let c=await To(o,n,a);return i+=BigInt(o.byteLength),r.onProgress?.(new X("unixfs:importer:progress:file:write",{bytesWritten:i,cid:c,path:t.path})),{cid:c,unixfs:s,size:BigInt(o.length),block:o}}}}var A5=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};var Sc=class r extends Error{static name="InvalidContentError";static code="ERR_INVALID_CONTENT";name=r.name;code=r.code;constructor(e="Invalid content"){super(e)}};var oM=async(r,e,t)=>{let n=new Te({type:"directory",mtime:r.mtime,mode:r.mode}),i=Je(Wt({Data:n.marshal()})),o=await To(i,e,t),s=r.path;return{cid:o,path:s,unixfs:n,size:BigInt(i.length),originalPath:r.originalPath,block:i}};async function*oZ(r,e,t){let n=-1,i;for await(let o of Hm(t.bufferImporter(r,e),t.blockWriteConcurrency)){if(n++,n===0){i={...o,single:!0};continue}else n===1&&i!=null&&(yield{...i,block:void 0,single:void 0},i=void 0);yield{...o,block:void 0}}i!=null&&(yield i)}function sM(r){return r.single===!0}var sZ=(r,e,t)=>async function(i){if(i.length===1&&sM(i[0])&&t.reduceSingleLeafToSelf){let u=i[0],f=u.block;return sM(u)&&(r.mtime!==void 0||r.mode!==void 0)&&(u.unixfs=new Te({type:"file",mtime:r.mtime,mode:r.mode,data:u.block}),f={Data:u.unixfs.marshal(),Links:[]},u.block=Je(Wt(f)),u.cid=await To(u.block,e,{...t,cidVersion:t.cidVersion}),u.size=BigInt(u.block.length)),t.onProgress?.(new X("unixfs:importer:progress:file:layout",{cid:u.cid,path:u.originalPath})),{cid:u.cid,path:r.path,unixfs:u.unixfs,size:u.size,originalPath:u.originalPath}}let o=new Te({type:"file",mtime:r.mtime,mode:r.mode}),s=i.filter(u=>u.cid.code===Et&&u.size>0||u.unixfs!=null&&u.unixfs.data==null&&u.unixfs.fileSize()>0n?!0:!!u.unixfs?.data?.length).map(u=>u.cid.code===Et?(o.addBlockSize(u.size),{Name:"",Tsize:Number(u.size),Hash:u.cid}):(u.unixfs?.data==null?o.addBlockSize(u.unixfs?.fileSize()??0n):o.addBlockSize(BigInt(u.unixfs.data.length)),{Name:"",Tsize:Number(u.size),Hash:u.cid})),a={Data:o.marshal(),Links:s},c=Je(Wt(a)),l=await To(c,e,t);return t.onProgress?.(new X("unixfs:importer:progress:file:layout",{cid:l,path:r.originalPath})),{cid:l,path:r.path,unixfs:o,size:BigInt(c.length+a.Links.reduce((u,f)=>u+(f.Tsize??0),0)),originalPath:r.originalPath,block:c}},aM=async(r,e,t)=>t.layout(oZ(r,e,t),sZ(r,e,t));function aZ(r){return Symbol.iterator in r}function cZ(r){return Symbol.asyncIterator in r}function lZ(r){try{if(r instanceof Uint8Array)return async function*(){yield r}();if(aZ(r))return async function*(){yield*r}();if(cZ(r))return r}catch{throw new Sc("Content was invalid")}throw new Sc("Content was invalid")}function cM(r){return async function*(t,n){for await(let i of t){let o;if(i.path!=null&&(o=i.path,i.path=i.path.split("/").filter(s=>s!=null&&s!==".").join("/")),uZ(i)){let s={path:i.path,mtime:i.mtime,mode:i.mode,content:async function*(){let a=0n;for await(let c of r.chunker(r.chunkValidator(lZ(i.content)))){let l=BigInt(c.byteLength);a+=l,r.onProgress?.(new X("unixfs:importer:progress:file:read",{bytesRead:a,chunkSize:l,path:i.path})),yield c}}(),originalPath:o};yield async()=>aM(s,n,r)}else if(i.path!=null){let s={path:i.path,mtime:i.mtime,mode:i.mode,originalPath:o};yield async()=>oM(s,n,r)}else throw new Error("Import candidate must have content or path or both")}}}function uZ(r){return r.content!=null}var lM=()=>async function*(e){for await(let t of e){if(t.length===void 0)throw new Sc("Content was invalid");if(typeof t=="string"||t instanceof String)yield R(t.toString());else if(Array.isArray(t))yield Uint8Array.from(t);else if(t instanceof Uint8Array)yield t;else throw new Sc("Content was invalid")}};var fZ=174;function zm(r){let e=r?.maxChildrenPerNode??fZ;return async function t(n,i){let o=[];for await(let s of S5(n,e))o.push(await i(s));return o.length>1?t(o,i):o[0]}}var as=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},Km=W.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),qm=W.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var Bu=class extends as{_children;constructor(e,t){super(e,t),this._children=new Map}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,this._children.set(e,t)}async get(e){return Promise.resolve(this._children.get(e))}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}async*eachChildSeries(){for(let[e,t]of this._children.entries())yield{key:e,child:t}}estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;this.nodeSize=0;for(let[e,t]of this._children.entries())t.size!=null&&t.cid!=null&&(this.nodeSize+=e.length+(this.options.cidVersion===1?qm.bytes.byteLength:Km.bytes.byteLength));return this.nodeSize}async*flush(e){let t=[];for(let[c,l]of this._children.entries()){let u=l;if(l instanceof as)for await(let f of l.flush(e))u=f,yield f;u.size!=null&&u.cid!=null&&t.push({Name:c,Tsize:Number(u.size),Hash:u.cid})}let n=new Te({type:"directory",mtime:this.mtime,mode:this.mode}),i={Data:n.marshal(),Links:t},o=Je(Wt(i)),s=await To(o,e,this.options),a=o.length+i.Links.reduce((c,l)=>c+(l.Tsize??0),0);this.cid=s,this.size=a,yield{cid:s,unixfs:n,path:this.path,size:BigInt(a)}}};async function dZ(r){return(await Ou.encode(r)).slice(0,8).reverse()}var uM=BigInt(34),hZ=8,kE=class extends as{_bucket;constructor(e,t){super(e,t),this._bucket=ah({hashFn:dZ,bits:t.shardFanoutBits??hZ})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=hM(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of dM(this._bucket,e,this,this.options))yield{...t,path:this.path}}},fM=kE;async function*dM(r,e,t,n){let i=r._children,o=(r.tableSize()-1).toString(16).length,s=[],a=0n;for(let m=0;m<i.length;m++){let g=i.get(m);if(g==null)continue;let w=m.toString(16).toUpperCase().padStart(o,"0");if(g instanceof yi){let x;for await(let S of dM(g,e,null,n))x=S;if(x==null)throw new Error("Could not flush sharded directory, no subshard found");s.push({Name:w,Tsize:Number(x.size),Hash:x.cid}),a+=x.size}else if(pZ(g.value)){let x=g.value,S;for await(let b of x.flush(e))S=b,yield S;if(S==null)throw new Error("Did not flush dir");let E=w+g.key;s.push({Name:E,Tsize:Number(S.size),Hash:S.cid}),a+=S.size}else{let x=g.value;if(x.cid==null)continue;let S=w+g.key,E=x.size;s.push({Name:S,Tsize:Number(E),Hash:x.cid}),a+=BigInt(E??0)}}let c=Uint8Array.from(i.bitField().reverse()),l=new Te({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:uM,mtime:t?.mtime,mode:t?.mode}),u={Data:l.marshal(),Links:s},f=Je(Wt(u)),h=await To(f,e,n),d=BigInt(f.byteLength)+a;yield{cid:h,unixfs:l,size:d}}function pZ(r){return typeof r.flush=="function"}function hM(r,e,t){let n=r._children,i=(r.tableSize()-1).toString(16).length,o=[];for(let l=0;l<n.length;l++){let u=n.get(l);if(u==null)continue;let f=l.toString(16).toUpperCase().padStart(i,"0");if(u instanceof yi){let h=hM(u,null,t);o.push({Name:f,Tsize:Number(h),Hash:t.cidVersion===0?Km:qm})}else if(typeof u.value.flush=="function"){let d=u.value.nodeSize();o.push({Name:f+u.key,Tsize:Number(d),Hash:t.cidVersion===0?Km:qm})}else{let h=u.value;if(h.cid==null)continue;let d=f+u.key,m=h.size;o.push({Name:d,Tsize:Number(m),Hash:h.cid})}}let s=Uint8Array.from(n.bitField().reverse()),a=new Te({type:"hamt-sharded-directory",data:s,fanout:BigInt(r.tableSize()),hashType:uM,mtime:e?.mtime,mode:e?.mode});return Je(Wt({Data:a.marshal(),Links:o})).length}async function PE(r,e,t,n){let i=e;e instanceof Bu&&e.estimateNodeSize()>t&&(i=await mZ(e,n));let o=i.parent;if(o!=null){if(i!==e){if(r!=null&&(r.parent=i),i.parentKey==null)throw new Error("No parent key found");await o.put(i.parentKey,i)}return PE(i,o,t,n)}return i}async function mZ(r,e){let t=new fM({root:r.root,dir:!0,parent:r.parent,parentKey:r.parentKey,path:r.path,dirty:r.dirty,flat:!1,mtime:r.mtime,mode:r.mode},e);for await(let{key:n,child:i}of r.eachChildSeries())await t.put(n,i);return t}var pM=(r="")=>r.split(/(?<!\\)\//).filter(Boolean);async function gZ(r,e,t){let n=pM(r.path??""),i=n.length-1,o=e,s="";for(let a=0;a<n.length;a++){let c=n[a];s+=`${s!==""?"/":""}${c}`;let l=a===i;if(o.dirty=!0,o.cid=void 0,o.size=void 0,l)await o.put(c,r),e=await PE(null,o,t.shardSplitThresholdBytes,t);else{let u=await o.get(c);(u==null||!(u instanceof as))&&(u=new Bu({root:!1,dir:!0,parent:o,parentKey:c,path:s,dirty:!0,flat:!0,mtime:u?.unixfs?.mtime,mode:u?.unixfs?.mode},t)),await o.put(c,u),o=u}}return e}async function*mM(r,e){if(!(r instanceof as)){r.unixfs?.isDirectory()===!0&&(yield r);return}yield*r.flush(e)}function gM(r){return async function*(t,n){let i=new Bu({root:!0,dir:!0,path:"",dirty:!0,flat:!0},r),o,s=!1;for await(let a of t){if(a==null)continue;let c=`${a.originalPath??""}`.split("/")[0];c!=null&&c!==""&&(o==null?(o=c,s=!0):o!==c&&(s=!1)),i=await gZ(a,i,r),a.unixfs?.isDirectory()!==!0&&(yield a)}if(r.wrapWithDirectory||s&&i.childCount()>1)yield*mM(i,n);else for await(let a of i.eachChildSeries())a!=null&&(yield*mM(a.child,n))}}async function*Lu(r,e,t={}){let n;Symbol.asyncIterator in r||Symbol.iterator in r?n=r:n=[r];let i=t.wrapWithDirectory??!1,o=t.shardSplitThresholdBytes??262144,s=t.shardFanoutBits??8,a=t.cidVersion??1,c=t.rawLeaves??!0,l=t.leafType??"file",u=t.fileImportConcurrency??50,f=t.blockWriteConcurrency??10,h=t.reduceSingleLeafToSelf??!0,d=t.chunker??Vm(),m=t.chunkValidator??lM(),g=t.dagBuilder??cM({chunker:d,chunkValidator:m,wrapWithDirectory:i,layout:t.layout??zm(),bufferImporter:t.bufferImporter??iM({cidVersion:a,rawLeaves:c,leafType:l,onProgress:t.onProgress}),blockWriteConcurrency:f,reduceSingleLeafToSelf:h,cidVersion:a,onProgress:t.onProgress}),w=t.treeBuilder??gM({wrapWithDirectory:i,shardSplitThresholdBytes:o,shardFanoutBits:s,cidVersion:a,onProgress:t.onProgress});for await(let x of w(Hm(g(n,e),u),e))yield{cid:x.cid,path:x.path,unixfs:x.unixfs,size:x.size}}async function yM(r,e,t={}){let n=await Vf(Lu([r],e,t));if(n==null)throw new A5("Nothing imported");return n}async function wM(r,e,t={}){return yM({content:r},e,t)}async function xM(r,e,t={}){return yM({content:r},e,t)}var jm={cidVersion:1,rawLeaves:!0,layout:zm({maxChildrenPerNode:1024}),chunker:Vm({chunkSize:1048576})};async function*_5(r,e,t={}){yield*Lu(r,e,{...jm,...t})}async function bM(r,e,t={}){let{cid:n}=await wM(r,e,{...jm,...t});return n}async function vM(r,e,t={}){let{cid:n}=await xM(r,e,{...jm,...t});return n}async function EM(r,e,t={}){if(r.path==null)throw new br("path is required");if(r.content==null)throw new br("content is required");let n=await Io(_5([r],e,{...jm,...t,wrapWithDirectory:!0}));if(n==null)throw new br("Nothing imported");return n.cid}async function SM(r,e,t={}){if(r.content!=null)throw new br("Directories cannot have content, use addFile instead");let i=await(r.path==null?Vf:Io)(_5([{...r,path:r.path??"-"}],e,{...jm,...t,wrapWithDirectory:r.path!=null}));if(i==null)throw new br("Nothing imported");return i.cid}var OE=ht(x5(),1);function T5(r){function e(t){return t instanceof I5?t:new I5(t,r)}return e}var I5=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 i=this._buffers[this._currentBufferIndex],o=Math.min(i.availableBits(),t),s=i.take(o);n=(n<<o)+s,t-=o,this._availableBits-=o,i.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?Ve([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new RE(t);this._buffers.push(n),this._availableBits+=n.availableBits()}},yZ=[255,254,252,248,240,224,192,128],wZ=[1,3,7,15,31,63,127,255],RE=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 i=this._value[this._currentBytePos],o=this._currentBitPos+1,s=Math.min(o,t),a=xZ(i,o-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 xZ(r,e,t){let n=bZ(e,t);return(r&n)>>>e}function bZ(r,e){return yZ[r]&wZ[Math.min(e+r-1,7)]}var Wm=BigInt(Ou.code),Mu=8;async function lh(r){return(await Ou.encode(r)).subarray(0,8).reverse()}var IM=ht(x5(),1);var Co=async(r,e,t)=>{t.codec==null&&(t.codec=ir);let n=await $e.digest(r),i=W.create(t.cidVersion,t.codec.code,n);return await e.put(i,r,{...t,signal:t.signal}),i};var DE=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},C5=class extends DE{_bucket;constructor(e,t){super(e,t),this._bucket=ah({hashFn:lh,bits:8})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=_M(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of AM(this._bucket,e,this,this.options))yield{...t,path:this.path}}};async function*AM(r,e,t,n){let i=r._children,o=[],s=0n;for(let d=0;d<i.length;d++){let m=i.get(d);if(m==null)continue;let g=d.toString(16).toUpperCase().padStart(2,"0");if(m instanceof yi){let w;for await(let x of AM(m,e,null,n))w=x;if(w==null)throw new Error("Could not flush sharded directory, no sub-shard found");o.push({Name:g,Tsize:Number(w.size),Hash:w.cid}),s+=w.size}else if(vZ(m.value)){let w=m.value,x;for await(let E of w.flush(e))x=E,yield x;if(x==null)throw new Error("Did not flush dir");let S=g+m.key;o.push({Name:S,Tsize:Number(x.size),Hash:x.cid}),s+=x.size}else{let w=m.value;if(w.cid==null)continue;let x=g+m.key,S=w.size;o.push({Name:x,Tsize:Number(S),Hash:w.cid}),s+=BigInt(S??0)}}let a=Uint8Array.from(i.bitField().reverse()),c=new Te({type:"hamt-sharded-directory",data:a,fanout:BigInt(r.tableSize()),hashType:Wm,mtime:t?.mtime,mode:t?.mode}),l={Data:c.marshal(),Links:o},u=Je(Wt(l)),f=await Co(u,e,n),h=BigInt(u.byteLength)+s;yield{cid:f,unixfs:c,size:h}}function vZ(r){return typeof r.flush=="function"}function _M(r,e,t){let n=r._children,i=[];for(let c=0;c<n.length;c++){let l=n.get(c);if(l==null)continue;let u=c.toString(16).toUpperCase().padStart(2,"0");if(l instanceof yi){let f=_M(l,null,t);i.push({Name:u,Tsize:Number(f),Hash:t.cidVersion===0?k5:P5})}else if(typeof l.value.flush=="function"){let h=l.value.nodeSize();i.push({Name:u+l.key,Tsize:Number(h),Hash:t.cidVersion===0?k5:P5})}else{let f=l.value;if(f.cid==null)continue;let h=u+l.key,d=f.size;i.push({Name:h,Tsize:Number(d),Hash:f.cid})}}let o=Uint8Array.from(n.bitField().reverse()),s=new Te({type:"hamt-sharded-directory",data:o,fanout:BigInt(r.tableSize()),hashType:Wm,mtime:e?.mtime,mode:e?.mode});return Je(Wt({Data:s.marshal(),Links:i})).length}var k5=W.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),P5=W.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var NE=ze("helia:unixfs:commands:utils:hamt-utils"),R5=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),TM=async(r,e,t)=>{let n=new C5({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mtime:t.mtime,mode:t.mode},t);for(let o=0;o<e.length;o++)await n._bucket.put(e[o].name,{size:e[o].size,cid:e[o].cid});let i=await Io(n.flush(r));if(i==null)throw new Error("Flushing shard yielded no result");return i},D5=async(r,e,t)=>{let n=Te.unmarshal(r[0].node.Data??new Uint8Array(0)),i=BigInt(Math.pow(2,Mu));r.reverse();let o,s;for(let a=0;a<r.length;a++){let c=a===r.length-1,l=r[a],u=Uint8Array.from(l.children.bitField().reverse()),f=new Te({type:"hamt-sharded-directory",data:u,fanout:i,hashType:Wm});c&&(f.mtime=n.mtime,f.mode=n.mode),s={Data:f.marshal(),Links:l.node.Links};let h=Je(Wt(s));if(o=await Co(h,e,t),!c){let d=r[a+1];if(d==null)throw new Error("Was not operating on shard root but also had no parent?");NE("updating link in parent sub-shard with prefix %s",d.prefix),d.node.Links=d.node.Links.filter(m=>m.Name!==d.prefix),d.node.Links.push({Name:d.prefix,Hash:o,Tsize:l.node.Links.reduce((m,g)=>m+(g.Tsize??0),h.byteLength)})}}if(o==null||s==null)throw new Error("Noting persisted");return{cid:o,node:s}},N5=async(r,e,t,n)=>{let o=T5(lh)(R(e)),s=[];for(;;){let a=await t.get(r,n),c=nr(a),l=new IM.default,u=await o.take(Mu),f=R5(u);s.push({prefix:f,children:l,node:c});let h;for(let m of c.Links){let g=m.Name??"";if(g.length<2)throw new Error("Invalid HAMT - link name was too short");let w=parseInt(g.substring(0,2),16);l.set(w,!0),g.startsWith(f)&&(h=m)}if(h==null){NE("no link found with prefix %s for %s",f,e);break}let d=h.Name??"";if(d.length<2)throw new Error("Invalid HAMT - link name was too short");if(d.length===2){r=h.Hash,NE("descend into sub-shard with prefix %s",d);continue}break}return{path:s,hash:o}};async function O5(r,e,t,n){if(r.Data==null)throw new Error("DagPB node had no data");let i=Te.unmarshal(r.Data),o;if(i.type==="directory")o=EZ(r);else if(i.type==="hamt-sharded-directory")o=await CM(r,0,t,e,n);else throw new Error("Can only estimate the size of directories or shards");return o>t}function EZ(r){let e=0;for(let t of r.Links)e+=(t.Name??"").length,e+=t.Hash.version===1?P5.bytes.byteLength:k5.bytes.byteLength;return e}async function CM(r,e,t,n,i){if(e>t)return t;if(r.Data==null||!Te.unmarshal(r.Data).isDirectory())return e;for(let s of r.Links){let a=s.Name??"";if(a=a.substring(2),e+=a.length,e+=s.Hash.bytes.byteLength,s.Hash.code===st){let c=await n.get(s.Hash,i),l=nr(c);e+=await CM(l,e,t,n,i)}}return e}var cs=ze("helia:unixfs:components:utils:add-link");async function uh(r,e,t,n){if(r.node.Data==null)throw new br("Invalid parent passed to addLink");if(Te.unmarshal(r.node.Data).type==="hamt-sharded-directory")return cs("adding link to sharded directory"),_Z(r,e,t,n);cs(`adding ${e.Name} (${e.Hash}) to regular directory`);let o=await AZ(r,e,t,n);if(await O5(o.node,t,n.shardSplitThresholdBytes,n)){cs("converting directory to sharded directory");let s=await SZ(o,t);o.cid=s.cid,o.node=nr(await t.get(s.cid,n))}return o}var SZ=async(r,e)=>{if(r.node.Data==null)throw new br("Invalid parent passed to convertToShardedDirectory");let t=Te.unmarshal(r.node.Data),n=await TM(e,r.node.Links.map(i=>({name:i.Name??"",size:BigInt(i.Tsize??0),cid:i.Hash})),{mode:t.mode,mtime:t.mtime,cidVersion:r.cid.version});return cs(`converted directory to sharded directory ${n.cid}`),n},AZ=async(r,e,t,n)=>{let i=r.node.Links.filter(u=>{let f=u.Name===e.Name;if(f&&!n.allowOverwriting)throw new Um;return!f});if(i.push(e),r.node.Data==null)throw new Xn("Parent node with no data passed to addToDirectory");let o=Te.unmarshal(r.node.Data),s;if(o.mtime!=null){let u=Date.now(),f=Math.floor(u/1e3);o.mtime={secs:BigInt(f),nsecs:(u-f*1e3)*1e3},s=o.marshal()}else s=r.node.Data;r.node=Wt({Data:s,Links:i});let a=Je(r.node),c=await $e.digest(a),l=W.create(r.cid.version,st,c);return await t.put(l,a),{node:r.node,cid:l}},_Z=async(r,e,t,n)=>{let{path:i,hash:o}=await N5(r.cid,e.Name,t,n),s=i[i.length-1];if(s==null)throw new Error("Invalid HAMT, could not generate path");let a=s.prefix,c=parseInt(a,16);cs("next prefix for %s is %s",e.Name,a);let l=`${a}${e.Name}`,u=s.node.Links.find(f=>(f.Name??"").startsWith(a));if(u!=null)if(cs("link %s was present in shard",l),u.Name===l){if(!n.allowOverwriting)throw new Um;cs("overwriting %s in sub-shard",e.Name),s.node.Links=s.node.Links.filter(f=>f.Name!==l),s.node.Links.push({Name:l,Hash:e.Hash,Tsize:e.Tsize})}else{if(u.Name?.length===2)throw new Error("Existing link was sub-shard?!");{cs("prefix %s already exists, creating new sub-shard",a);let f=s.node.Links.findIndex(w=>w.Name?.startsWith(a)),h=s.node.Links.splice(f,1)[0],d=(h.Name??"").substring(2),g=T5(lh)(R(d));for(let w=0;w<i.length;w++)await g.take(Mu);for(;;){let w=await g.take(Mu),x=R5(w);h.Name=`${x}${d}`;let S=await o.take(Mu),E=R5(S);if(x===E){let T=new OE.default;T.set(S,!0),i.push({prefix:E,children:T,node:{Links:[]}});continue}let b=new OE.default;b.set(S,!0),b.set(w,!0),i.push({prefix:a,children:b,node:{Links:[h,{Name:`${E}${e.Name}`,Hash:e.Hash,Tsize:e.Tsize}]}});break}}}else cs("link %s was not present in sub-shard",l),e.Name=l,s.node.Links.push(e),s.children.set(c,!0),cs("adding %s to existing sub-shard",l);return D5(i,t,n)};async function Ac(r,e,t={}){let n=await gr(r,e,t);if(n.type!=="directory")throw new Ec(`${r.toString()} was not a UnixFS directory`);return{cid:r,node:n.node}}async function fh(r,e,t,n){let i=await gr(r,t,n);if(i.type!=="directory"&&i.type!=="file"&&i.type!=="raw")throw new gi(`${r.toString()} was not a UnixFS node`);return{Name:e,Tsize:i.node instanceof Uint8Array?i.node.byteLength:IZ(i.node),Hash:r}}function IZ(r){let e=r.Links.reduce((t,n)=>t+(n.Tsize??0),0);return Je(r).byteLength+e}var TZ=ze("helia:unixfs:components:utils:resolve");async function ls(r,e,t,n){if(e==null||e==="")return{cid:r};let i=`/ipfs/${r}${e==null?"":`/${e}`}`,o=await Ps($m(i,t,n));if(o.length===0)throw new nh("Could not find path in directory");return TZ("resolved %s to %c",e,r),{cid:o[o.length-1].cid,path:e,segments:o}}async function dh(r,e,t,n){if(e.segments==null||e.segments.length===0)return r;let i=e.segments.pop();if(i==null)throw new Error("Insufficient segments");i.cid=r,e.segments.reverse();for(let o of e.segments){let[s,a]=await Promise.all([Ac(o.cid,t,n),fh(i.cid,i.name,t,n)]);r=(await uh(s,a,t,{...n,allowOverwriting:!0,cidVersion:r.version})).cid,o.cid=r,i=o}return r}var CZ=Gt.bind({ignoreUndefined:!0}),kZ={};async function*kM(r,e,t={}){let n=CZ(kZ,t),i=await ls(r,n.path,e,n),o=await gr(i.cid,e,n);if(o.type!=="file"&&o.type!=="raw")throw new f5;if(o.content==null)throw new ih;yield*o.content(n)}var PZ=Gt.bind({ignoreUndefined:!0}),RZ=ze("helia:unixfs:chmod"),DZ={recursive:!1,shardSplitThresholdBytes:262144};async function PM(r,e,t,n={}){let i=PZ(DZ,n),o=await ls(r,i.path,t,n);if(RZ("chmod %c %d",o.cid,e),i.recursive){let h=await pt(async function*(){for await(let d of ch(o.cid,t,n)){let m,g=[];if(d.type==="raw")m=new Te({type:"file",data:d.node});else if(d.type==="file"||d.type==="directory")m=d.unixfs,g=d.node.Links;else throw new gi;m.mode=e;let w={Data:m.marshal(),Links:g};yield{path:d.path,content:w}}},d=>Lu(d,t,{...i,dagBuilder:async function*(m,g){for await(let w of m)yield async function(){let x=w.content,S=Je(x),E=await Co(S,g,{...i,cidVersion:r.version});if(x.Data==null)throw new Xn(`${E} had no data`);let b=Te.unmarshal(x.Data);return{cid:E,size:BigInt(S.length),path:w.path,unixfs:b}}}}),async d=>Io(d));if(h==null)throw new vc(`Could not chmod ${o.cid.toString()}`);return dh(h.cid,o,t,i)}let s=await t.get(o.cid,n),a,c=[];if(o.cid.code===Et)a=new Te({type:"file",data:s});else{let h=nr(s);if(h.Data==null)throw new Xn(`${o.cid.toString()} had no data`);c=h.Links,a=Te.unmarshal(h.Data)}a.mode=e;let l=Je({Data:a.marshal(),Links:c}),u=await $e.digest(l),f=W.create(o.cid.version,st,u);return await t.put(f,l),dh(f,o,t,i)}var NZ=Gt.bind({ignoreUndefined:!0}),OZ=ze("helia:unixfs:cp"),BZ={force:!1,shardSplitThresholdBytes:262144};async function RM(r,e,t,n,i={}){let o=NZ(BZ,i);if(t.includes("/"))throw new br("Name must not have slashes");let[s,a]=await Promise.all([Ac(e,n,o),fh(r,t,n,o)]);return OZ('Adding %c as "%s" to %c',r,t,e),(await uh(s,a,n,{allowOverwriting:o.force,cidVersion:e.version,...o})).cid}var LZ=Gt.bind({ignoreUndefined:!0}),MZ={};async function*DM(r,e,t={}){let n=LZ(MZ,t),i=await ls(r,n.path,e,n),o=await gr(i.cid,e);if(o.type==="file"||o.type==="raw"){yield o;return}if(o.content==null)throw new ih;if(o.type!=="directory")throw new Ec;yield*o.content({offset:t.offset,length:t.length})}var UZ=Gt.bind({ignoreUndefined:!0}),NM=ze("helia:unixfs:mkdir"),FZ={cidVersion:1,force:!1,shardSplitThresholdBytes:262144};async function OM(r,e,t,n={}){let i=UZ(FZ,n);if(e.includes("/"))throw new br("Path must not have slashes");if((await gr(r,t,n)).type!=="directory")throw new Ec(`${r.toString()} was not a UnixFS directory`);NM("creating %s",e);let a={Data:new Te({type:"directory",mode:i.mode,mtime:i.mtime}).marshal(),Links:[]},c=Je(a),l=await $e.digest(c),u=W.create(i.cidVersion,st,l);await t.put(u,c);let[f,h]=await Promise.all([Ac(r,t,i),fh(u,e,t,i)]);return NM("adding empty dir called %s to %c",e,r),(await uh(f,h,t,{...i,allowOverwriting:i.force})).cid}var L5=ze("helia:unixfs:utils:remove-link");async function BM(r,e,t,n){if(r.node.Data==null)throw new Xn("Parent node had no data");if(Te.unmarshal(r.node.Data).type==="hamt-sharded-directory"){L5(`removing ${e} from sharded directory`);let o=await HZ(r,e,t,n);return await O5(o.node,t,n.shardSplitThresholdBytes,n)?o:(L5("converting shard to flat directory %c",r.cid),VZ(o,t,n))}return L5(`removing link ${e} regular directory`),$Z(r,e,t,n)}var $Z=async(r,e,t,n)=>{r.node.Links=r.node.Links.filter(s=>s.Name!==e);let i=Je(r.node),o=await Co(i,t,{...n,cidVersion:r.cid.version});return L5(`Updated regular directory ${o}`),{node:r.node,cid:o}},HZ=async(r,e,t,n)=>{let{path:i}=await N5(r.cid,e,t,n),o=i[i.length-1];if(o==null)throw new Error("Invalid HAMT, could not generate path");let s=o.node.Links.filter(l=>(l.Name??"").substring(2)===e).map(l=>l.Name).pop();if(s==null)throw new Error("File not found");let a=s.substring(0,2),c=parseInt(a,16);if(o.node.Links=o.node.Links.filter(l=>l.Name!==s),o.children.unset(c),o.node.Links.length===1)for(;i.length!==1;){let l=i[i.length-1];if(l==null||l.node.Links.length>1)break;i.pop();let u=i[i.length-1];if(u==null)break;let f=l.node.Links[0];u.node.Links=u.node.Links.filter(h=>!(h.Name??"").startsWith(u.prefix)),u.node.Links.push({Hash:f.Hash,Name:`${u.prefix}${(f.Name??"").substring(2)}`,Tsize:f.Tsize})}return D5(i,t,n)},VZ=async(r,e,t)=>{if(r.node.Data==null)throw new br("Invalid parent passed to convertToFlatDirectory");let n={Links:[]},i=await gr(r.cid,e);if(i.type!=="directory")throw new Error("Unexpected node type");for await(let c of i.content()){let l=0;c.node instanceof Uint8Array?l=c.node.byteLength:l=Je(c.node).length,n.Links.push({Hash:c.cid,Name:c.name,Tsize:l})}let o=Te.unmarshal(r.node.Data);n.Data=new Te({type:"directory",mode:o.mode,mtime:o.mtime}).marshal();let s=Je(Wt(n));return{cid:await Co(s,e,{codec:ir,cidVersion:r.cid.version,signal:t.signal}),node:n}};var zZ=Gt.bind({ignoreUndefined:!0}),KZ=ze("helia:unixfs:rm"),qZ={shardSplitThresholdBytes:262144};async function LM(r,e,t,n={}){let i=zZ(qZ,n);if(e.includes("/"))throw new br("Name must not have slashes");let o=await Ac(r,t,i);return KZ("Removing %s from %c",e,r),(await BM(o,e,t,{...i,cidVersion:r.version})).cid}var MM=1877,M5=1604,jZ=Gt.bind({ignoreUndefined:!0}),WZ=ze("helia:unixfs:stat"),GZ={};async function UM(r,e,t={}){let n=jZ(GZ,t),i=await ls(r,t.path,e,n);WZ("stat %c",i.cid);let o=await gr(i.cid,e,n);if(o.type==="raw")return t.extended===!0?ZZ(o):QZ(o);if(o.type==="file"||o.type==="directory")return t.extended===!0?YZ(o,e,t.filter??new xf({filterSize:1024}),t):XZ(o);throw new gi}function XZ(r){return{type:r.type,cid:r.cid,unixfs:r.unixfs,mode:r.unixfs.mode??(r.unixfs.isDirectory()?MM:M5),mtime:r.unixfs.mtime,size:r.unixfs.fileSize()}}async function YZ(r,e,t,n){let i=await FM(r.cid,e,!1,t,n);return{type:r.type,cid:r.cid,unixfs:r.unixfs,size:r.unixfs.isDirectory()?i.dirSize:r.unixfs.fileSize(),mode:r.unixfs.mode??(r.unixfs.isDirectory()?MM:M5),mtime:r.unixfs.mtime,localSize:i.localSize,dagSize:i.dagSize,deduplicatedDagSize:i.deduplicatedDagSize,blocks:i.blocks,uniqueBlocks:i.uniqueBlocks}}function QZ(r){return{type:r.type,cid:r.cid,unixfs:void 0,mode:M5,mtime:void 0,size:BigInt(r.node.byteLength)}}function ZZ(r){return{type:r.type,cid:r.cid,unixfs:void 0,mode:M5,mtime:void 0,size:BigInt(r.node.byteLength),localSize:BigInt(r.node.byteLength),dagSize:BigInt(r.node.byteLength),deduplicatedDagSize:BigInt(r.node.byteLength),blocks:1n,uniqueBlocks:1n}}async function FM(r,e,t,n,i){let o={dirSize:0n,localSize:0n,dagSize:0n,deduplicatedDagSize:0n,blocks:0n,uniqueBlocks:0n};try{let s=n.has(r.bytes);n.add(r.bytes);let a=await e.get(r,i);if(o.blocks++,o.dagSize+=BigInt(a.byteLength),s||(o.uniqueBlocks++,o.deduplicatedDagSize+=BigInt(a.byteLength)),r.code===Et)o.localSize+=BigInt(a.byteLength),t&&(o.dirSize+=BigInt(a.byteLength));else if(r.code===st){let c=nr(a),l;if(c.Data!=null&&(l=Te.unmarshal(c.Data)),c.Links.length>0){for(let u of c.Links){let f=await FM(u.Hash,e,JZ(u,l),n,i);o.localSize+=f.localSize,o.dagSize+=f.dagSize,o.deduplicatedDagSize+=f.deduplicatedDagSize,o.blocks+=f.blocks,o.uniqueBlocks+=f.uniqueBlocks,o.dirSize+=f.dirSize}t&&l!=null&&(o.dirSize+=l.fileSize())}else{if(l==null)throw new Xn(`PBNode ${r.toString()} had no data`);l.data!=null&&(o.localSize+=BigInt(l.data.byteLength??0)),t&&(o.dirSize+=l.fileSize())}}else throw new vc(`${r.toString()} was neither DAG_PB nor RAW`)}catch(s){if(s.name!=="NotFoundError"||i.offline!==!0)throw s}return o}function JZ(r,e){if(e==null)return!1;let t=r.Name;return t==null?!1:e.type==="directory"?!0:e.type==="hamt-sharded-directory"&&t.length>2}var eJ=Gt.bind({ignoreUndefined:!0}),tJ=ze("helia:unixfs:touch"),rJ={recursive:!1,shardSplitThresholdBytes:262144};async function $M(r,e,t={}){let n=eJ(rJ,t),i=await ls(r,n.path,e,n),o=n.mtime??{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(tJ("touch %c %o",i.cid,o),n.recursive){let h=await pt(async function*(){for await(let d of ch(i.cid,e)){let m,g;if(d.type==="raw")m=new Te({data:d.node}),g=[];else if(d.type==="file"||d.type==="directory")m=d.unixfs,g=d.node.Links;else throw new gi;m.mtime=o;let w={Data:m.marshal(),Links:g};yield{path:d.path,content:w}}},d=>Lu(d,e,{...n,dagBuilder:async function*(m,g){for await(let w of m)yield async function(){let x=w.content,S=Je(x),E=await Co(S,g,{...n,cidVersion:r.version});if(x.Data==null)throw new Xn(`${E} had no data`);let b=Te.unmarshal(x.Data);return{cid:E,size:BigInt(S.length),path:w.path,unixfs:b}}}}),async d=>Io(d));if(h==null)throw new vc(`Could not chmod ${i.cid.toString()}`);return dh(h.cid,i,e,n)}let s=await e.get(i.cid,t),a,c=[];if(i.cid.code===Et)a=new Te({data:s});else{let h=nr(s);if(c=h.Links,h.Data==null)throw new Xn(`${i.cid.toString()} had no data`);a=Te.unmarshal(h.Data)}a.mtime=o;let l=Je({Data:a.marshal(),Links:c}),u=await $e.digest(l),f=W.create(i.cid.version,st,u);return await e.put(f,l),dh(f,i,e,n)}var U5=class{components;constructor(e){this.components=e}async*addAll(e,t={}){yield*_5(e,this.components.blockstore,t)}async addBytes(e,t={}){return bM(e,this.components.blockstore,t)}async addByteStream(e,t={}){return vM(e,this.components.blockstore,t)}async addFile(e,t={}){return EM(e,this.components.blockstore,t)}async addDirectory(e={},t={}){return SM(e,this.components.blockstore,t)}async*cat(e,t={}){yield*kM(e,this.components.blockstore,t)}async chmod(e,t,n={}){return PM(e,t,this.components.blockstore,n)}async cp(e,t,n,i={}){return RM(e,t,n,this.components.blockstore,i)}async*ls(e,t={}){yield*DM(e,this.components.blockstore,t)}async mkdir(e,t,n={}){return OM(e,t,this.components.blockstore,n)}async rm(e,t,n={}){return LM(e,t,this.components.blockstore,n)}async stat(e,t={}){return UM(e,this.components.blockstore,t)}async touch(e,t={}){return $M(e,this.components.blockstore,t)}};function HM(r){return new U5(r)}async function VM(r,e,t,n){let i=t.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),o=r[Symbol.asyncIterator](),{value:s,done:a}=await o.next();if(a===!0)throw i.error("no content found for path",e),new X6;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:u,done:f}=await o.next();if(n?.signal?.aborted){l.error(new ft(n.signal.reason??"signal aborted by user")),l.close();return}if(f===!0){u!=null&&(n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(u)),l.close();return}n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(u)}}),firstChunk:s}}var KM=ht(zM(),1);function Yn(r){return new DataView(r.buffer,r.byteOffset)}var qM={len:1,get(r,e){return Yn(r).getUint8(e)},put(r,e,t){return Yn(r).setUint8(e,t),e+1}},Mt={len:2,get(r,e){return Yn(r).getUint16(e,!0)},put(r,e,t){return Yn(r).setUint16(e,t,!0),e+2}},hh={len:2,get(r,e){return Yn(r).getUint16(e)},put(r,e,t){return Yn(r).setUint16(e,t),e+2}};var sr={len:4,get(r,e){return Yn(r).getUint32(e,!0)},put(r,e,t){return Yn(r).setUint32(e,t,!0),e+4}},jM={len:4,get(r,e){return Yn(r).getUint32(e)},put(r,e,t){return Yn(r).setUint32(e,t),e+4}};var WM={len:4,get(r,e){return Yn(r).getInt32(e)},put(r,e,t){return Yn(r).setInt32(e,t),e+4}};var GM={len:8,get(r,e){return Yn(r).getBigUint64(e,!0)},put(r,e,t){return Yn(r).setBigUint64(e,t,!0),e+8}};var Qn=class{constructor(e,t){this.len=e,this.encoding=t,this.textDecoder=new TextDecoder(t)}get(e,t){return this.textDecoder.decode(e.subarray(t,t+this.len))}};var iJ="End-Of-Stream",Vt=class extends Error{constructor(){super(iJ),this.name="EndOfStreamError"}},Uu=class extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Fu=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0)throw new Vt;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let i=this.peekQueue.pop();if(!i)throw new Error("peekData should be defined");let o=Math.min(i.length,t);e.set(i.subarray(0,o),n),n+=o,t-=o,o<i.length&&this.peekQueue.push(i.subarray(o))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new Uu;let i=await this.readFromStream(e.subarray(n),t);if(i===0)break;n+=i}if(!t&&n<e.length)throw new Vt;return n}};var F5=class extends Fu{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}};var Gm=class extends F5{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}};var ph=class extends Fu{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let i=await this.reader.read();if(i.done){this.endOfStream=!0;break}i.value&&(n+=this.writeChunk(e.subarray(n),i.value))}if(n===0&&this.endOfStream)throw new Vt;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function LE(r){try{let e=r.getReader({mode:"byob"});return e instanceof ReadableStreamDefaultReader?new ph(e):new Gm(e)}catch(e){if(e instanceof TypeError)return new ph(r.getReader());throw e}}var $u=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new Vt;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new Vt;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new Vt;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new Vt;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};var sJ=256e3,$5=class extends $u{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),i=n.position-this.position;if(i>0)return await this.ignore(i),this.readBuffer(e,t);if(i<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let o=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=o,(!t||!t.mayBeLess)&&o<n.length)throw new Vt;return o}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),i=0;if(n.position){let o=n.position-this.position;if(o>0){let s=new Uint8Array(n.length+o);return i=await this.peekBuffer(s,{mayBeLess:n.mayBeLess}),e.set(s.subarray(o)),i-o}if(o<0)throw new Error("Cannot peek from a negative offset in a stream")}if(n.length>0){try{i=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(o){if(t?.mayBeLess&&o instanceof Vt)return 0;throw o}if(!n.mayBeLess&&i<n.length)throw new Vt}return i}async ignore(e){let t=Math.min(sJ,e),n=new Uint8Array(t),i=0;for(;i<e;){let o=e-i,s=await this.readBuffer(n,{length:Math.min(t,o)});if(s<0)return s;i+=s}return i}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}};var H5=class extends $u{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),i=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&i<n.length)throw new Vt;return e.set(this.uint8Array.subarray(n.position,n.position+i)),i}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function XM(r,e){let t=LE(r),n=e??{},i=n.onClose;return n.onClose=async()=>{if(await t.close(),i)return i()},new $5(t,n)}function YM(r,e){return new H5(r,e)}var xi=Uint8Array,mh=Uint16Array,cJ=Int32Array,QM=new xi([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ZM=new xi([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),lJ=new xi([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),JM=function(r,e){for(var t=new mh(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];for(var i=new cJ(t[30]),n=1;n<30;++n)for(var o=t[n];o<t[n+1];++o)i[o]=o-t[n]<<5|n;return{b:t,r:i}},eU=JM(QM,2),tU=eU.b,uJ=eU.r;tU[28]=258,uJ[258]=28;var rU=JM(ZM,0),fJ=rU.b,Vrt=rU.r,FE=new mh(32768);for(lt=0;lt<32768;++lt)na=(lt&43690)>>1|(lt&21845)<<1,na=(na&52428)>>2|(na&13107)<<2,na=(na&61680)>>4|(na&3855)<<4,FE[lt]=((na&65280)>>8|(na&255)<<8)>>1;var na,lt,Xm=function(r,e,t){for(var n=r.length,i=0,o=new mh(e);i<n;++i)r[i]&&++o[r[i]-1];var s=new mh(e);for(i=1;i<e;++i)s[i]=s[i-1]+o[i-1]<<1;var a;if(t){a=new mh(1<<e);var c=15-e;for(i=0;i<n;++i)if(r[i])for(var l=i<<4|r[i],u=e-r[i],f=s[r[i]-1]++<<u,h=f|(1<<u)-1;f<=h;++f)a[FE[f]>>c]=l}else for(a=new mh(n),i=0;i<n;++i)r[i]&&(a[i]=FE[s[r[i]-1]++]>>15-r[i]);return a},Ym=new xi(288);for(lt=0;lt<144;++lt)Ym[lt]=8;var lt;for(lt=144;lt<256;++lt)Ym[lt]=9;var lt;for(lt=256;lt<280;++lt)Ym[lt]=7;var lt;for(lt=280;lt<288;++lt)Ym[lt]=8;var lt,nU=new xi(32);for(lt=0;lt<32;++lt)nU[lt]=5;var lt;var dJ=Xm(Ym,9,1);var hJ=Xm(nU,5,1),ME=function(r){for(var e=r[0],t=1;t<r.length;++t)r[t]>e&&(e=r[t]);return e},ko=function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},UE=function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},pJ=function(r){return(r+7)/8|0},mJ=function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new xi(r.subarray(e,t))};var gJ=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],wi=function(r,e,t){var n=new Error(e||gJ[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,wi),!t)throw n;return n},$E=function(r,e,t,n){var i=r.length,o=n?n.length:0;if(!i||e.f&&!e.l)return t||new xi(0);var s=!t,a=s||e.i!=2,c=e.i;s&&(t=new xi(i*3));var l=function(ar){var yt=t.length;if(ar>yt){var zt=new xi(Math.max(yt*2,ar));zt.set(t),t=zt}},u=e.f||0,f=e.p||0,h=e.b||0,d=e.l,m=e.d,g=e.m,w=e.n,x=i*8;do{if(!d){u=ko(r,f,1);var S=ko(r,f+1,3);if(f+=3,S)if(S==1)d=dJ,m=hJ,g=9,w=5;else if(S==2){var M=ko(r,f,31)+257,_=ko(r,f+10,15)+4,C=M+ko(r,f+5,31)+1;f+=14;for(var L=new xi(C),G=new xi(19),F=0;F<_;++F)G[lJ[F]]=ko(r,f+F*3,7);f+=_*3;for(var K=ME(G),D=(1<<K)-1,ne=Xm(G,K,1),F=0;F<C;){var N=ne[ko(r,f,D)];f+=N&15;var E=N>>4;if(E<16)L[F++]=E;else{var U=0,Z=0;for(E==16?(Z=3+ko(r,f,3),f+=2,U=L[F-1]):E==17?(Z=3+ko(r,f,7),f+=3):E==18&&(Z=11+ko(r,f,127),f+=7);Z--;)L[F++]=U}}var V=L.subarray(0,M),A=L.subarray(M);g=ME(V),w=ME(A),d=Xm(V,g,1),m=Xm(A,w,1)}else wi(1);else{var E=pJ(f)+4,b=r[E-4]|r[E-3]<<8,T=E+b;if(T>i){c&&wi(0);break}a&&l(h+b),t.set(r.subarray(E,T),h),e.b=h+=b,e.p=f=T*8,e.f=u;continue}if(f>x){c&&wi(0);break}}a&&l(h+131072);for(var $=(1<<g)-1,Y=(1<<w)-1,H=f;;H=f){var U=d[UE(r,f)&$],le=U>>4;if(f+=U&15,f>x){c&&wi(0);break}if(U||wi(2),le<256)t[h++]=le;else if(le==256){H=f,d=null;break}else{var ke=le-254;if(le>264){var F=le-257,se=QM[F];ke=ko(r,f,(1<<se)-1)+tU[F],f+=se}var Re=m[UE(r,f)&Y],Ne=Re>>4;Re||wi(3),f+=Re&15;var A=fJ[Ne];if(Ne>3){var se=ZM[Ne];A+=UE(r,f)&(1<<se)-1,f+=se}if(f>x){c&&wi(0);break}a&&l(h+131072);var Ge=h+ke;if(h<A){var Xe=o-A,ut=Math.min(A,Ge);for(Xe+h<0&&wi(3);h<ut;++h)t[h]=n[Xe+h]}for(;h<Ge;++h)t[h]=t[h-A]}}e.l=d,e.p=H,e.b=h,e.f=u,d&&(u=1,e.m=g,e.d=m,e.n=w)}while(!u);return h!=t.length&&s?mJ(t,0,h):t.subarray(0,h)};var yJ=new xi(0);var wJ=function(r){(r[0]!=31||r[1]!=139||r[2]!=8)&&wi(6,"invalid gzip data");var e=r[3],t=10;e&4&&(t+=(r[10]|r[11]<<8)+2);for(var n=(e>>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},xJ=function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0};var bJ=function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&wi(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&wi(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2};function vJ(r,e){return $E(r,{i:2},e&&e.out,e&&e.dictionary)}function EJ(r,e){var t=wJ(r);return t+8>r.length&&wi(6,"invalid gzip data"),$E(r.subarray(t,-8),{i:2},e&&e.out||new xi(xJ(r)),e&&e.dictionary)}function SJ(r,e){return $E(r.subarray(bJ(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}function iU(r,e){return r[0]==31&&r[1]==139&&r[2]==8?EJ(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?vJ(r,e):SJ(r,e)}var AJ=typeof TextDecoder<"u"&&new TextDecoder,_J=0;try{AJ.decode(yJ,{stream:!0}),_J=1}catch{}var hU=ht(lU(),1);var Vu={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},HE={get(r){let e=Mt.get(r,6);return{signature:sr.get(r,0),compressedSize:sr.get(r,8),uncompressedSize:sr.get(r,12)}},len:16},uU={get(r){let e=Mt.get(r,6);return{signature:sr.get(r,0),minVersion:Mt.get(r,4),dataDescriptor:!!(e&8),compressedMethod:Mt.get(r,8),compressedSize:sr.get(r,18),uncompressedSize:sr.get(r,22),filenameLength:Mt.get(r,26),extraFieldLength:Mt.get(r,28),filename:null}},len:30},fU={get(r){return{signature:sr.get(r,0),nrOfThisDisk:Mt.get(r,4),nrOfThisDiskWithTheStart:Mt.get(r,6),nrOfEntriesOnThisDisk:Mt.get(r,8),nrOfEntriesOfSize:Mt.get(r,10),sizeOfCd:sr.get(r,12),offsetOfStartOfCd:sr.get(r,16),zipFileCommentLength:Mt.get(r,20)}},len:22},dU={get(r){let e=Mt.get(r,8);return{signature:sr.get(r,0),minVersion:Mt.get(r,6),dataDescriptor:!!(e&8),compressedMethod:Mt.get(r,10),compressedSize:sr.get(r,20),uncompressedSize:sr.get(r,24),filenameLength:Mt.get(r,28),extraFieldLength:Mt.get(r,30),fileCommentLength:Mt.get(r,32),relativeOffsetOfLocalHeader:sr.get(r,42),filename:null}},len:46};function pU(r){let e=new Uint8Array(sr.len);return sr.put(e,0,r),e}var us=(0,hU.default)("tokenizer:inflate"),VE=256*1024,UJ=pU(Vu.DataDescriptor),K5=pU(Vu.EndOfCentralDirectory),q5=class{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(VE)}async isZip(){return await this.peekSignature()===Vu.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(sr)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let i=n.length-4;i>=0;i--)if(n[i]===K5[0]&&n[i+1]===K5[1]&&n[i+2]===K5[2]&&n[i+3]===K5[3])return e.fileInfo.size-t+i;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){us("Cannot reading central-directory without random-read support");return}us("Reading central-directory...");let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){us("Central-directory 32-bit signature found");let n=await this.tokenizer.readToken(fU,t),i=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let o=0;o<n.nrOfEntriesOfSize;++o){let s=await this.tokenizer.readToken(dU);if(s.signature!==Vu.CentralFileHeader)throw new Error("Expected Central-File-Header signature");s.filename=await this.tokenizer.readToken(new Qn(s.filenameLength,"utf-8")),await this.tokenizer.ignore(s.extraFieldLength),await this.tokenizer.ignore(s.fileCommentLength),i.push(s),us(`Add central-directory file-entry: n=${o+1}/${i.length}: filename=${i[o].filename}`)}return this.tokenizer.setPosition(e),i}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let i=await this.readLocalFileHeader();if(!i)break;let o=e(i);n=!!o.stop;let s;if(await this.tokenizer.ignore(i.extraFieldLength),i.dataDescriptor&&i.compressedSize===0){let a=[],c=VE;us("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let l=-1;for(;l<0&&c===VE;){c=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),l=FJ(this.syncBuffer.subarray(0,c),UJ);let u=l>=0?l:c;if(o.handler){let f=new Uint8Array(u);await this.tokenizer.readBuffer(f),a.push(f)}else await this.tokenizer.ignore(u)}us(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),o.handler&&await this.inflate(i,$J(a),o.handler)}else o.handler?(us(`Reading compressed-file-data: ${i.compressedSize} bytes`),s=new Uint8Array(i.compressedSize),await this.tokenizer.readBuffer(s),await this.inflate(i,s,o.handler)):(us(`Ignoring compressed-file-data: ${i.compressedSize} bytes`),await this.tokenizer.ignore(i.compressedSize));if(us(`Reading data-descriptor at pos=${this.tokenizer.position}`),i.dataDescriptor&&(await this.tokenizer.readToken(HE)).signature!==134695760)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-HE.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let i=t(n);if(i.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let o=await this.readLocalFileHeader();if(o){await this.tokenizer.ignore(o.extraFieldLength);let s=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(s),await this.inflate(o,s,i.handler)}}if(i.stop)break}}inflate(e,t,n){if(e.compressedMethod===0)return n(t);us(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let i=iU(t);return n(i)}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(sr);if(e===Vu.LocalFileHeader){let t=await this.tokenizer.readToken(uU);return t.filename=await this.tokenizer.readToken(new Qn(t.filenameLength,"utf-8")),t}if(e===Vu.CentralFileHeader)return!1;throw e===3759263696?new Error("Encrypted ZIP"):new Error("Unexpected signature")}};function FJ(r,e){let t=r.length,n=e.length;if(n>t)return-1;for(let i=0;i<=t-n;i++){let o=!0;for(let s=0;s<n;s++)if(r[i+s]!==e[s]){o=!1;break}if(o)return i}return-1}function $J(r){let e=r.reduce((i,o)=>i+o.length,0),t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var Zrt={utf8:new globalThis.TextDecoder("utf8")};var Jrt=new globalThis.TextEncoder;var ent=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function zE(r){let{byteLength:e}=r;if(e===6)return r.getUint16(0)*2**32+r.getUint32(2);if(e===5)return r.getUint8(0)*2**32+r.getUint32(1);if(e===4)return r.getUint32(0);if(e===3)return r.getUint8(0)*2**16+r.getUint16(1);if(e===2)return r.getUint16(0);if(e===1)return r.getUint8(0)}function HJ(r,e){let t=r.length,n=e.length;if(n===0||n>t)return-1;let i=t-n;for(let o=0;o<=i;o++){let s=!0;for(let a=0;a<n;a++)if(r[o+a]!==e[a]){s=!1;break}if(s)return o}return-1}function mU(r,e){return HJ(r,e)!==-1}function gU(r){return[...r].map(e=>e.charCodeAt(0))}function yU(r,e=0){let t=Number.parseInt(new Qn(6).get(r,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(t))return!1;let n=8*32;for(let i=e;i<e+148;i++)n+=r[i];for(let i=e+156;i<e+512;i++)n+=r[i];return t===n}var wU={get:(r,e)=>r[e+3]&127|r[e+2]<<7|r[e+1]<<14|r[e]<<21,len:4};var xU=["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","ai","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","rm","ppsm","ppsx"],bU=["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/x-apache-arrow","video/mp4","audio/midi","video/x-matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/x-flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/x-parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx","application/vnd.visio","application/vnd.android.package-archive","application/vnd.google.draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia"];var KE=4100;async function vU(r){return new jE().fromBuffer(r)}function qE(r){switch(r.toLowerCase()){case"application/epub+zip":return{ext:"epub",mime:"application/epub+zip"};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:"application/vnd.oasis.opendocument.text"};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:"application/vnd.oasis.opendocument.text-template"};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:"application/vnd.oasis.opendocument.spreadsheet"};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:"application/vnd.oasis.opendocument.spreadsheet-template"};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:"application/vnd.oasis.opendocument.presentation"};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:"application/vnd.oasis.opendocument.presentation-template"};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:"application/vnd.oasis.opendocument.graphics"};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:"application/vnd.oasis.opendocument.graphics-template"};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:"application/vnd.openxmlformats-officedocument.presentationml.slideshow"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.template"};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.template"};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:"application/vnd.openxmlformats-officedocument.presentationml.template"};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"};default:}}function fs(r,e,t){t={offset:0,...t};for(let[n,i]of e.entries())if(t.mask){if(i!==(t.mask[n]&r[n+t.offset]))return!1}else if(i!==r[n+t.offset])return!1;return!0}var jE=class{constructor(e){this.detectors=[...e?.customDetectors??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:e?.signal}}async fromTokenizer(e){let t=e.position;for(let n of this.detectors){let i=await n.detect(e);if(i)return i;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(YM(t,this.tokenizerOptions))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){let t=await XM(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){let{sampleSize:n=KE}=t,i,o,s=e.getReader({mode:"byob"});try{let{value:l,done:u}=await s.read(new Uint8Array(n));if(o=l,!u&&l)try{i=await this.fromBuffer(l.slice(0,n))}catch(f){if(!(f instanceof Vt))throw f;i=void 0}o=l}finally{s.releaseLock()}let a=new TransformStream({async start(l){l.enqueue(o)},transform(l,u){u.enqueue(l)}}),c=e.pipeThrough(a);return c.fileType=i,c}check(e,t){return fs(this.buffer,e,t)}checkString(e,t){return this.check(gU(e),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(KE),e.fileInfo.size===void 0&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return{ext:"gz",mime:"application/gzip"};if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await e.ignore(6);let t=await e.readToken(wU);return e.position+t>e.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){let t;return await new q5(e).unzip(n=>{switch(n.filename){case"META-INF/mozilla.rsa":return t={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return t={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return{async handler(i){let o=new TextDecoder("utf-8").decode(i).trim();t=qE(o)},stop:!0};case"[Content_Types].xml":return{async handler(i){let o=new TextDecoder("utf-8").decode(i),s=o.indexOf('.main+xml"');if(s===-1){let a="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";o.includes(`ContentType="${a}"`)&&(t=qE(a))}else{o=o.slice(0,Math.max(0,s));let a=o.lastIndexOf('"'),c=o.slice(Math.max(0,a+1));t=qE(c)}},stop:!0};default:return/classes\d*\.dex/.test(n.filename)?(t={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}}),t??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),fs(t,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:fs(t,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:fs(t,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:fs(t,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:fs(t,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:fs(t,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/x-flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF")){try{if(await e.ignore(1350)===1350){let i=new Uint8Array(Math.min(10485760,e.fileInfo.size-1350));if(await e.readBuffer(i,{mayBeLess:!0}),mU(i,new TextEncoder().encode("AIPrivateData")))return{ext:"ai",mime:"application/postscript"}}}catch(t){if(!(t instanceof Vt))throw t}return{ext:"pdf",mime:"application/pdf"}}if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){let t=await this.readTiffHeader(!1);if(t)return t}if(this.check([77,77])){let t=await this.readTiffHeader(!0);if(t)return t}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function t(){let a=await e.peekNumber(qM),c=128,l=0;for(;(a&c)===0&&c!==0;)++l,c>>=1;let u=new Uint8Array(l+1);return await e.readBuffer(u),u}async function n(){let a=await t(),c=await t();c[0]^=128>>c.length-1;let l=Math.min(6,c.length),u=new DataView(a.buffer),f=new DataView(c.buffer,c.length-l,l);return{id:zE(u),len:zE(f)}}async function i(a){for(;a>0;){let c=await n();if(c.id===17026)return(await e.readToken(new Qn(c.len))).replaceAll(/\00.*$/g,"");await e.ignore(c.len),--a}}let o=await n();switch(await i(o.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/x-matroska"};default:return}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1"))return{ext:"parquet",mime:"application/x-parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190]))return{ext:"class",mime:"application/java-vm"};if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/vnd.google.draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){let t=new Qn(4,"latin1").get(this.buffer,2);if(t.match("^d*")&&t>=1e3&&t<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>"))return await e.ignore(8),await e.readToken(new Qn(13,"ascii"))==="debian-binary"?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(this.checkString("WEBVTT")&&[`
|
|
83
|
-
`,"\r"," "," ","\0"].some(t=>this.checkString(t,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){await e.ignore(8);async function t(){return{length:await e.readToken(WM),type:await e.readToken(new Qn(4,"latin1"))}}do{let n=await t();if(n.length<0)return;switch(n.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(n.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/x-apache-arrow"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.checkString("ftyp",{offset:4})&&(this.buffer[8]&96)!==0){let t=new Qn(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(t){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return t.startsWith("3g")?t.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.check([82,73,70,70])){if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function t(){let n=new Uint8Array(16);return await e.readBuffer(n),{id:n,size:Number(await e.readToken(GM))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),i=n.size-24;if(fs(n.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let o=new Uint8Array(16);if(i-=await e.readBuffer(o),fs(o,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(fs(o,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await e.ignore(i)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new Qn(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){let t=new DataView(this.buffer.buffer).getUint32(12,!0);if(t>12&&this.buffer.length>=t+16)try{let n=new TextDecoder().decode(this.buffer.slice(16,t+16));if(JSON.parse(n).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x.autodesk.fbx"};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),yU(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:"xml",mime:"application/xml"}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:void 0;if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"}};detectImprecise=async e=>{if(this.buffer=new Uint8Array(KE),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(this.buffer.length>=2&&this.check([255,224],{offset:0,mask:[255,224]})){if(this.check([16],{offset:1,mask:[22]}))return this.check([8],{offset:1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?hh:Mt);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?hh:Mt);for(let n=0;n<t;++n){let i=await this.readTiffTag(e);if(i)return i}}async readTiffHeader(e){let t=(e?hh:Mt).get(this.buffer,2),n=(e?jM:sr).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(n>=8){let o=(e?hh:Mt).get(this.buffer,8),s=(e?hh:Mt).get(this.buffer,10);if(o===28&&s===254||o===31&&s===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:"tif",mime:"image/tiff"}}if(t===43)return{ext:"tif",mime:"image/tiff"}}},lnt=new Set(xU),unt=new Set(bU);var _c=ze("helia:verified-fetch:content-type-parser"),j5="application/octet-stream";function VJ(r){return _c("checking for svg"),/^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(r)}async function zJ(r){_c("checking for json");try{return JSON.parse(r),!0}catch(e){return _c("failed to parse as json",e),!1}}function KJ(r){_c("checking for text");let e=new TextDecoder("utf-8",{fatal:!0});try{return e.decode(r)}catch{return null}}async function qJ(r){return _c("checking for html"),/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(r)}async function EU(r,e){_c("contentTypeParser called for fileName: %s, byte size=%s",e,r.length);let t=(await vU(r))?.mime;if(t!=null)return _c("detectedType: %s",t),t;if(_c("no detectedType"),e==null){let n=KJ(r);return n!=null?VJ(n)?"image/svg+xml":await zJ(n)?"application/json":await qJ(n)?"text/html; charset=utf-8":"text/plain; charset=utf-8":j5}switch(e.split(".").pop()){case"css":return"text/css";case"html":return"text/html; charset=utf-8";case"js":return"application/javascript";case"json":return"application/json";case"txt":return"text/plain";case"woff2":return"font/woff2";case"svg":return"image/svg+xml";case"csv":return"text/csv";case"doc":return"application/msword";case"xls":return"application/vnd.ms-excel";case"ppt":return"application/vnd.ms-powerpoint";case"msi":return"application/x-msdownload";default:return j5}}function SU(r){return r?.then!=null}async function W5({bytes:r,path:e,response:t,contentTypeParser:n,log:i,defaultContentType:o="application/octet-stream",filename:s}){let a;if(n!=null)try{let c;s==null?(c=e.split("/").pop()?.trim(),c=c===""||c?.split(".").length===1?void 0:c):c=s;let l=n(r,c);if(SU(l)){let u=await l;u!=null&&(a=u)}else l!=null&&(a=l);i.trace("contentTypeParser returned %s",a)}catch(c){i.error("error parsing content type",c)}a===j5&&(a=o),i.trace('setting content type to "%s"',a??o),t.headers.set("content-type",a??o)}var G5=class extends Lt{codes=[st];canHandle({cid:e,accept:t,pathDetails:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),n==null||i==null?!1:e.code===st}getRedirectUrl(e){let{resource:t,path:n}=e;if(n===""?!t.toString().endsWith("/"):!n.endsWith("/"))try{let o=new URL(t.toString());return o.pathname.endsWith("/")?null:(o.pathname=`${o.pathname}/`,o.toString())}catch{return`${t.toString()}/`}return null}async handle(e){let{cid:t,options:n,withServerTiming:i=!1,pathDetails:o,query:s}=e,{handleServerTiming:a,contentTypeParser:c,helia:l,getBlockstore:u}=this.pluginOptions,f=this.log,h=e.resource,d=e.path,m=!1,g=e.byteRangeContext,w=o.ipfsRoots,x=o.terminalElement,S=x.cid;if(x?.type==="directory"){let T=x.cid,M=this.getRedirectUrl(e);if(M!=null){if(f.trace("directory url normalization spec requires redirect..."),n?.redirect==="error")throw f('could not redirect to %s as redirect option was set to "error"',M),new TypeError("Failed to fetch");if(n?.redirect==="manual")return f("returning 301 permanent redirect to %s",M),Mm(h,M);f("following redirect to %s",M),h=M,m=!0}let _="index.html";try{f.trace("found directory at %c/%s, looking for index.html",t,d);let C=await a("exporter-dir","",async()=>gr(`/ipfs/${T}/${_}`,l.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),i);f.trace("found root file at %c/%s with cid %c",T,_,C.cid),d=_,S=C.cid}catch(C){if(n?.signal?.aborted)throw new ft(n?.signal?.reason);this.log.error("error loading path %c/%s",T,_,C),e.isDirectory=!0,e.directoryEntries=[],e.modified++,this.log.trace("attempting to get directory entries because index.html was not found");let L=HM({...l,blockstore:u(e.cid,e.resource,n?.session??!0,n)});try{for await(let G of L.ls(T,{signal:n?.signal,onProgress:n?.onProgress}))e.directoryEntries.push(G);return null}catch(G){return f.error("error listing directory %c",T,G),c5("Unable to get directory contents")}}finally{n?.onProgress?.(new X("verified-fetch:request:end",{cid:T,path:_}))}}g.isRangeRequest&&g.isValidRangeRequest&&x.type==="file"&&(g.setFileSize(x.unixfs.fileSize()),f.trace("fileSize for rangeRequest %d",g.getFileSize()));let E=g.offset,b=g.length;f.trace("calling exporter for %c/%s with offset=%o & length=%o",S,d,E,b);try{let M=(await a("exporter-file","",async()=>gr(S,l.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),i)).content({signal:n?.signal,onProgress:n?.onProgress,offset:E,length:b});f("got async iterator for %c/%s",t,d);let{stream:_,firstChunk:C}=await a("stream-and-chunk","",async()=>VM(M,d??"",this.pluginOptions.logger,{onProgress:n?.onProgress,signal:n?.signal}),i);g.setBody(_);let L=cn(h,g.getBody(),{byteRangeContext:g,log:f},{redirected:m});return await a("set-content-type","",async()=>W5({filename:s.filename,bytes:C,path:d,response:L,contentTypeParser:c,log:f}),i),Q6(L,w),L}catch(T){if(n?.signal?.aborted)throw new ft(n?.signal?.reason);return f.error("error streaming %c/%s",t,d,T),g.isRangeRequest&&T.code==="ERR_INVALID_PARAMS"?a5(h):rh(h.toString(),"Unable to stream content")}}};var X5=class extends Lt{canHandle(e){this.log("checking if we can handle %c with accept %s",e.cid,e.accept);let{pathDetails:t,cid:n}=e;return t!=null?!1:n.code===st||n.code===Rn}async handle(e){let{cid:t,resource:n,options:i,withServerTiming:o=!1}=e,{getBlockstore:s,handleServerTiming:a}=this.pluginOptions,c=s(t,n,i?.session??!0,i),l=await a("path-walking","",async()=>nM({...e,blockstore:c,log:this.log}),o);return l instanceof Response?(this.log.trace("path walking failed"),l.status===404?l:null):(e.modified++,e.pathDetails=l,null)}};function Y5(r){return r.charAt(0)==="1"||r.charAt(0)==="Q"?ot(r):wn(W.parse(r))}var Qm=class extends Error{name="PluginError";code;fatal;details;response;constructor(e,t,n){super(t),this.code=e,this.fatal=n?.fatal??!1,this.details=n?.details,this.response=n?.response}},ia=class extends Qm{name="PluginFatalError";constructor(e,t,n){super(e,t,{...n,fatal:!0}),this.name="PluginFatalError"}};var Q5=class extends Lt{codes=[];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/vnd.ipfs.ipns-record"||n.format==="ipns-record"}async handle(e){let{resource:t,path:n,options:i}=e,{helia:o}=this.pluginOptions;if(e.reqFormat="ipns-record",n!==""||!(t.startsWith("ipns://")||t.includes(".ipns.")||t.includes("/ipns/")))throw this.log.error('invalid request for IPNS name "%s" and path "%s"',t,n),new ia("ERR_INVALID_IPNS_NAME","Invalid IPNS name",{response:Lm(t,new Error("Invalid IPNS name"))});let s;try{let h;t.startsWith("ipns://")?h=t.replace("ipns://",""):t.includes("/ipns/")?h=t.split("/ipns/")[1].split("/")[0].split("?")[0]:h=t.split(".ipns.")[0].split("://")[1],this.log.trace('trying to parse peer id from "%s"',h),s=Y5(h)}catch(h){throw this.log.error("could not parse peer id from IPNS url %s",t,h),new ia("ERR_NO_PEER_ID_FOUND","could not parse peer id from url",{response:Lm(t,h)})}let a=Ve([R("/ipns/"),s.toMultihash().bytes]),c=new nt("/dht/record/"+q(a,"base32"),!1),l=await o.datastore.get(c,i),u=Ot.deserialize(l);e.byteRangeContext.setBody(u.value);let f=cn(t,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:this.log});return f.headers.set("content-type","application/vnd.ipfs.ipns-record"),f}};var Z5=class extends Lt{codes=[so,Bo];canHandle({cid:e,accept:t,byteRangeContext:n}){return this.log("checking if we can handle %c with accept %s",e,t),n==null?!1:t==="application/vnd.ipld.dag-json"&&e.code!==Rn?!0:so===e.code||Bo===e.code}async handle(e){let{path:t,resource:n,cid:i,accept:o,options:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.session??!0;this.log.trace("fetching %c/%s",i,t);let l=e.pathDetails?.terminalElement.cid??e.cid,f=await a(l,n,c,s).get(l,s),h;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let g=kf(f);h=Tf(g)}catch(g){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",g),ra(n)}else h=f;let d;o==null?so===i.code?d="application/vnd.ipld.dag-json":d="application/json":d=o.split(";")[0],e.byteRangeContext.setBody(h);let m=cn(n,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:this.log});return this.log.trace("setting content-type to %s",d),m.headers.set("content-type",d),e.byteRangeContext.isValidRangeRequest||m.headers.set("content-length",h.length.toString()),m}};var jJ=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function WJ({headers:r,accept:e}){let n=(e??new Headers(r).get("accept")??"").split(",").map(i=>i.split(";")[0]).map(i=>i.trim());for(let i of n){if(i==="*/*")return;if(jJ.includes(i??""))return i}}var J5=class extends Lt{codes=[Et,ur.code];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/vnd.ipld.raw"||n.format==="raw"}async handle(e){let{path:t,resource:n,cid:i,accept:o,query:s,options:a}=e,{getBlockstore:c,contentTypeParser:l}=this.pluginOptions,u=a?.session??!0,f=this.log;if(o==="application/vnd.ipld.raw"||s.format==="raw"?(e.reqFormat="raw",e.query.download=!0,e.query.filename=e.query.filename??`${i.toString()}.bin`,f.trace("Set content disposition...")):f.trace("Did NOT set content disposition..."),t!==""&&i.code===Et)throw f.trace("404-ing raw codec request for %c/%s",i,t),new ia("ERR_RAW_PATHS_NOT_SUPPORTED","Raw codec does not support paths",{response:l5(n,"Raw codec does not support paths")});let h=e.pathDetails?.terminalElement.cid??e.cid,m=await c(h,n,u,a).get(h,a);e.byteRangeContext.setBody(m);let g=cn(n,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:f},{redirected:!1});return await W5({filename:s.filename,bytes:m,path:t,response:g,defaultContentType:WJ({headers:a?.headers,accept:o}),contentTypeParser:l,log:f}),g}};var GJ=({weak:r,reqFormat:e})=>e==="tar"||e==="car"||e==="ipns-record"||r===!0?"W/":"",XJ=({reqFormat:r})=>r==null?"":r==="tar"?".x-tar":`.${r}`;function xh({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:i,contentPrefix:o}){let s=GJ({weak:t,reqFormat:e}),a=XJ({reqFormat:e});return(n!=null||i!=null)&&(a+=`.${n??"0"}-${i??"N"}`),`${s}"${o??""}${r.toString()}${a}"`}var fit=R("ustar\0","binary"),dit=R("ustar ","binary"),hit=R(" \0","binary");var CU=ht(_U(),1);function QJ(r){return r[Symbol.asyncIterator]!=null}function ZJ(r){if(QJ(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=Ve([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Ve(e,t)}var IU=ZJ;var JJ="0000000000000000000",eee="7777777777777777777",tee=48,ree=R("ustar\0","binary"),nee=R("00","binary"),iee=parseInt("7777",8),oee=257,see=263,aee=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}},cee=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},Ic=function(r,e){let t=r.toString(8);return t.length>e?R(eee.slice(0,e)+" "):R(JJ.slice(0,e-t.length)+t+" ")},WE=function(r){let e=R(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function TU(r){let e="";r.name!=null&&(e+=WE(" path="+r.name+`
|
|
82
|
+
`)}var L6=class{log;metrics;components;init;certificate;privateKey;emitter;renewCertificateTask;constructor(e,t={}){if(this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,this.emitter=new Ue,t.certificateLifespan!=null&&t.certificateRenewalThreshold!=null&&t.certificateRenewalThreshold>=t.certificateLifespan)throw new z("Certificate renewal threshold must be less than certificate lifespan");e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[ca]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[tt]=["@libp2p/transport"];async start(){this.certificate=await this.getCertificate()}async stop(){this.renewCertificateTask!=null&&clearTimeout(this.renewCertificateTask),this.certificate=void 0}async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,i=e.getPeerId();i!=null&&(n=ot(i));let o=FD(),s=await CB("client",o,typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{});try{return await TB(s,o,{role:"client",log:this.log,logger:this.components.logger,metrics:this.components.metrics,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeerId:n,privateKey:this.components.privateKey})}catch(a){throw s.close(),a}}createListener(e){if(this.certificate==null)throw new Jn;return new B6(this.components,{...this.init,...e,certificate:this.certificate,emitter:this.emitter})}listenFilter(e){return e.filter(kp.exactMatch)}dialFilter(e){return this.listenFilter(e)}async getCertificate(e){if(FY(this.init.certificate))return this.log("using provided TLS certificate"),this.init.certificate;let t=await this.loadOrCreatePrivateKey(),{pem:n,certhash:i}=await this.loadOrCreateCertificate(t,e);return{privateKey:await kB(t),pem:n,certhash:i}}async loadOrCreatePrivateKey(){if(this.privateKey!=null)return this.privateKey;let e=this.init.certificateKeychainName??PD,t=this.getKeychain();try{if(t==null)throw this.log("no keychain configured - not checking for stored private key"),new Qe;this.log.trace("checking for stored private key"),this.privateKey=await t.exportKey(e)}catch(n){if(n.name!=="NotFoundError")throw n;this.log.trace("generating private key"),this.privateKey=await yf("ECDSA","P-256"),t!=null?(this.log.trace("storing private key"),await t.importKey(e,this.privateKey)):this.log("no keychain configured - not storing private key")}return this.privateKey}async loadOrCreateCertificate(e,t){if(this.certificate!=null&&t!==!0)return this.certificate;let n,i=new nt(this.init.certificateDatastoreKey??kD),o=await t2(e);try{if(t===!0)throw this.log.trace("forcing renewal of TLS certificate"),new Qe;this.log.trace("checking for stored TLS certificate"),n=await this.loadCertificate(i,o)}catch(a){if(a.name!=="NotFoundError")throw a;this.log.trace("generating new TLS certificate"),n=await this.createCertificate(i,o)}let s=n.notAfter.getTime()-(this.init.certificateRenewalThreshold??fb)-Date.now();return s<0&&(s=100),this.log("will renew TLS certificate after %d ms",s),this.renewCertificateTask=setTimeout(()=>{this.log("renewing TLS certificate"),this.getCertificate(!0).then(a=>{this.certificate=a,this.emitter.safeDispatchEvent("certificate:renew",{detail:a})}).catch(a=>{this.log.error("could not renew certificate - %e",a)})},s),{pem:n.toString("pem"),certhash:Oc.encode((await $e.digest(new Uint8Array(n.rawData))).bytes)}}async loadCertificate(e,t){let n=await this.components.datastore.get(e),i=new th(n),o=i.notAfter.getTime()-(this.init.certificateRenewalThreshold??fb);if(Date.now()>o)throw this.log("stored TLS certificate has expired"),new Qe;this.log("loaded certificate, expires in %d ms",o);let s=await i.publicKey.export(crypto),a=await crypto.subtle.exportKey("raw",s),c=await crypto.subtle.exportKey("raw",t.publicKey);if(!pe(new Uint8Array(a,0,a.byteLength),new Uint8Array(c,0,c.byteLength)))throw this.log("stored TLS certificate public key did not match public key from private key"),new Qe;return this.log("loaded certificate, expiry time is %o",o),i}async createCertificate(e,t){let n=new Date,i=new Date(Date.now()+(this.init.certificateLifespan??RD));n.setMilliseconds(0),i.setMilliseconds(0);let o=await O6.createSelfSigned({serialNumber:(BigInt(Math.random().toString().replace(".",""))*100000n).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:n,notAfter:i,keys:t,extensions:[new Zd(!1,void 0,!0)]},crypto);return this.getKeychain()!=null?(this.log.trace("storing TLS certificate"),await this.components.datastore.put(e,R(o.toString("pem")))):this.log("no keychain is configured so not storing TLS certificate since the private key will not be reused"),o}getKeychain(){try{return this.components.keychain}catch{}}};function FY(r){return r==null?!1:typeof r.privateKey=="string"&&typeof r.pem=="string"&&typeof r.certhash=="string"}function M6(r){return e=>new L6(e,r)}function PB(r){return e=>new R4(e,r)}var RB=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",o)}function i(){n(),e()}function o(s){n(),t(s.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",o)})};var DB=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await RB(r)}catch(o){if(o.message==="socket closed")break;throw o}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(i)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((i,o)=>{r.addEventListener("close",s=>{if(s.wasClean||s.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:s});o(a)}}),setTimeout(()=>{r.close()})})});var LB=ht(OB(),1);function BB(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var MB=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((o,s)=>{if(n){o();return}if(i!=null){s(i);return}let a=u=>{r.removeEventListener("open",c),r.removeEventListener("error",l),u()},c=()=>{a(o)},l=u=>{a(()=>{s(u.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let o=new LB.EventIterator(({push:s,stop:a,fail:c})=>{let l=f=>{let h=null;typeof f.data=="string"&&(h=R(f.data)),BB(f.data)&&(h=new Uint8Array(f.data)),f.data instanceof Uint8Array&&(h=f.data),h!=null&&s(h)},u=f=>{c(f.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",u),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",u),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let s of o)yield BB(s)?new Uint8Array(s):s}(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",o=>{n||(i=o.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var UB=(r,e)=>{e=e??{};let t=MB(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let s=new URL(r.url);n=s.hostname,i=parseInt(s.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:DB(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(s=>{r.addEventListener("close",()=>{s()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var FB=WebSocket;var HY={"http:":"ws:","https:":"wss:"},$B="ws:",HB=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??$B}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??$B,i=e.host,o=e.port!=null&&i?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${i}${o}${r}`}let t=new URL(r);for(let[n,i]of Object.entries(HY))t.protocol===n&&(t.protocol=i);return t};function VB(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=HB(r,t),i=new FB(n.toString(),e.websocket);return UB(i,e)}function zB(r){return r.filter(e=>wl.exactMatch(e)||Cs.exactMatch(e))}function KB(){throw new Error("WebSocket Servers can not be created in the browser!")}function qB(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),i=t.metrics,o=t.metricPrefix??"",s={log:n,async sink(a){try{await r.sink(async function*(){for await(let c of a)c instanceof Uint8Array?yield c:yield c.subarray()}())}catch(c){c.type!=="aborted"&&n.error(c)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(a={}){let c=Date.now();if(a.signal==null){let u=AbortSignal.timeout(500);a={...a,signal:u}}let l=()=>{let{host:u,port:f}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",u,f,Date.now()-c),this.abort(new ft("Socket close timeout"))};a.signal?.addEventListener("abort",l);try{await r.close()}catch(u){n.error("error closing WebSocket gracefully",u),this.abort(u)}finally{a.signal?.removeEventListener("abort",l),s.timeline.close=Date.now()}},abort(a){let{host:c,port:l}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",c,l,a),r.destroy(),s.timeline.close=Date.now(),i?.increment({[`${o}error`]:!0})}};return r.socket.addEventListener("close",()=>{i?.increment({[`${o}close`]:!0}),s.timeline.close==null&&(s.timeline.close=Date.now())},{once:!0}),s}var cE=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[ca]=!0;[Symbol.toStringTag]="@libp2p/websockets";[tt]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=qB(n,e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",i.remoteAddr);let o=await t.upgrader.upgradeOutbound(i,t);return this.log("outbound connection %s upgraded",i.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let i=Ee(),o=VB(Lf(e),this.init);o.socket.addEventListener("error",()=>{let s=new Ku(`Could not connect to ${e.toString()}`);this.log.error("connection error:",s),this.metrics?.dialerEvents.increment({error:!0}),i.reject(s)});try{t.onProgress?.(new X("websockets:open-connection")),await Kt(Promise.race([o.connected(),i.promise]),t.signal)}catch(s){throw t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),o.close().catch(a=>{this.log.error("error closing raw socket",a)}),s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return KB({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):zB(e)}dialFilter(e){return this.listenFilter(e)}};function $6(r={}){return e=>new cE(e,r)}var lE=ht(hg(),1);function H6(r,e){let t=e.map((n,i)=>({record:Nn(n),index:i}));return t.sort((n,i)=>{let o=n.record.sequence,s=i.record.sequence;if(o>s)return-1;if(o<s)return 1;if(n.record.validityType===Nr.ValidityType.EOL&&i.record.validityType===Nr.ValidityType.EOL){let a=lE.default.fromString(n.record.validity).toDate(),c=lE.default.fromString(i.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var jB="5.4.2",WB="helia";var GB={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function km(r={}){let e=`${WB}/${jB} ${Xy()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[qx(),PB(),M6(),$6()],connectionEncrypters:[s3()],streamMuxers:[zP(),mD()],peerDiscovery:[oR(GB)],services:{autoNAT:GP(),dcutr:xR(),delegatedRouting:()=>Ig("https://delegated-ipfs.dev",x9()),dht:cD({clientMode:!0,validators:{ipns:Oa},selectors:{ipns:H6}}),identify:IR(),identifyPush:TR(),keychain:Jg(r.keychain),ping:xD()}}}async function XB(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await $9(r.datastore,r.keychain));let t=km(e);return t.datastore=t.datastore??r.datastore,await Qy({...t,...e,start:!1})}async function YB(r={}){let e=r.datastore??new bl,t=r.blockstore??new Up,n;return zY(r.libp2p)?n=r.libp2p:n=await XB({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Rp(),Sp()],routers:r.routers??[Mp(n),Lp()],metrics:n.metrics,start:r.start??!0}}function zY(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}async function QB(r={}){let e=await YB(r),t=new Cg(e);return r.start!==!1&&await t.start(),t}function ZB(){let r=km();r.start=!1,r.addresses={listen:[]},r.transports=[M6(),$6()],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 V6=class extends Error{static name="DNSLinkNotFoundError";constructor(e="DNSLink not found"){super(e),this.name="DNSLinkNotFoundError"}},z6=class extends Error{static name="RecordsFailedValidationError";constructor(e="Records failed validation"){super(e),this.name="RecordsFailedValidationError"}},K6=class extends Error{static name="UnsupportedMultibasePrefixError";constructor(e="Unsupported multibase prefix"){super(e),this.name="UnsupportedMultibasePrefixError"}},q6=class extends Error{static name="UnsupportedMultihashCodecError";constructor(e="Unsupported multihash codec"){super(e),this.name="UnsupportedMultihashCodecError"}},j6=class extends Error{static name="InvalidValueError";constructor(e="Invalid value"){super(e),this.name="InvalidValueError"}};var KY=32;async function JB(r,e,t,n,i={}){if(e===0)throw new Error("recursion limit exceeded");n("query %s for TXT and CNAME records",r);let s=((await t.query(r,{...i,types:[rn.TXT]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d TXT records for %s",s.length,r);for(let l of s)try{let u=l.data;if(u.startsWith('"')&&u.endsWith('"')&&(u=u.substring(1,u.length-1)),!u.startsWith("dnslink="))continue;n("%s TXT %s",l.name,u),u=u.replace("dnslink=","");let[,f,h,...d]=u.split("/");if(f==="ipfs")try{return{value:`/ipfs/${W.parse(h)}${d.length>0?`/${d.join("/")}`:""}`,answer:l}}catch{}else if(f==="ipns"){try{let m;return h.charAt(0)==="1"||h.charAt(0)==="Q"?m=ot(h):m=wn(W.parse(h)),{value:`/ipns/${m}${d.length>0?`/${d.join("/")}`:""}`,answer:l}}catch{}return await W6(h,e-1,t,n,i)}else{if(f==="dnslink")return await W6(h,e-1,t,n,i);n('unknown protocol "%s" in DNSLink record for domain: %s',f,r);continue}}catch(u){n.error("could not parse DNS link record for domain %s, %s",r,l.data,u)}n("no DNSLink records found for %s, falling back to CNAME",r);let c=((await t.query(r,{...i,types:[rn.CNAME]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d CNAME records for %s",c.length,r);for(let l of c)try{return await W6(l.data,e-1,t,n,i)}catch(u){n.error("domain %s cname %s had no DNSLink records",r,l.data,u)}throw new V6(`No DNSLink records found for domain: ${r}`)}async function W6(r,e,t,n,i={}){if(e===0)throw new Error("recursion limit exceeded");r.startsWith("_dnslink.")||(r=`_dnslink.${r}`);try{return await JB(r,e,t,n,i)}catch(o){if(o.code!=="ENOTFOUND"&&o.code!=="ENODATA"&&o.name!=="DNSLinkNotFoundError"&&o.name!=="NotFoundError")throw o;return r.startsWith("_dnslink.")?r=r.replace("_dnslink.",""):r=`_dnslink.${r}`,JB(r,e,t,n,i)}}async function eL(r,e,t,n={}){return W6(r,n.maxRecursiveDepth??KY,e,t,n)}var uE=class{routing;constructor(e){this.routing=e}async put(e,t,n={}){try{await this.routing.put(e,t,n)}catch(i){throw n.onProgress?.(new X("ipns:routing:helia:error",i)),i}}async get(e,t={}){try{return await this.routing.get(e,t)}catch(n){throw t.onProgress?.(new X("ipns:routing:helia:error",n)),n}}};function tL(r){return new uE(r)}function G6(r){return new nt("/dht/record/"+q(r,"base32"),!1)}function rL(r){return{async put(e,t,n={}){try{let i=G6(e);try{let s=await r.get(i),a=Ot.deserialize(s);if(pe(a.value,t))return}catch(s){if(s.name!=="NotFoundError")throw s}let o=new Ot(e,t,new Date);n.onProgress?.(new X("ipns:routing:datastore:put")),await r.put(i,o.serialize(),n)}catch(i){throw n.onProgress?.(new X("ipns:routing:datastore:error",i)),i}},async get(e,t={}){try{let n=G6(e);t.onProgress?.(new X("ipns:routing:datastore:get"));let i=await r.get(n,t),o=Ot.deserialize(i);return{record:o.value,created:o.timeReceived}}catch(n){throw t.onProgress?.(new X("ipns:routing:datastore:error",n)),n}},async has(e,t={}){let n=G6(e);return r.has(n,t)},async delete(e,t){let n=G6(e);return r.delete(n,t)}}}var fE="/ipns/";function dE(r,e){return r.code===e}var Js=ze("helia:ipns"),oL=60*1e3,sL=60*oL,WY=48*sL,hE=23*sL,nL=BigInt(oL)*5000000n,iL={[hn.prefix]:hn,[Le.prefix]:Le},pE=class{routers;localStore;timeout;dns;log;constructor(e,t=[]){this.routers=[tL(e.routing),...t],this.localStore=rL(e.datastore),this.dns=e.dns,this.log=e.logger.forComponent("helia:ipns")}async publish(e,t,n={}){try{let i=1n,o=ks(e.publicKey.toMultihash());if(await this.localStore.has(o,n)){let{record:l}=await this.localStore.get(o,n);i=Nn(l).sequence+1n}let s=n.ttl!=null?BigInt(n.ttl)*1000000n:nL,a=await eC(e,t,i,n.lifetime??WY,{...n,ttlNs:s}),c=Na(a);return await this.localStore.put(o,c,n),n.offline!==!0&&await Promise.all(this.routers.map(async l=>{await l.put(o,c,n)})),a}catch(i){throw n.onProgress?.(new X("ipns:publish:error",i)),i}}async resolve(e,t={}){let n=rS(e)?e.toMultihash():e,i=ks(n),o=await this.#t(i,t);return{...await this.#e(o.value,t),record:o}}async resolveDNSLink(e,t={}){let n=await eL(e,this.dns,this.log,t);return{...await this.#e(n.value,t),answer:n.answer}}republish(e={}){if(this.timeout!=null)throw new Error("Republish is already running");e.signal?.addEventListener("abort",()=>{clearTimeout(this.timeout)});async function t(){let n=Date.now();e.onProgress?.(new X("ipns:republish:start"));let o=Date.now()-n,s=hE-o;s<0&&(s=e.interval??hE),setTimeout(()=>{t().catch(a=>{Js.error("error republishing",a)})},s)}this.timeout=setTimeout(()=>{t().catch(n=>{Js.error("error republishing",n)})},e.interval??hE)}async#e(e,t={}){let n=e.split("/");try{let i=n[1];if(i==="ipns"){let o=n[2],s=o.substring(0,1),a;if(s==="1"||s==="Q")a=Le.decode(`z${o}`);else if(iL[s]!=null)a=iL[s].decode(o);else throw new K6(`Unsupported multibase prefix "${s}"`);let c;try{c=Fe(a)}catch{c=W.decode(a).multihash}if(!dE(c,0)&&!dE(c,18))throw new q6(`Unsupported multihash codec "${c.code}"`);let{cid:l}=await this.resolve(c,t),u=n.slice(3).join("/");return{cid:l,path:u}}else if(i==="ipfs"){let o=W.parse(n[2]),s=n.slice(3).join("/");return{cid:o,path:s}}}catch(i){Js.error("error parsing ipfs path",i)}throw Js.error("invalid ipfs path %s",e),new j6("Invalid value")}async#t(e,t={}){let n=[];if(await this.localStore.has(e,t))if(Js("record is present in the cache"),t.nocache!==!0)try{let{record:a,created:c}=await this.localStore.get(e,t);this.log("record retrieved from cache"),await Oa(e,a),this.log("record was valid");let l=Nn(a),u=Number((l.ttl??nL)/1000000n);if(c.getTime()+u>Date.now())return this.log("record TTL was valid"),l;if(t.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),l;this.log("record TTL has been reached, searching routing for updates"),n.push(a)}catch(a){this.log("cached record was invalid",a),await this.localStore.delete(e,t)}else Js("ignoring local cache due to nocache=true option");if(t.offline===!0)throw new Qe("Record was not present in the cache or has expired");Js("did not have record locally");let o=0;if(await Promise.all(this.routers.map(async a=>{let c;try{c=await a.get(e,{...t,validate:!1})}catch(l){Js.error("error finding IPNS record",l);return}try{await Oa(e,c),n.push(c)}catch(l){o++,Js.error("error finding IPNS record",l)}})),n.length===0)throw o>0?new z6(`${o>1?`${o} records`:"Record"} found for routing key ${o>1?"were":"was"} invalid`):new Qe("Could not find record for routing key");let s=n[H6(e,n)];return await this.localStore.put(e,s,t),Nn(s)}async republishRecord(e,t,n={}){let i;try{if(i=Op(t)?.toMultihash(),i==null)if(typeof e=="string"){e.startsWith(fE)&&(e=e.slice(fE.length));try{i=ot(e).toMultihash()}catch(a){throw new Error(`Invalid string key: ${a.message}`)}}else i=e;if(i==null)throw new Error("No public key multihash found to determine the routing key");let o=ks(i),s=Na(t);await Oa(o,s),await this.localStore.put(o,s,n),n.offline!==!0&&await Promise.all(this.routers.map(async a=>{await a.put(o,s,n)}))}catch(o){throw n.onProgress?.(new X("ipns:republish:error",{key:i,record:t,err:o})),o}}};function aL(r,{routers:e=[]}={}){return new pE(r,e)}var Ru=class extends Map{#e=0;#t=new Map;#r=new Map;#n;#c;#l;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.#n=e.maxSize,this.#c=e.maxAge||Number.POSITIVE_INFINITY,this.#l=e.onEviction}get __oldCache(){return this.#r}#s(e){if(typeof this.#l=="function")for(let[t,n]of e)this.#l(t,n.value)}#i(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.#l=="function"&&this.#l(e,t.value),this.delete(e)):!1}#o(e,t){if(this.#i(e,t)===!1)return t.value}#d(e,t){return t.expiry?this.#o(e,t):t.value}#a(e,t){let n=t.get(e);return this.#d(e,n)}#f(e,t){this.#t.set(e,t),this.#e++,this.#e>=this.#n&&(this.#e=0,this.#s(this.#r),this.#r=this.#t,this.#t=new Map)}#u(e,t){this.#r.delete(e),this.#f(e,t)}*#h(){for(let e of this.#r){let[t,n]=e;this.#t.has(t)||this.#i(t,n)===!1&&(yield e)}for(let e of this.#t){let[t,n]=e;this.#i(t,n)===!1&&(yield e)}}get(e){if(this.#t.has(e)){let t=this.#t.get(e);return this.#d(e,t)}if(this.#r.has(e)){let t=this.#r.get(e);if(this.#i(e,t)===!1)return this.#u(e,t),t.value}}set(e,t,{maxAge:n=this.#c}={}){let i=typeof n=="number"&&n!==Number.POSITIVE_INFINITY?Date.now()+n:void 0;return this.#t.has(e)?this.#t.set(e,{value:t,expiry:i}):this.#f(e,{value:t,expiry:i}),this}has(e){return this.#t.has(e)?!this.#i(e,this.#t.get(e)):this.#r.has(e)?!this.#i(e,this.#r.get(e)):!1}peek(e){if(this.#t.has(e))return this.#a(e,this.#t);if(this.#r.has(e))return this.#a(e,this.#r)}delete(e){let t=this.#t.delete(e);return t&&this.#e--,this.#r.delete(e)||t}clear(){this.#t.clear(),this.#r.clear(),this.#e=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this.#h()],n=t.length-e;n<0?(this.#t=new Map(t),this.#r=new Map,this.#e=t.length):(n>0&&this.#s(t.slice(0,n)),this.#r=new Map(t.slice(n)),this.#t=new Map,this.#e=0),this.#n=e}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.#t){let[t,n]=e;this.#i(t,n)===!1&&(yield[t,n.value])}for(let e of this.#r){let[t,n]=e;this.#t.has(t)||this.#i(t,n)===!1&&(yield[t,n.value])}}*entriesDescending(){let e=[...this.#t];for(let t=e.length-1;t>=0;--t){let n=e[t],[i,o]=n;this.#i(i,o)===!1&&(yield[i,o.value])}e=[...this.#r];for(let t=e.length-1;t>=0;--t){let n=e[t],[i,o]=n;this.#t.has(i)||this.#i(i,o)===!1&&(yield[i,o.value])}}*entriesAscending(){for(let[e,t]of this.#h())yield[e,t.value]}get size(){if(!this.#e)return this.#r.size;let e=0;for(let t of this.#r.keys())this.#t.has(t)||e++;return Math.min(this.#e+e,this.#n)}get maxSize(){return this.#n}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,i]of this.entriesAscending())e.call(t,i,n,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};var mi=class extends Error{static name="InvalidRangeError";constructor(e="Invalid range request"){super(e),this.name="InvalidRangeError"}},X6=class extends Error{static name="NoContentError";constructor(e="No content found"){super(e),this.name="NoContentError"}},Y6=class extends Error{static name="SubdomainNotSupportedError";constructor(e="Subdomain not supported"){super(e),this.name="SubdomainNotSupportedError"}};function cL(r,e){if(r==null)return;if(r instanceof Headers)return r.get(e)??void 0;if(Array.isArray(r))return r.find(([i])=>i.toLowerCase()===e.toLowerCase())?.[1];let t=Object.keys(r).find(n=>n.toLowerCase()===e.toLowerCase());if(t!=null)return r[t]}function lL(r,e,t){if((r??0)>(e??1/0))throw new mi("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(e??0)>=(t??1/0))throw new mi("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 mi("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new mi("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 uL({ttl:r,protocol:e,response:t}){if(t.headers.has("cache-control"))return;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 fL({byteStart:r,byteEnd:e,byteSize:t}){let n=t??"*";if((e??0)>=(t??1/0))throw new mi("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(t??1/0))throw new mi("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 i=t-1;return`bytes ${i-e+1}-${i}/${t}`}return r==null&&e==null?`bytes */${n}`:`bytes ${r}-${e}/${n}`}function Q6(r,e){e!=null&&r.headers.set("X-Ipfs-Roots",mE(e))}function mE(r){return r.map(e=>e.toV1().toString()).join(",")}function GY(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 XY(r){let e=r.match(/^bytes=(?<start>\d+)?-(?<end>\d+)?$/);if(e?.groups==null)throw new mi("Invalid range request");let{start:t,end:n}=e.groups;return{start:t,end:n}}var Z6=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=cL(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:i}=XY(this.rangeRequestHeader);this.requestRangeStart=n!=null?parseInt(n):null,this.requestRangeEnd=i!=null?parseInt(i):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??GY(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,i=this.byteSize;return t!=null||n!=null?(this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",t,n,i),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;return this.byteEnd!=null&&this.byteStart!=null?n=this.byteEnd-this.byteStart+1:n=void 0,this.log.trace("slicing body with offset=%o and length=%o",t,n),typeof e=="string"||e instanceof Blob||e instanceof ArrayBuffer||e instanceof Uint8Array?e.slice(t,n!==void 0?t+n:void 0):e}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.byteEnd-this.byteStart+1:this.byteEnd!=null?this.byteEnd+1:this.byteSize}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}=lL(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 mi("Invalid range request");return fL({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};var Lt=class{codes=[];pluginOptions;_log;get log(){return this._log==null&&(this._log=this.pluginOptions.logger.forComponent(this.id)),this._log}constructor(e){this.pluginOptions=e}};var J6=class extends Lt{id="byte-range-context-plugin";canHandle(e){return e.byteRangeContext==null}async handle(e){return e.byteRangeContext=new Z6(this.pluginOptions.logger,e.options?.headers),e.modified++,null}};var wE=ht(e5(),1);var xE=40;function bE(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=wE.default.decode(r);return e.seek(wE.default.decode.bytes),t}function vE(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 bc={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},Pm={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":bc.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(bc.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Pm["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let i=e;i<r.length;i++){let o=r[i];if(o=Pm["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:bc.Int,CarV1HeaderOrV2Pragma:r=>{if(bc.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let i=0;i<e.length;i++){let[o,s]=e[i];switch(o){case"roots":{let a=Pm["CarV1HeaderOrV2Pragma > roots (anon)"](r[o]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Pm.Int(r[o]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},Rm={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":bc.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(bc.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Rm["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let i=e;i<r.length;i++){let o=r[i];if(o=Rm["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:bc.Int,CarV1HeaderOrV2Pragma:r=>{if(bc.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let i=0;i<e.length;i++){let[o,s]=e[i];switch(o){case"roots":{let a=Rm["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Rm.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},EE={toTyped:Pm.CarV1HeaderOrV2Pragma,toRepresentation:Rm.CarV1HeaderOrV2Pragma};var PGe=g7();var dQ=ht(e5(),1);var BGe=[new Q(I.map,2),new Q(I.string,"version"),new Q(I.uint,1),new Q(I.string,"roots")],LGe=new Q(I.tag,42);async function SE(r,e){let t=bE(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),i=Pa(n);if(EE.toTyped(i)===void 0)throw new Error("Invalid CAR header format");if(i.version!==1&&i.version!==2||e!==void 0&&i.version!==e)throw new Error(`Invalid CAR version: ${i.version}${e!==void 0?` (expected ${e})`:""}`);if(i.version===1){if(!Array.isArray(i.roots))throw new Error("Invalid CAR header format");return i}if(i.roots!==void 0)throw new Error("Invalid CAR header format");let o=vE(await r.exactly(xE,!0));r.seek(o.dataOffset-r.pos);let s=await SE(r,1);return Object.assign(s,o)}function Dm(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 i=r.subarray(e,e+t);return n&&(e+=t),i},seek(t){e+=t},get pos(){return e}}}var AE=ht(e5(),1),SL=1;function _E(r){let e=Tf({version:SL,roots:r}),t=AE.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function AL(r){return{async setRoots(e){let t=_E(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(AE.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 SL}}}function t5(){}function _L(){let r=[],e=null,t=t5,n=!1,i=null,o=t5,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=t5,l()}})),e),a={write(l){r.push(l);let u=s();return o(),u},async end(){n=!0;let l=s();o(),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}):(i||(i=new Promise(u=>{o=()=>(i=null,o=t5,u(c.next()))})),i)}};return{writer:a,iterator:c}}var Nm=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=W.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=gQ(e);let{encoder:t,iterator:n}=IL(),i=new r(e,t),o=new r5(n);return{writer:i,out:o}}static createAppender(){let{encoder:e,iterator:t}=IL();e.setRoots=()=>Promise.resolve();let n=new r([],e),i=new r5(t);return{writer:n,out:i}}static async updateRootsInBytes(e,t){let n=Dm(e);await SE(n);let i=_E(t);if(Number(n.pos)!==i.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${i.length} bytes)`);return e.set(i,0),e}},r5=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 IL(){let r=_L(),{writer:e,iterator:t}=r;return{encoder:AL(e),iterator:t}}function gQ(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=W.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=W.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var n5=class{async*export(e,t){for(let[,n]of t.links())yield n}};var i5=class{target;constructor(e){this.target=e}isTarget(e){return this.target.equals(e)}async*traverse(e,t){for(let[,n]of t.links())yield n}};var o5=class{components;log;constructor(e,t){this.components=e,this.log=e.logger.forComponent("helia:car")}async import(e,t){await Sr(this.components.blockstore.putMany(qt(e.blocks(),({cid:n,bytes:i})=>({cid:n,block:i})),t))}async export(e,t,n){let i=Ee(),o=Array.isArray(e)?e:[e],s={currentPath:[],pathsToTarget:null},a=n?.traversal,c=n?.exporter??new n5,l=new Pn({concurrency:1}),u=!1;l.on("idle",()=>{if(u)i.resolve();else if(!u&&s.pathsToTarget?.length===o.length){this.log.trace("starting export of blocks to the car file"),u=!0;for(let f of s.pathsToTarget){let h=f.length-1,d=f[h];f.slice(0,-1).forEach(m=>{l.add(async()=>{await this.#t({cid:m,queue:l,writer:t,strategy:c,options:n,recursive:!1})}).catch(g=>{this.log.error("error during queue operation - %e",g)})}),l.add(async()=>{await this.#t({cid:d,queue:l,writer:t,strategy:c,options:n})}).catch(m=>{this.log.error("error during queue operation - %e",m)})}}else this.log.trace("no paths to target, skipping export"),i.reject(new Error("Could not traverse to target CID(s)"))}),l.on("error",f=>{l.clear(),i.reject(f)});for(let f of o)l.add(async()=>{this.log.trace("traversing dag from %c",f),await this.#e({cid:f,queue:l,strategy:a??new i5(f),traversalContext:s,parentPath:[],options:n})}).catch(h=>{this.log.error("error during queue operation - %e",h)});try{await i.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:i}=Nm.create(e);this.export(e,n,t).catch(o=>{this.log.error("error during streaming export - %e",o)});for await(let o of i)yield o}async#e({cid:e,queue:t,strategy:n,traversalContext:i,parentPath:o,options:s}){let a=[...o,e];if(n.isTarget(e)){i.pathsToTarget=i.pathsToTarget??[],i.pathsToTarget.push([...a]),this.log.trace("found path to target %c",e);return}let c=await this.components.getCodec(e.code),l=await this.components.blockstore.get(e,s),u=bp({bytes:l,cid:e,codec:c});for await(let f of n.traverse(e,u))t.add(async()=>{await this.#e({cid:f,queue:t,strategy:n,traversalContext:i,parentPath:a??[],options:s})}).catch(h=>{this.log.error("error during traversal queue operation - %e",h)})}async#t({cid:e,queue:t,writer:n,strategy:i,options:o,recursive:s=!0}){if(o?.blockFilter?.has(e.multihash.bytes)===!0)return;let a=await this.components.getCodec(e.code),c=await this.components.blockstore.get(e,o);if(o?.blockFilter?.add(e.multihash.bytes),await n.put({cid:e,bytes:c}),s){let l=bp({bytes:c,cid:e,codec:a});for await(let u of i.export(e,l))t.add(async()=>{await this.#t({cid:u,queue:t,writer:n,strategy:i,options:o})}).catch(f=>{this.log.error("error during export queue operation - %e",f)})}}};var Om=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 Ao;(function(r){let e;(function(i){i.Raw="Raw",i.Directory="Directory",i.File="File",i.Metadata="Metadata",i.Symlink="Symlink",i.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(i){i[i.Raw=0]="Raw",i[i.Directory=1]="Directory",i[i.File=2]="File",i[i.Metadata=3]="Metadata",i[i.Symlink=4]="Symlink",i[i.HAMTShard=5]="HAMTShard"})(t||(t={})),function(i){i.codec=()=>At(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=ve((i,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),r.DataType.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),i.filesize!=null&&(o.uint32(24),o.uint64(i.filesize)),i.blocksizes!=null)for(let a of i.blocksizes)o.uint32(32),o.uint64(a);i.hashType!=null&&(o.uint32(40),o.uint64(i.hashType)),i.fanout!=null&&(o.uint32(48),o.uint64(i.fanout)),i.mode!=null&&(o.uint32(56),o.uint32(i.mode)),i.mtime!=null&&(o.uint32(66),s5.codec().encode(i.mtime,o)),s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={blocksizes:[]},a=o==null?i.len:i.pos+o;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:s.Type=r.DataType.codec().decode(i);break;case 2:s.Data=i.bytes();break;case 3:s.filesize=i.uint64();break;case 4:s.blocksizes.push(i.uint64());break;case 5:s.hashType=i.uint64();break;case 6:s.fanout=i.uint64();break;case 7:s.mode=i.uint32();break;case 8:s.mtime=s5.codec().decode(i,i.uint32());break;default:i.skipType(c&7);break}}return s})),n),r.encode=i=>be(i,r.codec()),r.decode=i=>xe(i,r.codec())})(Ao||(Ao={}));var s5;(function(r){let e;r.codec=()=>(e==null&&(e=ve((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let s=t.uint32();switch(s>>>3){case 1:i.Seconds=t.int64();break;case 2:i.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>be(t,r.codec()),r.decode=t=>xe(t,r.codec())})(s5||(s5={}));var TL;(function(r){let e;r.codec=()=>(e==null&&(e=ve((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let s=t.uint32();switch(s>>>3){case 1:i.MimeType=t.string();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>be(t,r.codec()),r.decode=t=>xe(t,r.codec())})(TL||(TL={}));var CL={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},yQ=["directory","hamt-sharded-directory"],kL=parseInt("0644",8),PL=parseInt("0755",8),Te=class r{static unmarshal(e){let t=Ao.decode(e),n=new r({type:CL[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:i,hashType:o,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(CL).includes(t))throw new Om("Type: "+t+" is not valid");this.type=t??"file",this.data=n,this.hashType=o,this.fanout=s,this.blockSizes=i??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?PL:kL:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return yQ.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=Ao.DataType.Raw;break;case"directory":e=Ao.DataType.Directory;break;case"file":e=Ao.DataType.File;break;case"metadata":e=Ao.DataType.Metadata;break;case"symlink":e=Ao.DataType.Symlink;break;case"hamt-sharded-directory":e=Ao.DataType.HAMTShard;break;default:throw new Om(`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===kL&&!this.isDirectory()&&(n=void 0),n===PL&&this.isDirectory()&&(n=void 0));let i;return this.mtime!=null&&(i={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Ao.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:i})}};function RL(r,e={}){return new o5(r,e)}function Bm(r,e={}){let t=sd(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(i){try{let{value:o,done:s}=await t.next();if(this._cancelled)return;if(s===!0){i.close();return}i.enqueue(o)}catch(o){i.error(o)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}function IE(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function ea(r,e){IE(r,"type",e)}function ta(r,e){IE(r,"url",e)}function DL(r){IE(r,"redirected",!0)}function wQ(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&DL(n),ea(n,"basic"),ta(n,r),n}function rh(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return ea(n,"basic"),ta(n,r),n}function c5(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),ea(n,"basic"),ta(n,r),n}function ra(r,e,t){let n=new Response(e,{...t??{},status:406,statusText:"Not Acceptable"});return ea(n,"basic"),ta(n,r),n}function l5(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return ea(n,"basic"),ta(n,r),n}function xQ(r){return Array.isArray(r)&&r.every(e=>e instanceof Error)}function Lm(r,e,t){let n,i;xQ(e)?(n=e[e.length-1].stack,i=e.map(a=>({message:a.message,stack:a.stack??""}))):e instanceof Error&&(n=e.stack,i=[{message:e.message,stack:e.stack??""}]);let o=JSON.stringify({stack:n,errors:i}),s=new Response(o,{status:400,statusText:"Bad Request",...t??{},headers:{...t?.headers??{},"Content-Type":"application/json"}});return ea(s,"basic"),ta(s,r),s}function Mm(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return ea(n,"basic"),ta(n,r),n}function cn(r,e,{byteRangeContext:t,log:n},i){if(!t.isRangeRequest)return wQ(r,e,i);if(!t.isValidRangeRequest)return a5(r,e,i);let o;try{o=new Response(e,{...i??{},status:206,statusText:"Partial Content",headers:{...i?.headers??{},"content-range":t.contentRangeHeaderValue}})}catch(s){return n?.error("failed to create range response",s),a5(r,e,i)}return i?.redirected===!0&&DL(o),ea(o,"basic"),ta(o,r),o}function a5(r,e,t){let n=new Response(e,{...t??{},status:416,statusText:"Requested Range Not Satisfiable"});return ea(n,"basic"),ta(n,r),n}function bQ({cid:r,ipfsPath:e,query:t}){return t.filename!=null?t.filename:`${e.replace(/\/ipfs\//,"").replace(/\/ipns\//,"").replace(/\//g,"_")}.car`}var u5=class extends Lt{id="car-plugin";canHandle(e){return this.log("checking if we can handle %c with accept %s",e.cid,e.accept),e.byteRangeContext==null?!1:e.accept?.startsWith("application/vnd.ipld.car")===!0||e.query.format==="car"}async handle(e){let{options:t,pathDetails:n,cid:i}=e,{getBlockstore:o,helia:s}=this.pluginOptions;e.reqFormat="car",e.query.download=!0,e.query.filename=bQ(e);let a=o(i,e.resource,t?.session??!0,t),c=RL({blockstore:a,getCodec:s.getCodec,logger:s.logger}),l=Bm(c.stream(n?.terminalElement.cid??i,t));e.byteRangeContext.setBody(l);let u=cn(e.resource,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:this.log});return u.headers.set("content-type","application/vnd.ipld.car; version=1"),u}};function NL(r){let e=bn(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(vp(e))}var _o=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},gi=class extends _o{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}},Xn=class extends _o{constructor(e="invalid PBNode"){super(e,"InvalidPBNodeError","ERR_INVALID_PB_NODE")}},vc=class extends _o{constructor(e="unknown error"){super(e,"InvalidPBNodeError","ERR_UNKNOWN_ERROR")}},Um=class extends _o{constructor(e="path already exists"){super(e,"AlreadyExistsError","ERR_ALREADY_EXISTS")}},nh=class extends _o{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}},ih=class extends _o{constructor(e="no content"){super(e,"NoContentError","ERR_NO_CONTENT")}},f5=class extends _o{constructor(e="not a file"){super(e,"NotAFileError","ERR_NOT_A_FILE")}},Ec=class extends _o{constructor(e="not a directory"){super(e,"NotADirectoryError","ERR_NOT_A_DIRECTORY")}},br=class extends _o{constructor(e="invalid parameters"){super(e,"InvalidParametersError","ERR_INVALID_PARAMETERS")}};function vQ(r){return r[Symbol.asyncIterator]!=null}function EQ(r){if(vQ(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 Io=EQ;var d5=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},qi=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},h5=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},vr=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},p5=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},m5=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},g5=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)}},Du=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 oh(r,e,t,n,i,o,s){let a=r,c=i;for(;o.length>0;){let l=o[0];if(l in a){o.shift(),c=`${c}/${l}`;let u=W.asCID(a[l]);if(u!=null)return{entry:{type:"object",name:n,path:i,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:u,name:l,path:c,toResolve:o}};a=a[l]}else throw new g5(`No property named ${l} found in node ${t}`)}return{entry:{type:"object",name:n,path:i,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}}}}var SQ=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=Pa(c);return oh(l,c,r,e,t,n,o)},OL=SQ;var AQ=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=kf(c);return oh(l,c,r,e,t,n,o)},BL=AQ;function _Q(r,e,t,n){let i=BigInt(r.length),o=BigInt(e+i);return t>=o||n<e?new Uint8Array(0):(n>=e&&n<o&&(r=r.subarray(0,Number(n-e))),t>=e&&t<o&&(r=r.subarray(Number(t-e))),r)}var Nu=_Q;var IQ=(r,e=0,t=r)=>{let n=BigInt(r),i=BigInt(e??0),o=BigInt(t);if(o!==n&&(o=i+o),o>n&&(o=n),i<0n)throw new Du("Offset must be greater than or equal to 0");if(i>n)throw new Du("Offset must be less than the file size");if(o<0n)throw new Du("Length must be greater than or equal to 0");if(o>n)throw new Du("Length must be less than the file size");return{start:i,end:o}},sh=IQ;var TQ=r=>{async function*e(t={}){let{start:n,end:i}=sh(r.length,t.offset,t.length),o=Nu(r,0n,n,i);t.onProgress?.(new X("unixfs:exporter:progress:identity",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield o}return e},CQ=async(r,e,t,n,i,o,s,a)=>{if(n.length>0)throw new qi(`No link named ${t} found in raw node ${r}`);let c=Fe(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:TQ(c.digest),depth:o,size:BigInt(c.digest.length),node:c.digest}}},LL=CQ;var kQ=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=V8(c);return oh(l,c,r,e,t,n,o)},ML=kQ;var PQ=r=>{async function*e(t={}){let{start:n,end:i}=sh(r.length,t.offset,t.length),o=Nu(r,0n,n,i);t.onProgress?.(new X("unixfs:exporter:progress:raw",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield o}return e},RQ=async(r,e,t,n,i,o,s,a)=>{if(n.length>0)throw new qi(`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:PQ(c),depth:o,size:BigInt(c.length),node:c}}},UL=RQ;var w5=ht(HL(),1);function DQ(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 _Ye=Lc({name:"murmur3-32",code:35,encode:r=>DQ(w5.default.x86.hash32(r))}),Ou=Lc({name:"murmur3-128",code:34,encode:r=>Nc.fromHex(w5.default.x64.hash128(r))}),IYe=Lc({name:"murmur3-x64-64",code:34,encode:r=>Nc.fromHex(w5.default.x64.hash128(r)).subarray(0,8)});var KL=ht(x5(),1);var yi=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 KL.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((i,o,s)=>(o!=null&&(o instanceof r?i.push(o.serialize(e,t)):i.push(e(o,s))),i),n))}async asyncTransform(e,t){return qL(this,e,t)}toJSON(){return this.serialize(MQ,UQ)}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"?R(e):e),n=await t.take(this._options.bits),i=this._children.get(n);return i instanceof r?i._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:i}}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 i=await n._findPlace(t.existingChild.hash);return i.bucket._putAt(i,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(LQ);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 LQ(r){return!!r}function MQ(r,e){return r.key}function UQ(r){return r}async function qL(r,e,t){let n=[];for(let i of r._children.compactArray())if(i instanceof yi)await qL(i,e,t);else{let o=await e(i);n.push({bitField:r._children.bitField(),children:o})}return t(n)}var FQ=[255,254,252,248,240,224,192,128],$Q=[1,3,7,15,31,63,127,255],b5=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 i=this._value[this._currentBytePos],o=this._currentBitPos+1,s=Math.min(o,t),a=HQ(i,o-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 HQ(r,e,t){let n=VQ(e,t);return(r&n)>>>e}function VQ(r,e){return FQ[r]&$Q[Math.min(e+r-1,7)]}function jL(r){function e(t){return t instanceof v5?t:new v5(t,r)}return e}var v5=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 i=this._buffers[this._currentBufferIndex],o=Math.min(i.availableBits(),t),s=i.take(o);n=(n<<o)+s,t-=o,this._availableBits-=o,i.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?Ve([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new b5(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function ah(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:jL(r.hashFn)};return new yi(e)}var zQ=async function(r){return(await Ou.encode(r)).slice(0,8).reverse()},KQ=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async i=>{if(i.Name==null)throw new Error("Unexpected Link without a Name");if(i.Name.length===n){let o=parseInt(i.Name,16);e._putObjectAt(o,new yi({hash:t._options.hash,bits:t._options.bits},e,o));return}await t.put(i.Name.substring(2),!0)}))},WL=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),qQ=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},GL=async(r,e,t,n,i)=>{if(n==null){if(r.Data==null)throw new vr("no data in PBNode");let f;try{f=Te.unmarshal(r.Data)}catch(d){throw new vr(d.message)}if(f.type!=="hamt-sharded-directory")throw new vr("not a HAMT");if(f.fanout==null)throw new vr("missing fanout");let h=ah({hashFn:zQ,bits:Math.log2(Number(f.fanout))});n={rootBucket:h,hamtDepth:1,lastBucket:h}}let o=(n.lastBucket.tableSize()-1).toString(16).length;await KQ(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=WL(s.pos,o),c=qQ(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=WL(n.lastBucket._posAtParent,o));let l=r.Links.find(f=>{if(f.Name==null)return!1;let h=f.Name.substring(0,o),d=f.Name.substring(o);return!(h!==a||d!==""&&d!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(o)===e)return l.Hash;n.hamtDepth++;let u=await t.get(l.Hash,i);return r=nr(u),GL(r,e,t,n,i)},XL=GL;var jQ=(r,e,t,n,i,o,s)=>{async function*a(c={}){let l=c.offset??0,u=c.length??e.Links.length,f=e.Links.slice(l,u);c.onProgress?.(new X("unixfs:exporter:walk:directory",{cid:r})),yield*pt(f,h=>qt(h,d=>async()=>{let m=d.Name??"",g=`${n}/${m}`;return(await i(d.Hash,m,g,[],o+1,s,c)).entry}),h=>An(h,{ordered:!0,concurrency:c.blockReadConcurrency}),h=>ai(h,d=>d!=null))}return a},YL=jQ;async function QL(r,e,t,n,i,o,s){if(e instanceof Uint8Array){let l=Nu(e,n,i,o);t.push(l);return}if(e.Data==null)throw new vr("no data in PBNode");let a;try{a=Te.unmarshal(e.Data)}catch(l){throw new vr(l.message)}if(a.data!=null){let l=a.data,u=Nu(l,n,i,o);t.push(u),n+=BigInt(u.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new vr("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let u=e.Links[l],f=n,h=f+a.blockSizes[l];if((i>=f&&i<h||o>=f&&o<=h||i<f&&o>h)&&c.push({link:u,blockStart:n}),n=h,n>o)break}await pt(c,l=>qt(l,u=>async()=>{let f=await r.get(u.link.Hash,s);return{...u,block:f}}),l=>An(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:u,block:f,blockStart:h}of l){let d;switch(u.Hash.code){case st:d=nr(f);break;case Et:d=f;break;default:t.end(new vr(`Unsupported codec: ${u.Hash.code}`));return}let m=new Pn({concurrency:1});m.on("error",g=>{t.end(g)}),m.add(async()=>{s.onProgress?.(new X("unixfs:exporter:walk:file",{cid:u.Hash})),await QL(r,d,t,h,i,o,s)}),await m.onIdle()}}),n>=o&&t.end()}var WQ=(r,e,t,n,i,o,s)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:u,end:f}=sh(l,c.offset,c.length);if(f===0n)return;let h=0n,d=f-u,m=cr();c.onProgress?.(new X("unixfs:exporter:walk:file",{cid:r})),QL(s,e,m,0n,u,f,c).catch(g=>{m.end(g)});for await(let g of m)if(g!=null){if(h+=BigInt(g.byteLength),h>d)throw m.end(),new p5("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");h===d&&m.end(),c.onProgress?.(new X("unixfs:exporter:progress:unixfs:file",{bytesRead:h,totalBytes:d,fileSize:l})),yield g}if(h<d)throw new m5("Traversed entire DAG but did not read enough bytes")}return a},TE=WQ;var GQ=(r,e,t,n,i,o,s)=>{function a(c={}){return c.onProgress?.(new X("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),ZL(e,n,i,o,s,c)}return a};async function*ZL(r,e,t,n,i,o){let s=r.Links;if(r.Data==null)throw new vr("no data in PBNode");let a;try{a=Te.unmarshal(r.Data)}catch(u){throw new vr(u.message)}if(a.fanout==null)throw new vr("missing fanout");let c=(a.fanout-1n).toString(16).length,l=pt(s,u=>qt(u,f=>async()=>{let h=f.Name!=null?f.Name.substring(c):null;if(h!=null&&h!==""){let d=await t(f.Hash,h,`${e}/${h}`,[],n+1,i,o);return{entries:d.entry==null?[]:[d.entry]}}else{let d=await i.get(f.Hash,o);return r=nr(d),o.onProgress?.(new X("unixfs:exporter:walk:hamt-sharded-directory",{cid:f.Hash})),{entries:ZL(r,e,t,n,i,o)}}}),u=>An(u,{ordered:!0,concurrency:o.blockReadConcurrency}));for await(let{entries:u}of l)yield*u}var JL=GQ;var XQ=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,YQ={raw:TE,file:TE,directory:YL,"hamt-sharded-directory":JL,metadata:(r,e,t,n,i,o,s)=>()=>[],symlink:(r,e,t,n,i,o,s)=>()=>[]},QQ=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=nr(c),u,f;if(e==null&&(e=r.toString()),l.Data==null)throw new vr("no data in PBNode");try{u=Te.unmarshal(l.Data)}catch(d){throw new vr(d.message)}if(t==null&&(t=e),n.length>0){let d;if(u?.type==="hamt-sharded-directory"?d=await XL(l,n[0],s):d=XQ(l,n[0]),d==null)throw new qi("file does not exist");let m=n.shift(),g=`${t}/${m}`;f={cid:d,toResolve:n,name:m??"",path:g}}let h=YQ[u.type](r,l,u,t,i,o,s);if(h==null)throw new qi("could not find content exporter");return u.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:h,unixfs:u,depth:o,node:l,size:u.fileSize()},next:f}:{entry:{type:"file",name:e,path:t,cid:r,content:h,unixfs:u,depth:o,node:l,size:u.fileSize()},next:f}},eM=QQ;var ZQ={[st]:eM,[Et]:UL,[Rn]:OL,[so]:BL,[ur.code]:LL,[Bo]:ML},tM=async(r,e,t,n,i,o,s)=>{let a=ZQ[r.code];if(a==null)throw new h5(`No resolver for code ${r.code}`);return a(r,e,t,n,tM,i,o,s)},rM=tM;var JQ=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),eZ=r=>{if(r instanceof Uint8Array)return{cid:W.decode(r),toResolve:[]};let e=W.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=JQ(r);return{cid:W.parse(t[0]),toResolve:t.slice(1)}}throw new d5(`Unknown path type ${r}`)};async function*$m(r,e,t={}){let{cid:n,toResolve:i}=eZ(r),o=n.toString(),s=o,a=i.length;for(;;){let c=await rM(n,o,s,i,a,e,t);if(c.entry==null&&c.next==null)throw new qi(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;i=c.next.toResolve,n=c.next.cid,o=c.next.name,s=c.next.path}}async function gr(r,e,t={}){let n=await Io($m(r,e,t));if(n==null)throw new qi(`Could not resolve ${r}`);return n}async function*ch(r,e,t={}){let n=await gr(r,e,t);if(n==null)return;if(yield n,n.type==="directory")for await(let o of i(n,t))yield o;async function*i(o,s){for await(let a of o.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*i(a,s))}}async function tZ(r,e,t){let n=[],i;for await(let o of $m(e,r,t))n.push(o.cid),i=o;if(i==null)throw new nh("No terminal element found");return{ipfsRoots:n,terminalElement:i}}function CE(r){return r.type==="object"}async function nM({cid:r,path:e,resource:t,options:n,blockstore:i,log:o}){try{return await tZ(i,`${r.toString()}/${e}`,n)}catch(s){if(n?.signal?.aborted)throw new ft(n?.signal?.reason);return["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(s.code)?l5(t):(o.error("error walking path %s",e,s),rh(t,"Error walking path"))}}var E5=class extends Lt{id="dag-cbor-plugin";codes=[Rn];canHandle({cid:e,accept:t,pathDetails:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),n==null||!CE(n.terminalElement)||e.code!==Rn||i==null?!1:CE(n.terminalElement)}async handle(e){let{cid:t,path:n,resource:i,accept:o,pathDetails:s}=e;this.log.trace("fetching %c/%s",t,n);let a=s.ipfsRoots,l=s.terminalElement.node,u;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")u=l;else if(o==="application/vnd.ipld.dag-json")try{let d=Pa(l);u=U2(d)}catch(d){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",d),ra(i)}else try{u=NL(l)}catch(d){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',d),ra(i);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",d),u=l}e.byteRangeContext.setBody(u);let f=cn(i,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:this.log}),h=o??(u instanceof Uint8Array?"application/octet-stream":"application/json");return f.headers.set("content-type",h),Q6(f,a),f}};function rZ(r){return r[Symbol.asyncIterator]!=null}function nZ(r,e=1){return e=Number(e),rZ(r)?async function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}():function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)}()}var S5=nZ;async function*Hm(r,e=1){for await(let t of S5(r,e)){let n=t.map(async i=>i().then(o=>({ok:!0,value:o}),o=>({ok:!1,err:o})));for(let i=0;i<n.length;i++){let o=await n[i];if(o.ok)yield o.value;else throw o.err}}}var iZ=262144,Vm=(r={})=>{let e=r.chunkSize??iZ;return async function*(n){let i=new ge,o=0,s=!1;for await(let a of n)for(i.append(a),o+=a.length;o>=e;)if(yield i.slice(0,e),s=!0,e===i.length)i=new ge,o=0;else{let c=new ge;c.append(i.sublist(e)),i=c,o-=e}(!s||o>0)&&(yield i.subarray(0,o))}};var To=async(r,e,t)=>{t.codec==null&&(t.codec=ir);let n=await $e.digest(r),i=W.create(t.cidVersion,t.codec.code,n);return await e.put(i,r,t),i};function iM(r){return async function*(t,n){let i=0n;for await(let o of t.content)yield async()=>{let s,a={codec:ir,cidVersion:r.cidVersion,onProgress:r.onProgress};r.rawLeaves?(a.codec=Tn,a.cidVersion=1):(s=new Te({type:r.leafType,data:o}),o=Je({Data:s.marshal(),Links:[]}));let c=await To(o,n,a);return i+=BigInt(o.byteLength),r.onProgress?.(new X("unixfs:importer:progress:file:write",{bytesWritten:i,cid:c,path:t.path})),{cid:c,unixfs:s,size:BigInt(o.length),block:o}}}}var A5=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};var Sc=class r extends Error{static name="InvalidContentError";static code="ERR_INVALID_CONTENT";name=r.name;code=r.code;constructor(e="Invalid content"){super(e)}};var oM=async(r,e,t)=>{let n=new Te({type:"directory",mtime:r.mtime,mode:r.mode}),i=Je(Wt({Data:n.marshal()})),o=await To(i,e,t),s=r.path;return{cid:o,path:s,unixfs:n,size:BigInt(i.length),originalPath:r.originalPath,block:i}};async function*oZ(r,e,t){let n=-1,i;for await(let o of Hm(t.bufferImporter(r,e),t.blockWriteConcurrency)){if(n++,n===0){i={...o,single:!0};continue}else n===1&&i!=null&&(yield{...i,block:void 0,single:void 0},i=void 0);yield{...o,block:void 0}}i!=null&&(yield i)}function sM(r){return r.single===!0}var sZ=(r,e,t)=>async function(i){if(i.length===1&&sM(i[0])&&t.reduceSingleLeafToSelf){let u=i[0],f=u.block;return sM(u)&&(r.mtime!==void 0||r.mode!==void 0)&&(u.unixfs=new Te({type:"file",mtime:r.mtime,mode:r.mode,data:u.block}),f={Data:u.unixfs.marshal(),Links:[]},u.block=Je(Wt(f)),u.cid=await To(u.block,e,{...t,cidVersion:t.cidVersion}),u.size=BigInt(u.block.length)),t.onProgress?.(new X("unixfs:importer:progress:file:layout",{cid:u.cid,path:u.originalPath})),{cid:u.cid,path:r.path,unixfs:u.unixfs,size:u.size,originalPath:u.originalPath}}let o=new Te({type:"file",mtime:r.mtime,mode:r.mode}),s=i.filter(u=>u.cid.code===Et&&u.size>0||u.unixfs!=null&&u.unixfs.data==null&&u.unixfs.fileSize()>0n?!0:!!u.unixfs?.data?.length).map(u=>u.cid.code===Et?(o.addBlockSize(u.size),{Name:"",Tsize:Number(u.size),Hash:u.cid}):(u.unixfs?.data==null?o.addBlockSize(u.unixfs?.fileSize()??0n):o.addBlockSize(BigInt(u.unixfs.data.length)),{Name:"",Tsize:Number(u.size),Hash:u.cid})),a={Data:o.marshal(),Links:s},c=Je(Wt(a)),l=await To(c,e,t);return t.onProgress?.(new X("unixfs:importer:progress:file:layout",{cid:l,path:r.originalPath})),{cid:l,path:r.path,unixfs:o,size:BigInt(c.length+a.Links.reduce((u,f)=>u+(f.Tsize??0),0)),originalPath:r.originalPath,block:c}},aM=async(r,e,t)=>t.layout(oZ(r,e,t),sZ(r,e,t));function aZ(r){return Symbol.iterator in r}function cZ(r){return Symbol.asyncIterator in r}function lZ(r){try{if(r instanceof Uint8Array)return async function*(){yield r}();if(aZ(r))return async function*(){yield*r}();if(cZ(r))return r}catch{throw new Sc("Content was invalid")}throw new Sc("Content was invalid")}function cM(r){return async function*(t,n){for await(let i of t){let o;if(i.path!=null&&(o=i.path,i.path=i.path.split("/").filter(s=>s!=null&&s!==".").join("/")),uZ(i)){let s={path:i.path,mtime:i.mtime,mode:i.mode,content:async function*(){let a=0n;for await(let c of r.chunker(r.chunkValidator(lZ(i.content)))){let l=BigInt(c.byteLength);a+=l,r.onProgress?.(new X("unixfs:importer:progress:file:read",{bytesRead:a,chunkSize:l,path:i.path})),yield c}}(),originalPath:o};yield async()=>aM(s,n,r)}else if(i.path!=null){let s={path:i.path,mtime:i.mtime,mode:i.mode,originalPath:o};yield async()=>oM(s,n,r)}else throw new Error("Import candidate must have content or path or both")}}}function uZ(r){return r.content!=null}var lM=()=>async function*(e){for await(let t of e){if(t.length===void 0)throw new Sc("Content was invalid");if(typeof t=="string"||t instanceof String)yield R(t.toString());else if(Array.isArray(t))yield Uint8Array.from(t);else if(t instanceof Uint8Array)yield t;else throw new Sc("Content was invalid")}};var fZ=174;function zm(r){let e=r?.maxChildrenPerNode??fZ;return async function t(n,i){let o=[];for await(let s of S5(n,e))o.push(await i(s));return o.length>1?t(o,i):o[0]}}var as=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},Km=W.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),qm=W.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var Bu=class extends as{_children;constructor(e,t){super(e,t),this._children=new Map}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,this._children.set(e,t)}async get(e){return Promise.resolve(this._children.get(e))}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}async*eachChildSeries(){for(let[e,t]of this._children.entries())yield{key:e,child:t}}estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;this.nodeSize=0;for(let[e,t]of this._children.entries())t.size!=null&&t.cid!=null&&(this.nodeSize+=e.length+(this.options.cidVersion===1?qm.bytes.byteLength:Km.bytes.byteLength));return this.nodeSize}async*flush(e){let t=[];for(let[c,l]of this._children.entries()){let u=l;if(l instanceof as)for await(let f of l.flush(e))u=f,yield f;u.size!=null&&u.cid!=null&&t.push({Name:c,Tsize:Number(u.size),Hash:u.cid})}let n=new Te({type:"directory",mtime:this.mtime,mode:this.mode}),i={Data:n.marshal(),Links:t},o=Je(Wt(i)),s=await To(o,e,this.options),a=o.length+i.Links.reduce((c,l)=>c+(l.Tsize??0),0);this.cid=s,this.size=a,yield{cid:s,unixfs:n,path:this.path,size:BigInt(a)}}};async function dZ(r){return(await Ou.encode(r)).slice(0,8).reverse()}var uM=BigInt(34),hZ=8,kE=class extends as{_bucket;constructor(e,t){super(e,t),this._bucket=ah({hashFn:dZ,bits:t.shardFanoutBits??hZ})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for await(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=hM(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of dM(this._bucket,e,this,this.options))yield{...t,path:this.path}}},fM=kE;async function*dM(r,e,t,n){let i=r._children,o=(r.tableSize()-1).toString(16).length,s=[],a=0n;for(let m=0;m<i.length;m++){let g=i.get(m);if(g==null)continue;let w=m.toString(16).toUpperCase().padStart(o,"0");if(g instanceof yi){let x;for await(let S of dM(g,e,null,n))x=S;if(x==null)throw new Error("Could not flush sharded directory, no subshard found");s.push({Name:w,Tsize:Number(x.size),Hash:x.cid}),a+=x.size}else if(pZ(g.value)){let x=g.value,S;for await(let b of x.flush(e))S=b,yield S;if(S==null)throw new Error("Did not flush dir");let E=w+g.key;s.push({Name:E,Tsize:Number(S.size),Hash:S.cid}),a+=S.size}else{let x=g.value;if(x.cid==null)continue;let S=w+g.key,E=x.size;s.push({Name:S,Tsize:Number(E),Hash:x.cid}),a+=BigInt(E??0)}}let c=Uint8Array.from(i.bitField().reverse()),l=new Te({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:uM,mtime:t?.mtime,mode:t?.mode}),u={Data:l.marshal(),Links:s},f=Je(Wt(u)),h=await To(f,e,n),d=BigInt(f.byteLength)+a;yield{cid:h,unixfs:l,size:d}}function pZ(r){return typeof r.flush=="function"}function hM(r,e,t){let n=r._children,i=(r.tableSize()-1).toString(16).length,o=[];for(let l=0;l<n.length;l++){let u=n.get(l);if(u==null)continue;let f=l.toString(16).toUpperCase().padStart(i,"0");if(u instanceof yi){let h=hM(u,null,t);o.push({Name:f,Tsize:Number(h),Hash:t.cidVersion===0?Km:qm})}else if(typeof u.value.flush=="function"){let d=u.value.nodeSize();o.push({Name:f+u.key,Tsize:Number(d),Hash:t.cidVersion===0?Km:qm})}else{let h=u.value;if(h.cid==null)continue;let d=f+u.key,m=h.size;o.push({Name:d,Tsize:Number(m),Hash:h.cid})}}let s=Uint8Array.from(n.bitField().reverse()),a=new Te({type:"hamt-sharded-directory",data:s,fanout:BigInt(r.tableSize()),hashType:uM,mtime:e?.mtime,mode:e?.mode});return Je(Wt({Data:a.marshal(),Links:o})).length}async function PE(r,e,t,n){let i=e;e instanceof Bu&&e.estimateNodeSize()>t&&(i=await mZ(e,n));let o=i.parent;if(o!=null){if(i!==e){if(r!=null&&(r.parent=i),i.parentKey==null)throw new Error("No parent key found");await o.put(i.parentKey,i)}return PE(i,o,t,n)}return i}async function mZ(r,e){let t=new fM({root:r.root,dir:!0,parent:r.parent,parentKey:r.parentKey,path:r.path,dirty:r.dirty,flat:!1,mtime:r.mtime,mode:r.mode},e);for await(let{key:n,child:i}of r.eachChildSeries())await t.put(n,i);return t}var pM=(r="")=>r.split(/(?<!\\)\//).filter(Boolean);async function gZ(r,e,t){let n=pM(r.path??""),i=n.length-1,o=e,s="";for(let a=0;a<n.length;a++){let c=n[a];s+=`${s!==""?"/":""}${c}`;let l=a===i;if(o.dirty=!0,o.cid=void 0,o.size=void 0,l)await o.put(c,r),e=await PE(null,o,t.shardSplitThresholdBytes,t);else{let u=await o.get(c);(u==null||!(u instanceof as))&&(u=new Bu({root:!1,dir:!0,parent:o,parentKey:c,path:s,dirty:!0,flat:!0,mtime:u?.unixfs?.mtime,mode:u?.unixfs?.mode},t)),await o.put(c,u),o=u}}return e}async function*mM(r,e){if(!(r instanceof as)){r.unixfs?.isDirectory()===!0&&(yield r);return}yield*r.flush(e)}function gM(r){return async function*(t,n){let i=new Bu({root:!0,dir:!0,path:"",dirty:!0,flat:!0},r),o,s=!1;for await(let a of t){if(a==null)continue;let c=`${a.originalPath??""}`.split("/")[0];c!=null&&c!==""&&(o==null?(o=c,s=!0):o!==c&&(s=!1)),i=await gZ(a,i,r),a.unixfs?.isDirectory()!==!0&&(yield a)}if(r.wrapWithDirectory||s&&i.childCount()>1)yield*mM(i,n);else for await(let a of i.eachChildSeries())a!=null&&(yield*mM(a.child,n))}}async function*Lu(r,e,t={}){let n;Symbol.asyncIterator in r||Symbol.iterator in r?n=r:n=[r];let i=t.wrapWithDirectory??!1,o=t.shardSplitThresholdBytes??262144,s=t.shardFanoutBits??8,a=t.cidVersion??1,c=t.rawLeaves??!0,l=t.leafType??"file",u=t.fileImportConcurrency??50,f=t.blockWriteConcurrency??10,h=t.reduceSingleLeafToSelf??!0,d=t.chunker??Vm(),m=t.chunkValidator??lM(),g=t.dagBuilder??cM({chunker:d,chunkValidator:m,wrapWithDirectory:i,layout:t.layout??zm(),bufferImporter:t.bufferImporter??iM({cidVersion:a,rawLeaves:c,leafType:l,onProgress:t.onProgress}),blockWriteConcurrency:f,reduceSingleLeafToSelf:h,cidVersion:a,onProgress:t.onProgress}),w=t.treeBuilder??gM({wrapWithDirectory:i,shardSplitThresholdBytes:o,shardFanoutBits:s,cidVersion:a,onProgress:t.onProgress});for await(let x of w(Hm(g(n,e),u),e))yield{cid:x.cid,path:x.path,unixfs:x.unixfs,size:x.size}}async function yM(r,e,t={}){let n=await Vf(Lu([r],e,t));if(n==null)throw new A5("Nothing imported");return n}async function wM(r,e,t={}){return yM({content:r},e,t)}async function xM(r,e,t={}){return yM({content:r},e,t)}var jm={cidVersion:1,rawLeaves:!0,layout:zm({maxChildrenPerNode:1024}),chunker:Vm({chunkSize:1048576})};async function*_5(r,e,t={}){yield*Lu(r,e,{...jm,...t})}async function bM(r,e,t={}){let{cid:n}=await wM(r,e,{...jm,...t});return n}async function vM(r,e,t={}){let{cid:n}=await xM(r,e,{...jm,...t});return n}async function EM(r,e,t={}){if(r.path==null)throw new br("path is required");if(r.content==null)throw new br("content is required");let n=await Io(_5([r],e,{...jm,...t,wrapWithDirectory:!0}));if(n==null)throw new br("Nothing imported");return n.cid}async function SM(r,e,t={}){if(r.content!=null)throw new br("Directories cannot have content, use addFile instead");let i=await(r.path==null?Vf:Io)(_5([{...r,path:r.path??"-"}],e,{...jm,...t,wrapWithDirectory:r.path!=null}));if(i==null)throw new br("Nothing imported");return i.cid}var OE=ht(x5(),1);function T5(r){function e(t){return t instanceof I5?t:new I5(t,r)}return e}var I5=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 i=this._buffers[this._currentBufferIndex],o=Math.min(i.availableBits(),t),s=i.take(o);n=(n<<o)+s,t-=o,this._availableBits-=o,i.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?Ve([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new RE(t);this._buffers.push(n),this._availableBits+=n.availableBits()}},yZ=[255,254,252,248,240,224,192,128],wZ=[1,3,7,15,31,63,127,255],RE=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 i=this._value[this._currentBytePos],o=this._currentBitPos+1,s=Math.min(o,t),a=xZ(i,o-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 xZ(r,e,t){let n=bZ(e,t);return(r&n)>>>e}function bZ(r,e){return yZ[r]&wZ[Math.min(e+r-1,7)]}var Wm=BigInt(Ou.code),Mu=8;async function lh(r){return(await Ou.encode(r)).subarray(0,8).reverse()}var IM=ht(x5(),1);var Co=async(r,e,t)=>{t.codec==null&&(t.codec=ir);let n=await $e.digest(r),i=W.create(t.cidVersion,t.codec.code,n);return await e.put(i,r,{...t,signal:t.signal}),i};var DE=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},C5=class extends DE{_bucket;constructor(e,t){super(e,t),this._bucket=ah({hashFn:lh,bits:8})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=_M(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of AM(this._bucket,e,this,this.options))yield{...t,path:this.path}}};async function*AM(r,e,t,n){let i=r._children,o=[],s=0n;for(let d=0;d<i.length;d++){let m=i.get(d);if(m==null)continue;let g=d.toString(16).toUpperCase().padStart(2,"0");if(m instanceof yi){let w;for await(let x of AM(m,e,null,n))w=x;if(w==null)throw new Error("Could not flush sharded directory, no sub-shard found");o.push({Name:g,Tsize:Number(w.size),Hash:w.cid}),s+=w.size}else if(vZ(m.value)){let w=m.value,x;for await(let E of w.flush(e))x=E,yield x;if(x==null)throw new Error("Did not flush dir");let S=g+m.key;o.push({Name:S,Tsize:Number(x.size),Hash:x.cid}),s+=x.size}else{let w=m.value;if(w.cid==null)continue;let x=g+m.key,S=w.size;o.push({Name:x,Tsize:Number(S),Hash:w.cid}),s+=BigInt(S??0)}}let a=Uint8Array.from(i.bitField().reverse()),c=new Te({type:"hamt-sharded-directory",data:a,fanout:BigInt(r.tableSize()),hashType:Wm,mtime:t?.mtime,mode:t?.mode}),l={Data:c.marshal(),Links:o},u=Je(Wt(l)),f=await Co(u,e,n),h=BigInt(u.byteLength)+s;yield{cid:f,unixfs:c,size:h}}function vZ(r){return typeof r.flush=="function"}function _M(r,e,t){let n=r._children,i=[];for(let c=0;c<n.length;c++){let l=n.get(c);if(l==null)continue;let u=c.toString(16).toUpperCase().padStart(2,"0");if(l instanceof yi){let f=_M(l,null,t);i.push({Name:u,Tsize:Number(f),Hash:t.cidVersion===0?k5:P5})}else if(typeof l.value.flush=="function"){let h=l.value.nodeSize();i.push({Name:u+l.key,Tsize:Number(h),Hash:t.cidVersion===0?k5:P5})}else{let f=l.value;if(f.cid==null)continue;let h=u+l.key,d=f.size;i.push({Name:h,Tsize:Number(d),Hash:f.cid})}}let o=Uint8Array.from(n.bitField().reverse()),s=new Te({type:"hamt-sharded-directory",data:o,fanout:BigInt(r.tableSize()),hashType:Wm,mtime:e?.mtime,mode:e?.mode});return Je(Wt({Data:s.marshal(),Links:i})).length}var k5=W.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),P5=W.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var NE=ze("helia:unixfs:commands:utils:hamt-utils"),R5=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),TM=async(r,e,t)=>{let n=new C5({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mtime:t.mtime,mode:t.mode},t);for(let o=0;o<e.length;o++)await n._bucket.put(e[o].name,{size:e[o].size,cid:e[o].cid});let i=await Io(n.flush(r));if(i==null)throw new Error("Flushing shard yielded no result");return i},D5=async(r,e,t)=>{let n=Te.unmarshal(r[0].node.Data??new Uint8Array(0)),i=BigInt(Math.pow(2,Mu));r.reverse();let o,s;for(let a=0;a<r.length;a++){let c=a===r.length-1,l=r[a],u=Uint8Array.from(l.children.bitField().reverse()),f=new Te({type:"hamt-sharded-directory",data:u,fanout:i,hashType:Wm});c&&(f.mtime=n.mtime,f.mode=n.mode),s={Data:f.marshal(),Links:l.node.Links};let h=Je(Wt(s));if(o=await Co(h,e,t),!c){let d=r[a+1];if(d==null)throw new Error("Was not operating on shard root but also had no parent?");NE("updating link in parent sub-shard with prefix %s",d.prefix),d.node.Links=d.node.Links.filter(m=>m.Name!==d.prefix),d.node.Links.push({Name:d.prefix,Hash:o,Tsize:l.node.Links.reduce((m,g)=>m+(g.Tsize??0),h.byteLength)})}}if(o==null||s==null)throw new Error("Noting persisted");return{cid:o,node:s}},N5=async(r,e,t,n)=>{let o=T5(lh)(R(e)),s=[];for(;;){let a=await t.get(r,n),c=nr(a),l=new IM.default,u=await o.take(Mu),f=R5(u);s.push({prefix:f,children:l,node:c});let h;for(let m of c.Links){let g=m.Name??"";if(g.length<2)throw new Error("Invalid HAMT - link name was too short");let w=parseInt(g.substring(0,2),16);l.set(w,!0),g.startsWith(f)&&(h=m)}if(h==null){NE("no link found with prefix %s for %s",f,e);break}let d=h.Name??"";if(d.length<2)throw new Error("Invalid HAMT - link name was too short");if(d.length===2){r=h.Hash,NE("descend into sub-shard with prefix %s",d);continue}break}return{path:s,hash:o}};async function O5(r,e,t,n){if(r.Data==null)throw new Error("DagPB node had no data");let i=Te.unmarshal(r.Data),o;if(i.type==="directory")o=EZ(r);else if(i.type==="hamt-sharded-directory")o=await CM(r,0,t,e,n);else throw new Error("Can only estimate the size of directories or shards");return o>t}function EZ(r){let e=0;for(let t of r.Links)e+=(t.Name??"").length,e+=t.Hash.version===1?P5.bytes.byteLength:k5.bytes.byteLength;return e}async function CM(r,e,t,n,i){if(e>t)return t;if(r.Data==null||!Te.unmarshal(r.Data).isDirectory())return e;for(let s of r.Links){let a=s.Name??"";if(a=a.substring(2),e+=a.length,e+=s.Hash.bytes.byteLength,s.Hash.code===st){let c=await n.get(s.Hash,i),l=nr(c);e+=await CM(l,e,t,n,i)}}return e}var cs=ze("helia:unixfs:components:utils:add-link");async function uh(r,e,t,n){if(r.node.Data==null)throw new br("Invalid parent passed to addLink");if(Te.unmarshal(r.node.Data).type==="hamt-sharded-directory")return cs("adding link to sharded directory"),_Z(r,e,t,n);cs(`adding ${e.Name} (${e.Hash}) to regular directory`);let o=await AZ(r,e,t,n);if(await O5(o.node,t,n.shardSplitThresholdBytes,n)){cs("converting directory to sharded directory");let s=await SZ(o,t);o.cid=s.cid,o.node=nr(await t.get(s.cid,n))}return o}var SZ=async(r,e)=>{if(r.node.Data==null)throw new br("Invalid parent passed to convertToShardedDirectory");let t=Te.unmarshal(r.node.Data),n=await TM(e,r.node.Links.map(i=>({name:i.Name??"",size:BigInt(i.Tsize??0),cid:i.Hash})),{mode:t.mode,mtime:t.mtime,cidVersion:r.cid.version});return cs(`converted directory to sharded directory ${n.cid}`),n},AZ=async(r,e,t,n)=>{let i=r.node.Links.filter(u=>{let f=u.Name===e.Name;if(f&&!n.allowOverwriting)throw new Um;return!f});if(i.push(e),r.node.Data==null)throw new Xn("Parent node with no data passed to addToDirectory");let o=Te.unmarshal(r.node.Data),s;if(o.mtime!=null){let u=Date.now(),f=Math.floor(u/1e3);o.mtime={secs:BigInt(f),nsecs:(u-f*1e3)*1e3},s=o.marshal()}else s=r.node.Data;r.node=Wt({Data:s,Links:i});let a=Je(r.node),c=await $e.digest(a),l=W.create(r.cid.version,st,c);return await t.put(l,a),{node:r.node,cid:l}},_Z=async(r,e,t,n)=>{let{path:i,hash:o}=await N5(r.cid,e.Name,t,n),s=i[i.length-1];if(s==null)throw new Error("Invalid HAMT, could not generate path");let a=s.prefix,c=parseInt(a,16);cs("next prefix for %s is %s",e.Name,a);let l=`${a}${e.Name}`,u=s.node.Links.find(f=>(f.Name??"").startsWith(a));if(u!=null)if(cs("link %s was present in shard",l),u.Name===l){if(!n.allowOverwriting)throw new Um;cs("overwriting %s in sub-shard",e.Name),s.node.Links=s.node.Links.filter(f=>f.Name!==l),s.node.Links.push({Name:l,Hash:e.Hash,Tsize:e.Tsize})}else{if(u.Name?.length===2)throw new Error("Existing link was sub-shard?!");{cs("prefix %s already exists, creating new sub-shard",a);let f=s.node.Links.findIndex(w=>w.Name?.startsWith(a)),h=s.node.Links.splice(f,1)[0],d=(h.Name??"").substring(2),g=T5(lh)(R(d));for(let w=0;w<i.length;w++)await g.take(Mu);for(;;){let w=await g.take(Mu),x=R5(w);h.Name=`${x}${d}`;let S=await o.take(Mu),E=R5(S);if(x===E){let T=new OE.default;T.set(S,!0),i.push({prefix:E,children:T,node:{Links:[]}});continue}let b=new OE.default;b.set(S,!0),b.set(w,!0),i.push({prefix:a,children:b,node:{Links:[h,{Name:`${E}${e.Name}`,Hash:e.Hash,Tsize:e.Tsize}]}});break}}}else cs("link %s was not present in sub-shard",l),e.Name=l,s.node.Links.push(e),s.children.set(c,!0),cs("adding %s to existing sub-shard",l);return D5(i,t,n)};async function Ac(r,e,t={}){let n=await gr(r,e,t);if(n.type!=="directory")throw new Ec(`${r.toString()} was not a UnixFS directory`);return{cid:r,node:n.node}}async function fh(r,e,t,n){let i=await gr(r,t,n);if(i.type!=="directory"&&i.type!=="file"&&i.type!=="raw")throw new gi(`${r.toString()} was not a UnixFS node`);return{Name:e,Tsize:i.node instanceof Uint8Array?i.node.byteLength:IZ(i.node),Hash:r}}function IZ(r){let e=r.Links.reduce((t,n)=>t+(n.Tsize??0),0);return Je(r).byteLength+e}var TZ=ze("helia:unixfs:components:utils:resolve");async function ls(r,e,t,n){if(e==null||e==="")return{cid:r};let i=`/ipfs/${r}${e==null?"":`/${e}`}`,o=await Ps($m(i,t,n));if(o.length===0)throw new nh("Could not find path in directory");return TZ("resolved %s to %c",e,r),{cid:o[o.length-1].cid,path:e,segments:o}}async function dh(r,e,t,n){if(e.segments==null||e.segments.length===0)return r;let i=e.segments.pop();if(i==null)throw new Error("Insufficient segments");i.cid=r,e.segments.reverse();for(let o of e.segments){let[s,a]=await Promise.all([Ac(o.cid,t,n),fh(i.cid,i.name,t,n)]);r=(await uh(s,a,t,{...n,allowOverwriting:!0,cidVersion:r.version})).cid,o.cid=r,i=o}return r}var CZ=Gt.bind({ignoreUndefined:!0}),kZ={};async function*kM(r,e,t={}){let n=CZ(kZ,t),i=await ls(r,n.path,e,n),o=await gr(i.cid,e,n);if(o.type!=="file"&&o.type!=="raw")throw new f5;if(o.content==null)throw new ih;yield*o.content(n)}var PZ=Gt.bind({ignoreUndefined:!0}),RZ=ze("helia:unixfs:chmod"),DZ={recursive:!1,shardSplitThresholdBytes:262144};async function PM(r,e,t,n={}){let i=PZ(DZ,n),o=await ls(r,i.path,t,n);if(RZ("chmod %c %d",o.cid,e),i.recursive){let h=await pt(async function*(){for await(let d of ch(o.cid,t,n)){let m,g=[];if(d.type==="raw")m=new Te({type:"file",data:d.node});else if(d.type==="file"||d.type==="directory")m=d.unixfs,g=d.node.Links;else throw new gi;m.mode=e;let w={Data:m.marshal(),Links:g};yield{path:d.path,content:w}}},d=>Lu(d,t,{...i,dagBuilder:async function*(m,g){for await(let w of m)yield async function(){let x=w.content,S=Je(x),E=await Co(S,g,{...i,cidVersion:r.version});if(x.Data==null)throw new Xn(`${E} had no data`);let b=Te.unmarshal(x.Data);return{cid:E,size:BigInt(S.length),path:w.path,unixfs:b}}}}),async d=>Io(d));if(h==null)throw new vc(`Could not chmod ${o.cid.toString()}`);return dh(h.cid,o,t,i)}let s=await t.get(o.cid,n),a,c=[];if(o.cid.code===Et)a=new Te({type:"file",data:s});else{let h=nr(s);if(h.Data==null)throw new Xn(`${o.cid.toString()} had no data`);c=h.Links,a=Te.unmarshal(h.Data)}a.mode=e;let l=Je({Data:a.marshal(),Links:c}),u=await $e.digest(l),f=W.create(o.cid.version,st,u);return await t.put(f,l),dh(f,o,t,i)}var NZ=Gt.bind({ignoreUndefined:!0}),OZ=ze("helia:unixfs:cp"),BZ={force:!1,shardSplitThresholdBytes:262144};async function RM(r,e,t,n,i={}){let o=NZ(BZ,i);if(t.includes("/"))throw new br("Name must not have slashes");let[s,a]=await Promise.all([Ac(e,n,o),fh(r,t,n,o)]);return OZ('Adding %c as "%s" to %c',r,t,e),(await uh(s,a,n,{allowOverwriting:o.force,cidVersion:e.version,...o})).cid}var LZ=Gt.bind({ignoreUndefined:!0}),MZ={};async function*DM(r,e,t={}){let n=LZ(MZ,t),i=await ls(r,n.path,e,n),o=await gr(i.cid,e);if(o.type==="file"||o.type==="raw"){yield o;return}if(o.content==null)throw new ih;if(o.type!=="directory")throw new Ec;yield*o.content({offset:t.offset,length:t.length})}var UZ=Gt.bind({ignoreUndefined:!0}),NM=ze("helia:unixfs:mkdir"),FZ={cidVersion:1,force:!1,shardSplitThresholdBytes:262144};async function OM(r,e,t,n={}){let i=UZ(FZ,n);if(e.includes("/"))throw new br("Path must not have slashes");if((await gr(r,t,n)).type!=="directory")throw new Ec(`${r.toString()} was not a UnixFS directory`);NM("creating %s",e);let a={Data:new Te({type:"directory",mode:i.mode,mtime:i.mtime}).marshal(),Links:[]},c=Je(a),l=await $e.digest(c),u=W.create(i.cidVersion,st,l);await t.put(u,c);let[f,h]=await Promise.all([Ac(r,t,i),fh(u,e,t,i)]);return NM("adding empty dir called %s to %c",e,r),(await uh(f,h,t,{...i,allowOverwriting:i.force})).cid}var L5=ze("helia:unixfs:utils:remove-link");async function BM(r,e,t,n){if(r.node.Data==null)throw new Xn("Parent node had no data");if(Te.unmarshal(r.node.Data).type==="hamt-sharded-directory"){L5(`removing ${e} from sharded directory`);let o=await HZ(r,e,t,n);return await O5(o.node,t,n.shardSplitThresholdBytes,n)?o:(L5("converting shard to flat directory %c",r.cid),VZ(o,t,n))}return L5(`removing link ${e} regular directory`),$Z(r,e,t,n)}var $Z=async(r,e,t,n)=>{r.node.Links=r.node.Links.filter(s=>s.Name!==e);let i=Je(r.node),o=await Co(i,t,{...n,cidVersion:r.cid.version});return L5(`Updated regular directory ${o}`),{node:r.node,cid:o}},HZ=async(r,e,t,n)=>{let{path:i}=await N5(r.cid,e,t,n),o=i[i.length-1];if(o==null)throw new Error("Invalid HAMT, could not generate path");let s=o.node.Links.filter(l=>(l.Name??"").substring(2)===e).map(l=>l.Name).pop();if(s==null)throw new Error("File not found");let a=s.substring(0,2),c=parseInt(a,16);if(o.node.Links=o.node.Links.filter(l=>l.Name!==s),o.children.unset(c),o.node.Links.length===1)for(;i.length!==1;){let l=i[i.length-1];if(l==null||l.node.Links.length>1)break;i.pop();let u=i[i.length-1];if(u==null)break;let f=l.node.Links[0];u.node.Links=u.node.Links.filter(h=>!(h.Name??"").startsWith(u.prefix)),u.node.Links.push({Hash:f.Hash,Name:`${u.prefix}${(f.Name??"").substring(2)}`,Tsize:f.Tsize})}return D5(i,t,n)},VZ=async(r,e,t)=>{if(r.node.Data==null)throw new br("Invalid parent passed to convertToFlatDirectory");let n={Links:[]},i=await gr(r.cid,e);if(i.type!=="directory")throw new Error("Unexpected node type");for await(let c of i.content()){let l=0;c.node instanceof Uint8Array?l=c.node.byteLength:l=Je(c.node).length,n.Links.push({Hash:c.cid,Name:c.name,Tsize:l})}let o=Te.unmarshal(r.node.Data);n.Data=new Te({type:"directory",mode:o.mode,mtime:o.mtime}).marshal();let s=Je(Wt(n));return{cid:await Co(s,e,{codec:ir,cidVersion:r.cid.version,signal:t.signal}),node:n}};var zZ=Gt.bind({ignoreUndefined:!0}),KZ=ze("helia:unixfs:rm"),qZ={shardSplitThresholdBytes:262144};async function LM(r,e,t,n={}){let i=zZ(qZ,n);if(e.includes("/"))throw new br("Name must not have slashes");let o=await Ac(r,t,i);return KZ("Removing %s from %c",e,r),(await BM(o,e,t,{...i,cidVersion:r.version})).cid}var MM=1877,M5=1604,jZ=Gt.bind({ignoreUndefined:!0}),WZ=ze("helia:unixfs:stat"),GZ={};async function UM(r,e,t={}){let n=jZ(GZ,t),i=await ls(r,t.path,e,n);WZ("stat %c",i.cid);let o=await gr(i.cid,e,n);if(o.type==="raw")return t.extended===!0?ZZ(o):QZ(o);if(o.type==="file"||o.type==="directory")return t.extended===!0?YZ(o,e,t.filter??new xf({filterSize:1024}),t):XZ(o);throw new gi}function XZ(r){return{type:r.type,cid:r.cid,unixfs:r.unixfs,mode:r.unixfs.mode??(r.unixfs.isDirectory()?MM:M5),mtime:r.unixfs.mtime,size:r.unixfs.fileSize()}}async function YZ(r,e,t,n){let i=await FM(r.cid,e,!1,t,n);return{type:r.type,cid:r.cid,unixfs:r.unixfs,size:r.unixfs.isDirectory()?i.dirSize:r.unixfs.fileSize(),mode:r.unixfs.mode??(r.unixfs.isDirectory()?MM:M5),mtime:r.unixfs.mtime,localSize:i.localSize,dagSize:i.dagSize,deduplicatedDagSize:i.deduplicatedDagSize,blocks:i.blocks,uniqueBlocks:i.uniqueBlocks}}function QZ(r){return{type:r.type,cid:r.cid,unixfs:void 0,mode:M5,mtime:void 0,size:BigInt(r.node.byteLength)}}function ZZ(r){return{type:r.type,cid:r.cid,unixfs:void 0,mode:M5,mtime:void 0,size:BigInt(r.node.byteLength),localSize:BigInt(r.node.byteLength),dagSize:BigInt(r.node.byteLength),deduplicatedDagSize:BigInt(r.node.byteLength),blocks:1n,uniqueBlocks:1n}}async function FM(r,e,t,n,i){let o={dirSize:0n,localSize:0n,dagSize:0n,deduplicatedDagSize:0n,blocks:0n,uniqueBlocks:0n};try{let s=n.has(r.bytes);n.add(r.bytes);let a=await e.get(r,i);if(o.blocks++,o.dagSize+=BigInt(a.byteLength),s||(o.uniqueBlocks++,o.deduplicatedDagSize+=BigInt(a.byteLength)),r.code===Et)o.localSize+=BigInt(a.byteLength),t&&(o.dirSize+=BigInt(a.byteLength));else if(r.code===st){let c=nr(a),l;if(c.Data!=null&&(l=Te.unmarshal(c.Data)),c.Links.length>0){for(let u of c.Links){let f=await FM(u.Hash,e,JZ(u,l),n,i);o.localSize+=f.localSize,o.dagSize+=f.dagSize,o.deduplicatedDagSize+=f.deduplicatedDagSize,o.blocks+=f.blocks,o.uniqueBlocks+=f.uniqueBlocks,o.dirSize+=f.dirSize}t&&l!=null&&(o.dirSize+=l.fileSize())}else{if(l==null)throw new Xn(`PBNode ${r.toString()} had no data`);l.data!=null&&(o.localSize+=BigInt(l.data.byteLength??0)),t&&(o.dirSize+=l.fileSize())}}else throw new vc(`${r.toString()} was neither DAG_PB nor RAW`)}catch(s){if(s.name!=="NotFoundError"||i.offline!==!0)throw s}return o}function JZ(r,e){if(e==null)return!1;let t=r.Name;return t==null?!1:e.type==="directory"?!0:e.type==="hamt-sharded-directory"&&t.length>2}var eJ=Gt.bind({ignoreUndefined:!0}),tJ=ze("helia:unixfs:touch"),rJ={recursive:!1,shardSplitThresholdBytes:262144};async function $M(r,e,t={}){let n=eJ(rJ,t),i=await ls(r,n.path,e,n),o=n.mtime??{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(tJ("touch %c %o",i.cid,o),n.recursive){let h=await pt(async function*(){for await(let d of ch(i.cid,e)){let m,g;if(d.type==="raw")m=new Te({data:d.node}),g=[];else if(d.type==="file"||d.type==="directory")m=d.unixfs,g=d.node.Links;else throw new gi;m.mtime=o;let w={Data:m.marshal(),Links:g};yield{path:d.path,content:w}}},d=>Lu(d,e,{...n,dagBuilder:async function*(m,g){for await(let w of m)yield async function(){let x=w.content,S=Je(x),E=await Co(S,g,{...n,cidVersion:r.version});if(x.Data==null)throw new Xn(`${E} had no data`);let b=Te.unmarshal(x.Data);return{cid:E,size:BigInt(S.length),path:w.path,unixfs:b}}}}),async d=>Io(d));if(h==null)throw new vc(`Could not chmod ${i.cid.toString()}`);return dh(h.cid,i,e,n)}let s=await e.get(i.cid,t),a,c=[];if(i.cid.code===Et)a=new Te({data:s});else{let h=nr(s);if(c=h.Links,h.Data==null)throw new Xn(`${i.cid.toString()} had no data`);a=Te.unmarshal(h.Data)}a.mtime=o;let l=Je({Data:a.marshal(),Links:c}),u=await $e.digest(l),f=W.create(i.cid.version,st,u);return await e.put(f,l),dh(f,i,e,n)}var U5=class{components;constructor(e){this.components=e}async*addAll(e,t={}){yield*_5(e,this.components.blockstore,t)}async addBytes(e,t={}){return bM(e,this.components.blockstore,t)}async addByteStream(e,t={}){return vM(e,this.components.blockstore,t)}async addFile(e,t={}){return EM(e,this.components.blockstore,t)}async addDirectory(e={},t={}){return SM(e,this.components.blockstore,t)}async*cat(e,t={}){yield*kM(e,this.components.blockstore,t)}async chmod(e,t,n={}){return PM(e,t,this.components.blockstore,n)}async cp(e,t,n,i={}){return RM(e,t,n,this.components.blockstore,i)}async*ls(e,t={}){yield*DM(e,this.components.blockstore,t)}async mkdir(e,t,n={}){return OM(e,t,this.components.blockstore,n)}async rm(e,t,n={}){return LM(e,t,this.components.blockstore,n)}async stat(e,t={}){return UM(e,this.components.blockstore,t)}async touch(e,t={}){return $M(e,this.components.blockstore,t)}};function HM(r){return new U5(r)}async function VM(r,e,t,n){let i=t.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),o=r[Symbol.asyncIterator](),{value:s,done:a}=await o.next();if(a===!0)throw i.error("no content found for path",e),new X6;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:u,done:f}=await o.next();if(n?.signal?.aborted){l.error(new ft(n.signal.reason??"signal aborted by user")),l.close();return}if(f===!0){u!=null&&(n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(u)),l.close();return}n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(u)}}),firstChunk:s}}var KM=ht(zM(),1);function Yn(r){return new DataView(r.buffer,r.byteOffset)}var qM={len:1,get(r,e){return Yn(r).getUint8(e)},put(r,e,t){return Yn(r).setUint8(e,t),e+1}},Mt={len:2,get(r,e){return Yn(r).getUint16(e,!0)},put(r,e,t){return Yn(r).setUint16(e,t,!0),e+2}},hh={len:2,get(r,e){return Yn(r).getUint16(e)},put(r,e,t){return Yn(r).setUint16(e,t),e+2}};var sr={len:4,get(r,e){return Yn(r).getUint32(e,!0)},put(r,e,t){return Yn(r).setUint32(e,t,!0),e+4}},jM={len:4,get(r,e){return Yn(r).getUint32(e)},put(r,e,t){return Yn(r).setUint32(e,t),e+4}};var WM={len:4,get(r,e){return Yn(r).getInt32(e)},put(r,e,t){return Yn(r).setInt32(e,t),e+4}};var GM={len:8,get(r,e){return Yn(r).getBigUint64(e,!0)},put(r,e,t){return Yn(r).setBigUint64(e,t,!0),e+8}};var Qn=class{constructor(e,t){this.len=e,this.encoding=t,this.textDecoder=new TextDecoder(t)}get(e,t){return this.textDecoder.decode(e.subarray(t,t+this.len))}};var iJ="End-Of-Stream",Vt=class extends Error{constructor(){super(iJ),this.name="EndOfStreamError"}},Uu=class extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Fu=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0)throw new Vt;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let i=this.peekQueue.pop();if(!i)throw new Error("peekData should be defined");let o=Math.min(i.length,t);e.set(i.subarray(0,o),n),n+=o,t-=o,o<i.length&&this.peekQueue.push(i.subarray(o))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new Uu;let i=await this.readFromStream(e.subarray(n),t);if(i===0)break;n+=i}if(!t&&n<e.length)throw new Vt;return n}};var F5=class extends Fu{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}};var Gm=class extends F5{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}};var ph=class extends Fu{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let i=await this.reader.read();if(i.done){this.endOfStream=!0;break}i.value&&(n+=this.writeChunk(e.subarray(n),i.value))}if(n===0&&this.endOfStream)throw new Vt;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function LE(r){try{let e=r.getReader({mode:"byob"});return e instanceof ReadableStreamDefaultReader?new ph(e):new Gm(e)}catch(e){if(e instanceof TypeError)return new ph(r.getReader());throw e}}var $u=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new Vt;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new Vt;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new Vt;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new Vt;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};var sJ=256e3,$5=class extends $u{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),i=n.position-this.position;if(i>0)return await this.ignore(i),this.readBuffer(e,t);if(i<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let o=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=o,(!t||!t.mayBeLess)&&o<n.length)throw new Vt;return o}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),i=0;if(n.position){let o=n.position-this.position;if(o>0){let s=new Uint8Array(n.length+o);return i=await this.peekBuffer(s,{mayBeLess:n.mayBeLess}),e.set(s.subarray(o)),i-o}if(o<0)throw new Error("Cannot peek from a negative offset in a stream")}if(n.length>0){try{i=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(o){if(t?.mayBeLess&&o instanceof Vt)return 0;throw o}if(!n.mayBeLess&&i<n.length)throw new Vt}return i}async ignore(e){let t=Math.min(sJ,e),n=new Uint8Array(t),i=0;for(;i<e;){let o=e-i,s=await this.readBuffer(n,{length:Math.min(t,o)});if(s<0)return s;i+=s}return i}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}};var H5=class extends $u{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),i=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&i<n.length)throw new Vt;return e.set(this.uint8Array.subarray(n.position,n.position+i)),i}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function XM(r,e){let t=LE(r),n=e??{},i=n.onClose;return n.onClose=async()=>{if(await t.close(),i)return i()},new $5(t,n)}function YM(r,e){return new H5(r,e)}var xi=Uint8Array,mh=Uint16Array,cJ=Int32Array,QM=new xi([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ZM=new xi([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),lJ=new xi([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),JM=function(r,e){for(var t=new mh(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];for(var i=new cJ(t[30]),n=1;n<30;++n)for(var o=t[n];o<t[n+1];++o)i[o]=o-t[n]<<5|n;return{b:t,r:i}},eU=JM(QM,2),tU=eU.b,uJ=eU.r;tU[28]=258,uJ[258]=28;var rU=JM(ZM,0),fJ=rU.b,Vrt=rU.r,FE=new mh(32768);for(lt=0;lt<32768;++lt)na=(lt&43690)>>1|(lt&21845)<<1,na=(na&52428)>>2|(na&13107)<<2,na=(na&61680)>>4|(na&3855)<<4,FE[lt]=((na&65280)>>8|(na&255)<<8)>>1;var na,lt,Xm=function(r,e,t){for(var n=r.length,i=0,o=new mh(e);i<n;++i)r[i]&&++o[r[i]-1];var s=new mh(e);for(i=1;i<e;++i)s[i]=s[i-1]+o[i-1]<<1;var a;if(t){a=new mh(1<<e);var c=15-e;for(i=0;i<n;++i)if(r[i])for(var l=i<<4|r[i],u=e-r[i],f=s[r[i]-1]++<<u,h=f|(1<<u)-1;f<=h;++f)a[FE[f]>>c]=l}else for(a=new mh(n),i=0;i<n;++i)r[i]&&(a[i]=FE[s[r[i]-1]++]>>15-r[i]);return a},Ym=new xi(288);for(lt=0;lt<144;++lt)Ym[lt]=8;var lt;for(lt=144;lt<256;++lt)Ym[lt]=9;var lt;for(lt=256;lt<280;++lt)Ym[lt]=7;var lt;for(lt=280;lt<288;++lt)Ym[lt]=8;var lt,nU=new xi(32);for(lt=0;lt<32;++lt)nU[lt]=5;var lt;var dJ=Xm(Ym,9,1);var hJ=Xm(nU,5,1),ME=function(r){for(var e=r[0],t=1;t<r.length;++t)r[t]>e&&(e=r[t]);return e},ko=function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},UE=function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},pJ=function(r){return(r+7)/8|0},mJ=function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new xi(r.subarray(e,t))};var gJ=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],wi=function(r,e,t){var n=new Error(e||gJ[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,wi),!t)throw n;return n},$E=function(r,e,t,n){var i=r.length,o=n?n.length:0;if(!i||e.f&&!e.l)return t||new xi(0);var s=!t,a=s||e.i!=2,c=e.i;s&&(t=new xi(i*3));var l=function(ar){var yt=t.length;if(ar>yt){var zt=new xi(Math.max(yt*2,ar));zt.set(t),t=zt}},u=e.f||0,f=e.p||0,h=e.b||0,d=e.l,m=e.d,g=e.m,w=e.n,x=i*8;do{if(!d){u=ko(r,f,1);var S=ko(r,f+1,3);if(f+=3,S)if(S==1)d=dJ,m=hJ,g=9,w=5;else if(S==2){var M=ko(r,f,31)+257,_=ko(r,f+10,15)+4,C=M+ko(r,f+5,31)+1;f+=14;for(var L=new xi(C),G=new xi(19),F=0;F<_;++F)G[lJ[F]]=ko(r,f+F*3,7);f+=_*3;for(var K=ME(G),D=(1<<K)-1,ne=Xm(G,K,1),F=0;F<C;){var N=ne[ko(r,f,D)];f+=N&15;var E=N>>4;if(E<16)L[F++]=E;else{var U=0,Z=0;for(E==16?(Z=3+ko(r,f,3),f+=2,U=L[F-1]):E==17?(Z=3+ko(r,f,7),f+=3):E==18&&(Z=11+ko(r,f,127),f+=7);Z--;)L[F++]=U}}var V=L.subarray(0,M),A=L.subarray(M);g=ME(V),w=ME(A),d=Xm(V,g,1),m=Xm(A,w,1)}else wi(1);else{var E=pJ(f)+4,b=r[E-4]|r[E-3]<<8,T=E+b;if(T>i){c&&wi(0);break}a&&l(h+b),t.set(r.subarray(E,T),h),e.b=h+=b,e.p=f=T*8,e.f=u;continue}if(f>x){c&&wi(0);break}}a&&l(h+131072);for(var $=(1<<g)-1,Y=(1<<w)-1,H=f;;H=f){var U=d[UE(r,f)&$],le=U>>4;if(f+=U&15,f>x){c&&wi(0);break}if(U||wi(2),le<256)t[h++]=le;else if(le==256){H=f,d=null;break}else{var ke=le-254;if(le>264){var F=le-257,se=QM[F];ke=ko(r,f,(1<<se)-1)+tU[F],f+=se}var Re=m[UE(r,f)&Y],Ne=Re>>4;Re||wi(3),f+=Re&15;var A=fJ[Ne];if(Ne>3){var se=ZM[Ne];A+=UE(r,f)&(1<<se)-1,f+=se}if(f>x){c&&wi(0);break}a&&l(h+131072);var Ge=h+ke;if(h<A){var Xe=o-A,ut=Math.min(A,Ge);for(Xe+h<0&&wi(3);h<ut;++h)t[h]=n[Xe+h]}for(;h<Ge;++h)t[h]=t[h-A]}}e.l=d,e.p=H,e.b=h,e.f=u,d&&(u=1,e.m=g,e.d=m,e.n=w)}while(!u);return h!=t.length&&s?mJ(t,0,h):t.subarray(0,h)};var yJ=new xi(0);var wJ=function(r){(r[0]!=31||r[1]!=139||r[2]!=8)&&wi(6,"invalid gzip data");var e=r[3],t=10;e&4&&(t+=(r[10]|r[11]<<8)+2);for(var n=(e>>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},xJ=function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0};var bJ=function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&wi(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&wi(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2};function vJ(r,e){return $E(r,{i:2},e&&e.out,e&&e.dictionary)}function EJ(r,e){var t=wJ(r);return t+8>r.length&&wi(6,"invalid gzip data"),$E(r.subarray(t,-8),{i:2},e&&e.out||new xi(xJ(r)),e&&e.dictionary)}function SJ(r,e){return $E(r.subarray(bJ(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}function iU(r,e){return r[0]==31&&r[1]==139&&r[2]==8?EJ(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?vJ(r,e):SJ(r,e)}var AJ=typeof TextDecoder<"u"&&new TextDecoder,_J=0;try{AJ.decode(yJ,{stream:!0}),_J=1}catch{}var hU=ht(lU(),1);var Vu={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},HE={get(r){let e=Mt.get(r,6);return{signature:sr.get(r,0),compressedSize:sr.get(r,8),uncompressedSize:sr.get(r,12)}},len:16},uU={get(r){let e=Mt.get(r,6);return{signature:sr.get(r,0),minVersion:Mt.get(r,4),dataDescriptor:!!(e&8),compressedMethod:Mt.get(r,8),compressedSize:sr.get(r,18),uncompressedSize:sr.get(r,22),filenameLength:Mt.get(r,26),extraFieldLength:Mt.get(r,28),filename:null}},len:30},fU={get(r){return{signature:sr.get(r,0),nrOfThisDisk:Mt.get(r,4),nrOfThisDiskWithTheStart:Mt.get(r,6),nrOfEntriesOnThisDisk:Mt.get(r,8),nrOfEntriesOfSize:Mt.get(r,10),sizeOfCd:sr.get(r,12),offsetOfStartOfCd:sr.get(r,16),zipFileCommentLength:Mt.get(r,20)}},len:22},dU={get(r){let e=Mt.get(r,8);return{signature:sr.get(r,0),minVersion:Mt.get(r,6),dataDescriptor:!!(e&8),compressedMethod:Mt.get(r,10),compressedSize:sr.get(r,20),uncompressedSize:sr.get(r,24),filenameLength:Mt.get(r,28),extraFieldLength:Mt.get(r,30),fileCommentLength:Mt.get(r,32),relativeOffsetOfLocalHeader:sr.get(r,42),filename:null}},len:46};function pU(r){let e=new Uint8Array(sr.len);return sr.put(e,0,r),e}var us=(0,hU.default)("tokenizer:inflate"),VE=256*1024,UJ=pU(Vu.DataDescriptor),K5=pU(Vu.EndOfCentralDirectory),q5=class{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(VE)}async isZip(){return await this.peekSignature()===Vu.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(sr)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let i=n.length-4;i>=0;i--)if(n[i]===K5[0]&&n[i+1]===K5[1]&&n[i+2]===K5[2]&&n[i+3]===K5[3])return e.fileInfo.size-t+i;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){us("Cannot reading central-directory without random-read support");return}us("Reading central-directory...");let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){us("Central-directory 32-bit signature found");let n=await this.tokenizer.readToken(fU,t),i=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let o=0;o<n.nrOfEntriesOfSize;++o){let s=await this.tokenizer.readToken(dU);if(s.signature!==Vu.CentralFileHeader)throw new Error("Expected Central-File-Header signature");s.filename=await this.tokenizer.readToken(new Qn(s.filenameLength,"utf-8")),await this.tokenizer.ignore(s.extraFieldLength),await this.tokenizer.ignore(s.fileCommentLength),i.push(s),us(`Add central-directory file-entry: n=${o+1}/${i.length}: filename=${i[o].filename}`)}return this.tokenizer.setPosition(e),i}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let i=await this.readLocalFileHeader();if(!i)break;let o=e(i);n=!!o.stop;let s;if(await this.tokenizer.ignore(i.extraFieldLength),i.dataDescriptor&&i.compressedSize===0){let a=[],c=VE;us("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let l=-1;for(;l<0&&c===VE;){c=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),l=FJ(this.syncBuffer.subarray(0,c),UJ);let u=l>=0?l:c;if(o.handler){let f=new Uint8Array(u);await this.tokenizer.readBuffer(f),a.push(f)}else await this.tokenizer.ignore(u)}us(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),o.handler&&await this.inflate(i,$J(a),o.handler)}else o.handler?(us(`Reading compressed-file-data: ${i.compressedSize} bytes`),s=new Uint8Array(i.compressedSize),await this.tokenizer.readBuffer(s),await this.inflate(i,s,o.handler)):(us(`Ignoring compressed-file-data: ${i.compressedSize} bytes`),await this.tokenizer.ignore(i.compressedSize));if(us(`Reading data-descriptor at pos=${this.tokenizer.position}`),i.dataDescriptor&&(await this.tokenizer.readToken(HE)).signature!==134695760)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-HE.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let i=t(n);if(i.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let o=await this.readLocalFileHeader();if(o){await this.tokenizer.ignore(o.extraFieldLength);let s=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(s),await this.inflate(o,s,i.handler)}}if(i.stop)break}}inflate(e,t,n){if(e.compressedMethod===0)return n(t);us(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let i=iU(t);return n(i)}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(sr);if(e===Vu.LocalFileHeader){let t=await this.tokenizer.readToken(uU);return t.filename=await this.tokenizer.readToken(new Qn(t.filenameLength,"utf-8")),t}if(e===Vu.CentralFileHeader)return!1;throw e===3759263696?new Error("Encrypted ZIP"):new Error("Unexpected signature")}};function FJ(r,e){let t=r.length,n=e.length;if(n>t)return-1;for(let i=0;i<=t-n;i++){let o=!0;for(let s=0;s<n;s++)if(r[i+s]!==e[s]){o=!1;break}if(o)return i}return-1}function $J(r){let e=r.reduce((i,o)=>i+o.length,0),t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var Zrt={utf8:new globalThis.TextDecoder("utf8")};var Jrt=new globalThis.TextEncoder;var ent=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function zE(r){let{byteLength:e}=r;if(e===6)return r.getUint16(0)*2**32+r.getUint32(2);if(e===5)return r.getUint8(0)*2**32+r.getUint32(1);if(e===4)return r.getUint32(0);if(e===3)return r.getUint8(0)*2**16+r.getUint16(1);if(e===2)return r.getUint16(0);if(e===1)return r.getUint8(0)}function HJ(r,e){let t=r.length,n=e.length;if(n===0||n>t)return-1;let i=t-n;for(let o=0;o<=i;o++){let s=!0;for(let a=0;a<n;a++)if(r[o+a]!==e[a]){s=!1;break}if(s)return o}return-1}function mU(r,e){return HJ(r,e)!==-1}function gU(r){return[...r].map(e=>e.charCodeAt(0))}function yU(r,e=0){let t=Number.parseInt(new Qn(6).get(r,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(t))return!1;let n=8*32;for(let i=e;i<e+148;i++)n+=r[i];for(let i=e+156;i<e+512;i++)n+=r[i];return t===n}var wU={get:(r,e)=>r[e+3]&127|r[e+2]<<7|r[e+1]<<14|r[e]<<21,len:4};var xU=["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","ai","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","rm","ppsm","ppsx"],bU=["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/x-apache-arrow","video/mp4","audio/midi","video/x-matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/x-flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/x-parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx","application/vnd.visio","application/vnd.android.package-archive","application/vnd.google.draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia"];var KE=4100;async function vU(r){return new jE().fromBuffer(r)}function qE(r){switch(r.toLowerCase()){case"application/epub+zip":return{ext:"epub",mime:"application/epub+zip"};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:"application/vnd.oasis.opendocument.text"};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:"application/vnd.oasis.opendocument.text-template"};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:"application/vnd.oasis.opendocument.spreadsheet"};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:"application/vnd.oasis.opendocument.spreadsheet-template"};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:"application/vnd.oasis.opendocument.presentation"};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:"application/vnd.oasis.opendocument.presentation-template"};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:"application/vnd.oasis.opendocument.graphics"};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:"application/vnd.oasis.opendocument.graphics-template"};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:"application/vnd.openxmlformats-officedocument.presentationml.slideshow"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.template"};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.template"};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:"application/vnd.openxmlformats-officedocument.presentationml.template"};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"};default:}}function fs(r,e,t){t={offset:0,...t};for(let[n,i]of e.entries())if(t.mask){if(i!==(t.mask[n]&r[n+t.offset]))return!1}else if(i!==r[n+t.offset])return!1;return!0}var jE=class{constructor(e){this.detectors=[...e?.customDetectors??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:e?.signal}}async fromTokenizer(e){let t=e.position;for(let n of this.detectors){let i=await n.detect(e);if(i)return i;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(YM(t,this.tokenizerOptions))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){let t=await XM(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){let{sampleSize:n=KE}=t,i,o,s=e.getReader({mode:"byob"});try{let{value:l,done:u}=await s.read(new Uint8Array(n));if(o=l,!u&&l)try{i=await this.fromBuffer(l.slice(0,n))}catch(f){if(!(f instanceof Vt))throw f;i=void 0}o=l}finally{s.releaseLock()}let a=new TransformStream({async start(l){l.enqueue(o)},transform(l,u){u.enqueue(l)}}),c=e.pipeThrough(a);return c.fileType=i,c}check(e,t){return fs(this.buffer,e,t)}checkString(e,t){return this.check(gU(e),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(KE),e.fileInfo.size===void 0&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return{ext:"gz",mime:"application/gzip"};if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await e.ignore(6);let t=await e.readToken(wU);return e.position+t>e.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){let t;return await new q5(e).unzip(n=>{switch(n.filename){case"META-INF/mozilla.rsa":return t={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return t={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return{async handler(i){let o=new TextDecoder("utf-8").decode(i).trim();t=qE(o)},stop:!0};case"[Content_Types].xml":return{async handler(i){let o=new TextDecoder("utf-8").decode(i),s=o.indexOf('.main+xml"');if(s===-1){let a="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";o.includes(`ContentType="${a}"`)&&(t=qE(a))}else{o=o.slice(0,Math.max(0,s));let a=o.lastIndexOf('"'),c=o.slice(Math.max(0,a+1));t=qE(c)}},stop:!0};default:return/classes\d*\.dex/.test(n.filename)?(t={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}}),t??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),fs(t,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:fs(t,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:fs(t,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:fs(t,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:fs(t,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:fs(t,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/x-flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF")){try{if(await e.ignore(1350)===1350){let i=new Uint8Array(Math.min(10485760,e.fileInfo.size-1350));if(await e.readBuffer(i,{mayBeLess:!0}),mU(i,new TextEncoder().encode("AIPrivateData")))return{ext:"ai",mime:"application/postscript"}}}catch(t){if(!(t instanceof Vt))throw t}return{ext:"pdf",mime:"application/pdf"}}if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){let t=await this.readTiffHeader(!1);if(t)return t}if(this.check([77,77])){let t=await this.readTiffHeader(!0);if(t)return t}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function t(){let a=await e.peekNumber(qM),c=128,l=0;for(;(a&c)===0&&c!==0;)++l,c>>=1;let u=new Uint8Array(l+1);return await e.readBuffer(u),u}async function n(){let a=await t(),c=await t();c[0]^=128>>c.length-1;let l=Math.min(6,c.length),u=new DataView(a.buffer),f=new DataView(c.buffer,c.length-l,l);return{id:zE(u),len:zE(f)}}async function i(a){for(;a>0;){let c=await n();if(c.id===17026)return(await e.readToken(new Qn(c.len))).replaceAll(/\00.*$/g,"");await e.ignore(c.len),--a}}let o=await n();switch(await i(o.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/x-matroska"};default:return}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1"))return{ext:"parquet",mime:"application/x-parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190]))return{ext:"class",mime:"application/java-vm"};if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/vnd.google.draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){let t=new Qn(4,"latin1").get(this.buffer,2);if(t.match("^d*")&&t>=1e3&&t<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>"))return await e.ignore(8),await e.readToken(new Qn(13,"ascii"))==="debian-binary"?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(this.checkString("WEBVTT")&&[`
|
|
83
|
+
`,"\r"," "," ","\0"].some(t=>this.checkString(t,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){await e.ignore(8);async function t(){return{length:await e.readToken(WM),type:await e.readToken(new Qn(4,"latin1"))}}do{let n=await t();if(n.length<0)return;switch(n.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(n.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/x-apache-arrow"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.checkString("ftyp",{offset:4})&&(this.buffer[8]&96)!==0){let t=new Qn(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(t){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return t.startsWith("3g")?t.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.check([82,73,70,70])){if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function t(){let n=new Uint8Array(16);return await e.readBuffer(n),{id:n,size:Number(await e.readToken(GM))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),i=n.size-24;if(fs(n.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let o=new Uint8Array(16);if(i-=await e.readBuffer(o),fs(o,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(fs(o,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await e.ignore(i)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new Qn(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){let t=new DataView(this.buffer.buffer).getUint32(12,!0);if(t>12&&this.buffer.length>=t+16)try{let n=new TextDecoder().decode(this.buffer.slice(16,t+16));if(JSON.parse(n).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x.autodesk.fbx"};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),yU(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:"xml",mime:"application/xml"}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:void 0;if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"}};detectImprecise=async e=>{if(this.buffer=new Uint8Array(KE),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(this.buffer.length>=2&&this.check([255,224],{offset:0,mask:[255,224]})){if(this.check([16],{offset:1,mask:[22]}))return this.check([8],{offset:1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?hh:Mt);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?hh:Mt);for(let n=0;n<t;++n){let i=await this.readTiffTag(e);if(i)return i}}async readTiffHeader(e){let t=(e?hh:Mt).get(this.buffer,2),n=(e?jM:sr).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(n>=8){let o=(e?hh:Mt).get(this.buffer,8),s=(e?hh:Mt).get(this.buffer,10);if(o===28&&s===254||o===31&&s===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:"tif",mime:"image/tiff"}}if(t===43)return{ext:"tif",mime:"image/tiff"}}},lnt=new Set(xU),unt=new Set(bU);var _c=ze("helia:verified-fetch:content-type-parser"),j5="application/octet-stream";function VJ(r){return _c("checking for svg"),/^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(r)}async function zJ(r){_c("checking for json");try{return JSON.parse(r),!0}catch(e){return _c("failed to parse as json",e),!1}}function KJ(r){_c("checking for text");let e=new TextDecoder("utf-8",{fatal:!0});try{return e.decode(r)}catch{return null}}async function qJ(r){return _c("checking for html"),/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(r)}async function EU(r,e){_c("contentTypeParser called for fileName: %s, byte size=%s",e,r.length);let t=(await vU(r))?.mime;if(t!=null)return _c("detectedType: %s",t),t;if(_c("no detectedType"),e==null){let n=KJ(r);return n!=null?VJ(n)?"image/svg+xml":await zJ(n)?"application/json":await qJ(n)?"text/html; charset=utf-8":"text/plain; charset=utf-8":j5}switch(e.split(".").pop()){case"css":return"text/css";case"html":return"text/html; charset=utf-8";case"js":return"application/javascript";case"json":return"application/json";case"txt":return"text/plain";case"woff2":return"font/woff2";case"svg":return"image/svg+xml";case"csv":return"text/csv";case"doc":return"application/msword";case"xls":return"application/vnd.ms-excel";case"ppt":return"application/vnd.ms-powerpoint";case"msi":return"application/x-msdownload";default:return j5}}function SU(r){return r?.then!=null}async function W5({bytes:r,path:e,response:t,contentTypeParser:n,log:i,defaultContentType:o="application/octet-stream",filename:s}){let a;if(n!=null)try{let c;s==null?(c=e.split("/").pop()?.trim(),c=c===""||c?.split(".").length===1?void 0:c):c=s;let l=n(r,c);if(SU(l)){let u=await l;u!=null&&(a=u)}else l!=null&&(a=l);i.trace("contentTypeParser returned %s",a)}catch(c){i.error("error parsing content type",c)}a===j5&&(a=o),i.trace('setting content type to "%s"',a??o),t.headers.set("content-type",a??o)}var G5=class extends Lt{id="dag-pb-plugin";codes=[st];canHandle({cid:e,accept:t,pathDetails:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),n==null||i==null?!1:e.code===st}getRedirectUrl(e){let{resource:t,path:n}=e;if(n===""?!t.toString().endsWith("/"):!n.endsWith("/"))try{let o=new URL(t.toString());return o.pathname.endsWith("/")?null:(o.pathname=`${o.pathname}/`,o.toString())}catch{return`${t.toString()}/`}return null}async handle(e){let{cid:t,options:n,withServerTiming:i=!1,pathDetails:o,query:s}=e,{handleServerTiming:a,contentTypeParser:c,helia:l,getBlockstore:u}=this.pluginOptions,f=this.log,h=e.resource,d=e.path,m=!1,g=e.byteRangeContext,w=o.ipfsRoots,x=o.terminalElement,S=x.cid;if(x?.type==="directory"){let T=x.cid,M=this.getRedirectUrl(e);if(M!=null){if(f.trace("directory url normalization spec requires redirect..."),n?.redirect==="error")throw f('could not redirect to %s as redirect option was set to "error"',M),new TypeError("Failed to fetch");if(n?.redirect==="manual")return f("returning 301 permanent redirect to %s",M),Mm(h,M);f("following redirect to %s",M),h=M,m=!0}let _="index.html";try{f.trace("found directory at %c/%s, looking for index.html",t,d);let C=await a("exporter-dir","",async()=>gr(`/ipfs/${T}/${_}`,l.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),i);f.trace("found root file at %c/%s with cid %c",T,_,C.cid),d=_,S=C.cid}catch(C){if(n?.signal?.aborted)throw new ft(n?.signal?.reason);this.log.error("error loading path %c/%s",T,_,C),e.isDirectory=!0,e.directoryEntries=[],e.modified++,this.log.trace("attempting to get directory entries because index.html was not found");let L=HM({...l,blockstore:u(e.cid,e.resource,n?.session??!0,n)});try{for await(let G of L.ls(T,{signal:n?.signal,onProgress:n?.onProgress}))e.directoryEntries.push(G);return null}catch(G){return f.error("error listing directory %c",T,G),c5("Unable to get directory contents")}}finally{n?.onProgress?.(new X("verified-fetch:request:end",{cid:T,path:_}))}}g.isRangeRequest&&g.isValidRangeRequest&&x.type==="file"&&(g.setFileSize(x.unixfs.fileSize()),f.trace("fileSize for rangeRequest %d",g.getFileSize()));let E=g.offset,b=g.length;f.trace("calling exporter for %c/%s with offset=%o & length=%o",S,d,E,b);try{let M=(await a("exporter-file","",async()=>gr(S,l.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),i)).content({signal:n?.signal,onProgress:n?.onProgress,offset:E,length:b});f("got async iterator for %c/%s",t,d);let{stream:_,firstChunk:C}=await a("stream-and-chunk","",async()=>VM(M,d??"",this.pluginOptions.logger,{onProgress:n?.onProgress,signal:n?.signal}),i);g.setBody(_);let L=cn(h,g.getBody(),{byteRangeContext:g,log:f},{redirected:m});return await a("set-content-type","",async()=>W5({filename:s.filename,bytes:C,path:d,response:L,contentTypeParser:c,log:f}),i),Q6(L,w),L}catch(T){if(n?.signal?.aborted)throw new ft(n?.signal?.reason);return f.error("error streaming %c/%s",t,d,T),g.isRangeRequest&&T.code==="ERR_INVALID_PARAMS"?a5(h):rh(h.toString(),"Unable to stream content")}}};var X5=class extends Lt{id="dag-walk-plugin";canHandle(e){this.log("checking if we can handle %c with accept %s",e.cid,e.accept);let{pathDetails:t,cid:n}=e;return t!=null?!1:n.code===st||n.code===Rn}async handle(e){let{cid:t,resource:n,options:i,withServerTiming:o=!1}=e,{getBlockstore:s,handleServerTiming:a}=this.pluginOptions,c=s(t,n,i?.session??!0,i),l=await a("path-walking","",async()=>nM({...e,blockstore:c,log:this.log}),o);return l instanceof Response?(this.log.trace("path walking failed"),l.status===404?l:null):(e.modified++,e.pathDetails=l,null)}};function Y5(r){return r.charAt(0)==="1"||r.charAt(0)==="Q"?ot(r):wn(W.parse(r))}var Qm=class extends Error{name="PluginError";code;fatal;details;response;constructor(e,t,n){super(t),this.code=e,this.fatal=n?.fatal??!1,this.details=n?.details,this.response=n?.response}},ia=class extends Qm{name="PluginFatalError";constructor(e,t,n){super(e,t,{...n,fatal:!0}),this.name="PluginFatalError"}};var Q5=class extends Lt{id="ipns-record-plugin";codes=[];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/vnd.ipfs.ipns-record"||n.format==="ipns-record"}async handle(e){let{resource:t,path:n,options:i}=e,{helia:o}=this.pluginOptions;if(e.reqFormat="ipns-record",n!==""||!(t.startsWith("ipns://")||t.includes(".ipns.")||t.includes("/ipns/")))throw this.log.error('invalid request for IPNS name "%s" and path "%s"',t,n),new ia("ERR_INVALID_IPNS_NAME","Invalid IPNS name",{response:Lm(t,new Error("Invalid IPNS name"))});let s;try{let h;t.startsWith("ipns://")?h=t.replace("ipns://",""):t.includes("/ipns/")?h=t.split("/ipns/")[1].split("/")[0].split("?")[0]:h=t.split(".ipns.")[0].split("://")[1],this.log.trace('trying to parse peer id from "%s"',h),s=Y5(h)}catch(h){throw this.log.error("could not parse peer id from IPNS url %s",t,h),new ia("ERR_NO_PEER_ID_FOUND","could not parse peer id from url",{response:Lm(t,h)})}let a=Ve([R("/ipns/"),s.toMultihash().bytes]),c=new nt("/dht/record/"+q(a,"base32"),!1),l=await o.datastore.get(c,i),u=Ot.deserialize(l);e.byteRangeContext.setBody(u.value);let f=cn(t,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:this.log});return f.headers.set("content-type","application/vnd.ipfs.ipns-record"),f}};var Z5=class extends Lt{id="json-plugin";codes=[so,Bo];canHandle({cid:e,accept:t,byteRangeContext:n}){return this.log("checking if we can handle %c with accept %s",e,t),n==null?!1:t==="application/vnd.ipld.dag-json"&&e.code!==Rn?!0:so===e.code||Bo===e.code}async handle(e){let{path:t,resource:n,cid:i,accept:o,options:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.session??!0;this.log.trace("fetching %c/%s",i,t);let l=e.pathDetails?.terminalElement.cid??e.cid,f=await a(l,n,c,s).get(l,s),h;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let g=kf(f);h=Tf(g)}catch(g){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",g),ra(n)}else h=f;let d;o==null?so===i.code?d="application/vnd.ipld.dag-json":d="application/json":d=o.split(";")[0],e.byteRangeContext.setBody(h);let m=cn(n,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:this.log});return this.log.trace("setting content-type to %s",d),m.headers.set("content-type",d),e.byteRangeContext.isValidRangeRequest||m.headers.set("content-length",h.length.toString()),m}};var jJ=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function WJ({headers:r,accept:e}){let n=(e??new Headers(r).get("accept")??"").split(",").map(i=>i.split(";")[0]).map(i=>i.trim());for(let i of n){if(i==="*/*")return;if(jJ.includes(i??""))return i}}var J5=class extends Lt{id="raw-plugin";codes=[Et,ur.code];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/vnd.ipld.raw"||n.format==="raw"}async handle(e){let{path:t,resource:n,cid:i,accept:o,query:s,options:a}=e,{getBlockstore:c,contentTypeParser:l}=this.pluginOptions,u=a?.session??!0,f=this.log;if(o==="application/vnd.ipld.raw"||s.format==="raw"?(e.reqFormat="raw",e.query.download=!0,e.query.filename=e.query.filename??`${i.toString()}.bin`,f.trace("Set content disposition...")):f.trace("Did NOT set content disposition..."),t!==""&&i.code===Et)throw f.trace("404-ing raw codec request for %c/%s",i,t),new ia("ERR_RAW_PATHS_NOT_SUPPORTED","Raw codec does not support paths",{response:l5(n,"Raw codec does not support paths")});let h=e.pathDetails?.terminalElement.cid??e.cid,m=await c(h,n,u,a).get(h,a);e.byteRangeContext.setBody(m);let g=cn(n,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:f},{redirected:!1});return await W5({filename:s.filename,bytes:m,path:t,response:g,defaultContentType:WJ({headers:a?.headers,accept:o}),contentTypeParser:l,log:f}),g}};var GJ=({weak:r,reqFormat:e})=>e==="tar"||e==="car"||e==="ipns-record"||r===!0?"W/":"",XJ=({reqFormat:r})=>r==null?"":r==="tar"?".x-tar":`.${r}`;function xh({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:i,contentPrefix:o}){let s=GJ({weak:t,reqFormat:e}),a=XJ({reqFormat:e});return(n!=null||i!=null)&&(a+=`.${n??"0"}-${i??"N"}`),`${s}"${o??""}${r.toString()}${a}"`}var fit=R("ustar\0","binary"),dit=R("ustar ","binary"),hit=R(" \0","binary");var CU=ht(_U(),1);function QJ(r){return r[Symbol.asyncIterator]!=null}function ZJ(r){if(QJ(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=Ve([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Ve(e,t)}var IU=ZJ;var JJ="0000000000000000000",eee="7777777777777777777",tee=48,ree=R("ustar\0","binary"),nee=R("00","binary"),iee=parseInt("7777",8),oee=257,see=263,aee=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}},cee=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},Ic=function(r,e){let t=r.toString(8);return t.length>e?R(eee.slice(0,e)+" "):R(JJ.slice(0,e-t.length)+t+" ")},WE=function(r){let e=R(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function TU(r){let e="";r.name!=null&&(e+=WE(" path="+r.name+`
|
|
84
84
|
`)),r.linkname!=null&&(e+=WE(" linkpath="+r.linkname+`
|
|
85
85
|
`));let t=r.pax;if(t!=null)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e+=WE(" "+n+"="+t[n]+`
|
|
86
|
-
`));return R(e)}function e8(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),R(t).byteLength!==t.length)return null;for(;R(t).byteLength>100;){let i=t.indexOf("/");if(i===-1)return null;n+=n!==""?"/"+t.slice(0,i):t.slice(0,i),t=t.slice(i+1)}return R(t).byteLength>100||R(n).byteLength>155||r.linkname!=null&&R(r.linkname).byteLength>100?null:(e.set(R(t),0),e.set(Ic(r.mode&iee,6),100),e.set(Ic(r.uid,6),108),e.set(Ic(r.gid,6),116),e.set(Ic(r.size,11),124),e.set(Ic(r.mtime.getTime()/1e3|0,11),136),e[156]=tee+aee(r.type),r.linkname!=null&&e.set(R(r.linkname),157),e.set(ree,oee),e.set(nee,see),r.uname!=null&&e.set(R(r.uname),265),r.gname!=null&&e.set(R(r.gname),297),e.set(Ic(r.devmajor??0,6),329),e.set(Ic(r.devminor??0,6),337),n!=null&&e.set(R(n),345),e.set(Ic(cee(e),6),148),e)}var{S_IFMT:uee,S_IFBLK:fee,S_IFCHR:dee,S_IFDIR:hee,S_IFIFO:pee,S_IFLNK:mee}=CU.default,gee=parseInt("755",8),yee=parseInt("644",8),kU=new Uint8Array(1024);function wee(r=0){switch(r&uee){case fee:return"block-device";case dee:return"character-device";case hee:return"directory";case pee:return"fifo";case mee:return"symlink";default:return"file"}}function XE(r){return r&=511,r!==0?kU.subarray(0,512-r):new Uint8Array(0)}function GE(r){if(r.pax==null){let e=e8(r);if(e!=null)return e}return xee(r)}function xee(r){let e=TU(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 ge(e8(t)??new Uint8Array(0),e,XE(e.length),e8({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function t8(){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??wee(e.mode),mode:e.mode??(e.type==="directory"?gee:yee),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=R(t)),t instanceof Uint8Array||bi(t)){n.size=t.length,yield GE(n),yield bi(t)?t.subarray():t,yield XE(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=q(await IU(t)),yield GE(n);continue}if(yield GE(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let i=0;for await(let o of t??[])i+=o.length,yield bi(o)?o.subarray():o;if(i!==n.size)throw new Error(`size mismatch, wrote ${i} of ${n.size} bytes`);yield XE(n.size)}yield kU}}var bee=["file","raw","directory"];function vee(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 PU(r){if(!bee.includes(r.type))throw new gi(`${r.type} is not a UnixFS node`);let e={header:vee(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*RU(r,e,t){let n=await gr(r,e,t);if(n.type==="file"||n.type==="raw"){yield*pt([PU(n)],t8());return}if(n.type==="directory"){yield*pt(ch(r,e,t),i=>qt(i,o=>PU(o)),t8());return}throw new gi("Not a UnixFS node")}var r8=class extends Lt{codes=[];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/x-tar"||n.format==="tar"}async handle(e){let{cid:t,path:n,resource:i,options:o,pathDetails:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.terminalElement.cid??t;if(c.code!==st&&c.code!==Et)return ra("only UnixFS data can be returned in a TAR file");e.reqFormat="tar",e.query.download=!0,e.query.filename=e.query.filename??`${c.toString()}.tar`;let l=a(c,i,o?.session,o),u=Bm(RU(`/ipfs/${t}/${n}`,l,o));e.byteRangeContext.setBody(u);let f=cn(i,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:this.log});return f.headers.set("content-type","application/x-tar"),f.headers.set("etag",xh({cid:c,reqFormat:e.reqFormat,weak:!0})),f}};function DU(r){let e=Eee(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function Eee(r){return r.replace(/[^\x00-\x7F]/g,"_")}var See={[Rn]:["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"],[so]:["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"],[Bo]:["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"],[st]:["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"],[Et]:["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 NU(r,e){let t=See[r.code];if(e!=null)return Aee(e,t)}function Aee(r,e){let t=r.split(",").map(n=>{let i=n.trim().split(";");return{mimeType:`${i[0]}`.trim(),weight:_ee(i[1])}}).sort((n,i)=>n.weight===i.weight?0:n.weight>i.weight?-1:1).map(n=>n.mimeType);for(let n of t)for(let i of e)if(n.includes(i)||n==="*/*"||n.startsWith("*/")&&i.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&i.split("/")[0]===n.split("/")[0])return i}function _ee(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 n8={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 OU(r){if(r!=null)return n8[r]}function YE(r){let e=r.get("accept");return!!(e!=null&&Object.values(n8).includes(e))}function QE(r){let e=r?.format;return!!(e!=null&&Object.keys(n8).includes(e))}function BU({query:r,headers:e}){return YE(e)||QE(r)}function LU({query:r,headers:e,logger:t}){let n=t.forComponent("helia:verified-fetch:get-resolved-accept-header"),i=new Headers(e),o=i.get("accept")??void 0;if(o!=null&&n('incoming accept header "%s"',o),!BU({query:r,headers:i}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",o),o;let s=OU(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=o;return!YE(i)&&QE(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 Zm(r,e,t){let n=performance.now();try{let i=await t(),s=(performance.now()-n).toFixed(1),a=`${r};dur=${s};desc="${e}"`;return{result:i,header:a,error:null}}catch(i){let s=(performance.now()-n).toFixed(1),a=`${r};dur=${s};desc="${e}"`;return{result:null,error:i,header:a}}}var i8=class{lru;constructor(e){this.lru=new Ru({maxSize:e})}get(e){return this.lru.get(e)}set(e,t,n){this.lru.set(e,t,{maxAge:Date.now()+n})}has(e){return this.get(e)!=null}remove(e){this.lru.delete(e)}clear(){this.lru.clear()}};var MU=new i8(1e3),Iee=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,Tee=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,Cee=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,kee=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function Pee(r){let e=r?.protocol;if(e==null)return!1;let t=r?.cidOrPeerIdOrDnsLink;if(t==null)return!1;let n=r?.path,i=r?.queryString;return["ipns","ipfs"].includes(e)&&typeof t=="string"&&(n==null||typeof n=="string")&&(i==null||typeof i=="string")}function Jm(r){for(let e of[kee,Iee,Cee,Tee]){let t=r.match(e);if(Pee(t?.groups))return t.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function Ree(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 Dee=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function Nee(r){return Dee.test(r)&&r.includes("-")&&!r.includes(".")}function Oee(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function UU({urlString:r,ipns:e,logger:t,withServerTiming:n=!1},i){let o=t.forComponent("helia:verified-fetch:parse-url-string"),{protocol:s,cidOrPeerIdOrDnsLink:a,path:c,queryString:l}=Jm(r),u,f,h=[],d,m=[];if(s==="ipfs")try{u=W.parse(a)}catch(x){o.error(x),h.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(d=MU.get(a),d!=null)u=d.cid,f=d.path,o.trace("resolved %s to %c from cache",a,u);else{o.trace("Attempting to resolve PeerId for %s",a);let x;try{x=Y5(a);let S=x?.publicKey;if(S==null)throw new TypeError("cidOrPeerIdOrDnsLink contains no public key");if(n){let E=async()=>e.resolve(S,i),b=await Zm("ipns.resolve",`Resolve IPNS name ${a}`,E);if(m.push(b),b.error!=null)throw b.error;d=b.result}else d=await e.resolve(S,i);u=d?.cid,f=d?.path,o.trace("resolved %s to %c",a,u)}catch(S){if(i?.signal?.aborted)throw new ft(i?.signal?.reason);x==null?(o.error('could not parse PeerId string "%s"',a,S),h.push(new TypeError(`Could not parse PeerId in ipns url "${a}", ${S.message}`))):(o.error("could not resolve PeerId %c",x,S),h.push(new TypeError(`Could not resolve PeerId "${a}": ${S.message}`)))}if(u==null){let S=a;Nee(a)&&(S=Oee(a),o.trace('decoded dnslink from "%s" to "%s"',a,S)),o.trace("Attempting to resolve DNSLink for %s",S);try{if(n){let E=await Zm("ipns.resolveDNSLink",`Resolve DNSLink ${S}`,e.resolveDNSLink.bind(e,S,i));if(m.push(E),E.error!=null)throw E.error;d=E.result}else d=await e.resolveDNSLink(S,i);u=d?.cid,f=d?.path,o.trace("resolved %s to %c",S,u)}catch(E){if(i?.signal?.aborted)throw new ft(i?.signal?.reason);o.error('could not resolve DnsLink for "%s"',a,E),h.push(E)}}}if(u==null)throw h.length===1?h[0]:(h.push(new Error(`Invalid resource. Cannot determine CID from URL "${r}".`)),h);let g=Ree(d);d!=null&&(g=g??60*2,o.trace("caching %s resolved to %s with TTL: %s",a,u,g),MU.set(a,d,g*1e3));let w={};if(l!=null&&l.length>0){let x=l.split("&");for(let S of x){let[E,b]=S.split("=");w[E]=decodeURIComponent(b)}w.download!=null&&(w.download=w.download==="true"),w.filename!=null&&(w.filename=w.filename.toString())}return{protocol:s,cid:u,path:Bee(f,c??""),query:w,ttl:g,ipfsPath:`/${s}/${a}${c!=null&&c!==""?`/${c}`:""}`,serverTimings:m}}function Bee(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 FU(r){return r.match(/\.[a-zA-Z0-9]{1,4}$/)!=null||r.endsWith("/")?r:`${r}/`}async function $U({resource:r,options:e,logger:t,cid:n,fetch:i=globalThis.fetch}){let o=t.forComponent("helia:verified-fetch:get-redirect-response");if(typeof r!="string"||e==null||["ipfs://","ipns://"].some(u=>r.startsWith(u)))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 o.trace("no redirect info found in headers"),null;o.trace("checking for redirect info");try{let u=Jm(r),f=new URL(r),h=a??f.host,d=new URL(f);if(u.protocol==="ipfs"&&n.version===0?d.host=`${n.toV1()}.ipfs.${h}`:d.host=`${u.cidOrPeerIdOrDnsLink}.${u.protocol}.${h}`,c?.includes(u.protocol)===!0&&d.host.includes(c))return o.trace("request was for a subdomain already, not setting location header"),null;if(c!=null&&!d.host.includes(c))return o.trace("host header is not the same as the subdomain url host, not setting location header"),null;if(f.host===d.host)return o.trace("req url is the same as the subdomain url, not setting location header"),null;d.pathname=FU(f.pathname.replace(`/${u.cidOrPeerIdOrDnsLink}`,"").replace(`/${u.protocol}`,"")),o.trace("subdomain url %s",d.href);let m=new URL(f,`${f.protocol}//${h}`);m.pathname=FU(f.pathname),o.trace("path url %s",m.href);try{let g=await i(d,{method:"HEAD"});if(g.ok)return o("subdomain supported, redirecting to subdomain"),Mm(r.toString(),d.href);throw o("subdomain not supported, subdomain failed with status %s %s",g.status,g.statusText),new Y6("subdomain not supported")}catch(g){return o("subdomain not supported",g),m.href===f.href?(o("path url is the same as the request url, not setting location header"),null):Mm(r.toString(),m.href)}}catch(u){o.error("error setting location header for x-forwarded-host",u)}return null}async function HU(r,{ipns:e,logger:t},{withServerTiming:n=!1,...i}={withServerTiming:!1}){if(typeof r=="string")return UU({urlString:r,ipns:e,logger:t,withServerTiming:n},i);let o=W.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ipfsPath:`/ipfs/${o.toString()}`,ttl:29030400,serverTimings:[]};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function VU(r){let e=W.asCID(r);if(e!=null)return`ipfs://${e}`;try{return`ipfs://${W.parse(r.toString())}`}catch{}let{protocol:t,cidOrPeerIdOrDnsLink:n}=Jm(r.toString());return`${t}://${n}`}var Lee=100,Mee=60*1e3;function Uee(r){if(r==null)return;let e;return r?.signal===null?e=void 0:e=r?.signal,{...r,signal:e}}var o8=class{helia;ipns;log;contentTypeParser;blockstoreSessions;serverTimingHeaders=[];withServerTiming;plugins=[];constructor({helia:e,ipns:t},n){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipns=t??aL(e),this.contentTypeParser=n?.contentTypeParser??EU,this.blockstoreSessions=new Ru({maxSize:n?.sessionCacheSize??Lee,maxAge:n?.sessionTTLms??Mee,onEviction:(a,c)=>{c.close()}}),this.withServerTiming=n?.withServerTiming??!1;let i={...n,logger:A_("helia:verified-fetch"),getBlockstore:(a,c,l,u)=>this.getBlockstore(a,c,l,u),handleServerTiming:async(a,c,l)=>this.handleServerTiming(a,c,l,this.withServerTiming),helia:e,contentTypeParser:this.contentTypeParser},o=[new X5(i),new J6(i),new Q5(i),new u5(i),new J5(i),new r8(i),new Z5(i),new E5(i),new G5(i)],s=n?.plugins?.map(a=>a(i))??[];if(s.length>0){let a=new Map(o.map(l=>[l.constructor.name,l])),c=new Map(s.map(l=>[l.constructor.name,l]));this.plugins=o.map(l=>c.get(l.constructor.name)??l),this.plugins.push(...s.filter(l=>!a.has(l.constructor.name)))}else this.plugins=o;this.log.trace("created VerifiedFetch instance")}getBlockstore(e,t,n=!0,i={}){let o=VU(t);if(!n)return this.helia.blockstore;let s=this.blockstoreSessions.get(o);return s==null&&(s=this.helia.blockstore.createSession(e,i),this.blockstoreSessions.set(o,s)),s}async handleServerTiming(e,t,n,i){if(!i)return n();let{error:o,result:s,header:a}=await Zm(e,t,n);if(this.serverTimingHeaders.push(a),o!=null)throw o;return s}handleFinalResponse(e,{query:t,cid:n,reqFormat:i,ttl:o,protocol:s,ipfsPath:a,pathDetails:c,byteRangeContext:l,options:u}={}){if(this.serverTimingHeaders.length>0){let h=this.serverTimingHeaders.join(", ");e.headers.set("Server-Timing",h),this.serverTimingHeaders=[]}if(e.headers.get("Transfer-Encoding")!=="chunked"&&l!=null){let h=l.length;h!=null&&(this.log.trace("Setting Content-Length from byteRangeContext: %d",h),e.headers.set("Content-Length",h.toString()))}let f;if(this.log.trace("checking for content disposition"),t?.download===!0?f="attachment":this.log.trace("download not requested"),t?.filename!=null?(f==null&&(f="inline"),f=`${f}; ${DU(t.filename)}`):this.log.trace("no filename specified in query"),f!=null?e.headers.set("Content-Disposition",f):this.log.trace("no content disposition specified"),n!=null&&e.headers.get("etag")==null&&e.headers.set("etag",xh({cid:c?.terminalElement.cid??n,reqFormat:i,weak:!1})),s!=null&&uL({response:e,ttl:o,protocol:s}),a!=null&&e.headers.set("X-Ipfs-Path",a),e.headers.set("Access-Control-Allow-Origin","*"),e.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),e.headers.set("Access-Control-Allow-Headers","Range, X-Requested-With"),e.headers.set("Access-Control-Expose-Headers","Content-Range, Content-Length, X-Ipfs-Path, X-Stream-Output"),i!=="car"?e.headers.set("Accept-Ranges","bytes"):e.headers.set("Accept-Ranges","none"),u?.method==="HEAD"){let h=e?.headers;return new Response(null,{status:200,headers:h})}return e}async runPluginPipeline(e,t=3){let n,i=0,o=new Set,s=e.modified;for(;i<t;){this.log(`Starting pipeline pass #${i+1}`),i++;let a=this.plugins.filter(u=>!o.has(u.constructor.name)).filter(u=>u.canHandle(e));if(a.length===0){this.log.trace("No plugins can handle the current context.. checking by CID code");let u=this.plugins.filter(f=>f.codes.includes(e.cid.code));if(u.length>0)a.push(...u);else{this.log.trace("No plugins found that can handle request by CID code; exiting pipeline.");break}}this.log.trace("Plugins ready to handle request: ",a.map(u=>u.constructor.name).join(", "));let c=!1,l=!1;for(let u of a){try{this.log.trace("Invoking plugin:",u.constructor.name),o.add(u.constructor.name);let f=await u.handle(e);if(f!=null){n=f,l=!0;break}}catch(f){if(e.options?.signal?.aborted)throw new ft(e.options?.signal?.reason);if(this.log.error("Error in plugin:",u.constructor.name,f),f.name==="PluginFatalError")return f.response??rh(e.resource,"Failed to fetch")}finally{let f=e.modified;c=f!==s,c&&(s=f)}if(n!=null){this.log.trace("Plugin produced final response:",u.constructor.name);break}}if(l&&n!=null)break;if(!c){this.log.trace("No context changes and no final response; exiting pipeline.");break}}return n}async fetch(e,t){if(this.log("fetch %s",e),t?.method==="OPTIONS")return this.handleFinalResponse(new Response(null,{status:200}));let n=Uee(t),i=n?.withServerTiming??this.withServerTiming;n?.onProgress?.(new X("verified-fetch:request:start",{resource:e}));let o;try{o=await this.handleServerTiming("parse-resource","",async()=>HU(e,{ipns:this.ipns,logger:this.helia.logger},{withServerTiming:i,...n}),i),this.serverTimingHeaders.push(...o.serverTimings.map(({header:h})=>h))}catch(h){if(n?.signal?.aborted)throw new ft(n?.signal?.reason);return this.log.error("error parsing resource %s",e,h),this.handleFinalResponse(Lm(e.toString(),h))}n?.onProgress?.(new X("verified-fetch:request:resolve",{cid:o.cid,path:o.path}));let s=LU({query:o.query,headers:n?.headers,logger:this.helia.logger}),a=NU(o.cid,s);if(this.log("output type %s",a),s!=null&&a==null)return this.handleFinalResponse(ra(e.toString()));let c=a?.split(";")[0]??"application/octet-stream",l=await $U({resource:e,options:n,logger:this.helia.logger,cid:o.cid});if(l!=null)return this.handleFinalResponse(l);let u={...o,resource:e.toString(),accept:a,options:n,withServerTiming:i,onProgress:n?.onProgress,modified:0};this.log.trace('finding handler for cid code "%s" and response content type "%s"',o.cid.code,c);let f=await this.runPluginPipeline(u);return n?.onProgress?.(new X("verified-fetch:request:end",{cid:o.cid,path:o.path})),this.handleFinalResponse(f??c5(e.toString()),u)}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};var e0,s8=async function(e,t){return e0==null&&(e0=await ZE()),e0(e,t)};s8.start=async function(){await e0?.start()};s8.stop=async function(){await e0?.stop()};function Fee(r){return"ipfs-_blank"}function $ee(r,e){let t=e.globalData.gatewayURLWithoutSubdomain.host;return`<a class="ipfs-hash" translate="no" href="${e.globalData.gatewayURLWithoutSubdomain.protocol}//${t}/ipfs/${r.hash}?filename=${r.name}">${r.shortHash}</a>`}function Hee(r){let e=r.split("."),t=[];for(let n=e.length-1;n>=0;n--){let i=e[n];if(i==="ipfs"||i==="ipns")break;t.push(i)}return t.reverse(),t.join(".")}function Vee(r){let e;try{e=new URL(r)}catch{e=new URL("https://inbrowser.link")}return e.host=Hee(e.host),e}function zee(r){return r.path!=null?`Index of <a href="${`${r.globalData.gatewayURL}/${r.path}`}">${r.name}</a>`:`Index of ${r.name} ${r.path}`}function Kee(r){return r.listing.map(e=>`<div class="type-icon">
|
|
86
|
+
`));return R(e)}function e8(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),R(t).byteLength!==t.length)return null;for(;R(t).byteLength>100;){let i=t.indexOf("/");if(i===-1)return null;n+=n!==""?"/"+t.slice(0,i):t.slice(0,i),t=t.slice(i+1)}return R(t).byteLength>100||R(n).byteLength>155||r.linkname!=null&&R(r.linkname).byteLength>100?null:(e.set(R(t),0),e.set(Ic(r.mode&iee,6),100),e.set(Ic(r.uid,6),108),e.set(Ic(r.gid,6),116),e.set(Ic(r.size,11),124),e.set(Ic(r.mtime.getTime()/1e3|0,11),136),e[156]=tee+aee(r.type),r.linkname!=null&&e.set(R(r.linkname),157),e.set(ree,oee),e.set(nee,see),r.uname!=null&&e.set(R(r.uname),265),r.gname!=null&&e.set(R(r.gname),297),e.set(Ic(r.devmajor??0,6),329),e.set(Ic(r.devminor??0,6),337),n!=null&&e.set(R(n),345),e.set(Ic(cee(e),6),148),e)}var{S_IFMT:uee,S_IFBLK:fee,S_IFCHR:dee,S_IFDIR:hee,S_IFIFO:pee,S_IFLNK:mee}=CU.default,gee=parseInt("755",8),yee=parseInt("644",8),kU=new Uint8Array(1024);function wee(r=0){switch(r&uee){case fee:return"block-device";case dee:return"character-device";case hee:return"directory";case pee:return"fifo";case mee:return"symlink";default:return"file"}}function XE(r){return r&=511,r!==0?kU.subarray(0,512-r):new Uint8Array(0)}function GE(r){if(r.pax==null){let e=e8(r);if(e!=null)return e}return xee(r)}function xee(r){let e=TU(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 ge(e8(t)??new Uint8Array(0),e,XE(e.length),e8({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function t8(){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??wee(e.mode),mode:e.mode??(e.type==="directory"?gee:yee),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=R(t)),t instanceof Uint8Array||bi(t)){n.size=t.length,yield GE(n),yield bi(t)?t.subarray():t,yield XE(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=q(await IU(t)),yield GE(n);continue}if(yield GE(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let i=0;for await(let o of t??[])i+=o.length,yield bi(o)?o.subarray():o;if(i!==n.size)throw new Error(`size mismatch, wrote ${i} of ${n.size} bytes`);yield XE(n.size)}yield kU}}var bee=["file","raw","directory"];function vee(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 PU(r){if(!bee.includes(r.type))throw new gi(`${r.type} is not a UnixFS node`);let e={header:vee(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*RU(r,e,t){let n=await gr(r,e,t);if(n.type==="file"||n.type==="raw"){yield*pt([PU(n)],t8());return}if(n.type==="directory"){yield*pt(ch(r,e,t),i=>qt(i,o=>PU(o)),t8());return}throw new gi("Not a UnixFS node")}var r8=class extends Lt{id="tar-plugin";codes=[];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/x-tar"||n.format==="tar"}async handle(e){let{cid:t,path:n,resource:i,options:o,pathDetails:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.terminalElement.cid??t;if(c.code!==st&&c.code!==Et)return ra("only UnixFS data can be returned in a TAR file");e.reqFormat="tar",e.query.download=!0,e.query.filename=e.query.filename??`${c.toString()}.tar`;let l=a(c,i,o?.session,o),u=Bm(RU(`/ipfs/${t}/${n}`,l,o));e.byteRangeContext.setBody(u);let f=cn(i,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:this.log});return f.headers.set("content-type","application/x-tar"),f.headers.set("etag",xh({cid:c,reqFormat:e.reqFormat,weak:!0})),f}};function DU(r){let e=Eee(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function Eee(r){return r.replace(/[^\x00-\x7F]/g,"_")}var See={[Rn]:["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"],[so]:["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"],[Bo]:["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"],[st]:["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"],[Et]:["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 NU(r,e){let t=See[r.code];if(e!=null)return Aee(e,t)}function Aee(r,e){let t=r.split(",").map(n=>{let i=n.trim().split(";");return{mimeType:`${i[0]}`.trim(),weight:_ee(i[1])}}).sort((n,i)=>n.weight===i.weight?0:n.weight>i.weight?-1:1).map(n=>n.mimeType);for(let n of t)for(let i of e)if(n.includes(i)||n==="*/*"||n.startsWith("*/")&&i.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&i.split("/")[0]===n.split("/")[0])return i}function _ee(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 n8={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 OU(r){if(r!=null)return n8[r]}function YE(r){let e=r.get("accept");return!!(e!=null&&Object.values(n8).includes(e))}function QE(r){let e=r?.format;return!!(e!=null&&Object.keys(n8).includes(e))}function BU({query:r,headers:e}){return YE(e)||QE(r)}function LU({query:r,headers:e,logger:t}){let n=t.forComponent("helia:verified-fetch:get-resolved-accept-header"),i=new Headers(e),o=i.get("accept")??void 0;if(o!=null&&n('incoming accept header "%s"',o),!BU({query:r,headers:i}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",o),o;let s=OU(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=o;return!YE(i)&&QE(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 Zm(r,e,t){let n=performance.now();try{let i=await t(),s=(performance.now()-n).toFixed(1),a=`${r};dur=${s};desc="${e}"`;return{result:i,header:a,error:null}}catch(i){let s=(performance.now()-n).toFixed(1),a=`${r};dur=${s};desc="${e}"`;return{result:null,error:i,header:a}}}var i8=class{lru;constructor(e){this.lru=new Ru({maxSize:e})}get(e){return this.lru.get(e)}set(e,t,n){this.lru.set(e,t,{maxAge:Date.now()+n})}has(e){return this.get(e)!=null}remove(e){this.lru.delete(e)}clear(){this.lru.clear()}};var MU=new i8(1e3),Iee=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,Tee=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,Cee=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,kee=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function Pee(r){let e=r?.protocol;if(e==null)return!1;let t=r?.cidOrPeerIdOrDnsLink;if(t==null)return!1;let n=r?.path,i=r?.queryString;return["ipns","ipfs"].includes(e)&&typeof t=="string"&&(n==null||typeof n=="string")&&(i==null||typeof i=="string")}function Jm(r){for(let e of[kee,Iee,Cee,Tee]){let t=r.match(e);if(Pee(t?.groups))return t.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function Ree(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 Dee=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function Nee(r){return Dee.test(r)&&r.includes("-")&&!r.includes(".")}function Oee(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function UU({urlString:r,ipns:e,logger:t,withServerTiming:n=!1},i){let o=t.forComponent("helia:verified-fetch:parse-url-string"),{protocol:s,cidOrPeerIdOrDnsLink:a,path:c,queryString:l}=Jm(r),u,f,h=[],d,m=[];if(s==="ipfs")try{u=W.parse(a)}catch(x){o.error(x),h.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(d=MU.get(a),d!=null)u=d.cid,f=d.path,o.trace("resolved %s to %c from cache",a,u);else{o.trace("Attempting to resolve PeerId for %s",a);let x;try{x=Y5(a);let S=x?.publicKey;if(S==null)throw new TypeError("cidOrPeerIdOrDnsLink contains no public key");if(n){let E=async()=>e.resolve(S,i),b=await Zm("ipns.resolve",`Resolve IPNS name ${a}`,E);if(m.push(b),b.error!=null)throw b.error;d=b.result}else d=await e.resolve(S,i);u=d?.cid,f=d?.path,o.trace("resolved %s to %c",a,u)}catch(S){if(i?.signal?.aborted)throw new ft(i?.signal?.reason);x==null?(o.error('could not parse PeerId string "%s"',a,S),h.push(new TypeError(`Could not parse PeerId in ipns url "${a}", ${S.message}`))):(o.error("could not resolve PeerId %c",x,S),h.push(new TypeError(`Could not resolve PeerId "${a}": ${S.message}`)))}if(u==null){let S=a;Nee(a)&&(S=Oee(a),o.trace('decoded dnslink from "%s" to "%s"',a,S)),o.trace("Attempting to resolve DNSLink for %s",S);try{if(n){let E=await Zm("ipns.resolveDNSLink",`Resolve DNSLink ${S}`,e.resolveDNSLink.bind(e,S,i));if(m.push(E),E.error!=null)throw E.error;d=E.result}else d=await e.resolveDNSLink(S,i);u=d?.cid,f=d?.path,o.trace("resolved %s to %c",S,u)}catch(E){if(i?.signal?.aborted)throw new ft(i?.signal?.reason);o.error('could not resolve DnsLink for "%s"',a,E),h.push(E)}}}if(u==null)throw h.length===1?h[0]:(h.push(new Error(`Invalid resource. Cannot determine CID from URL "${r}".`)),h);let g=Ree(d);d!=null&&(g=g??60*2,o.trace("caching %s resolved to %s with TTL: %s",a,u,g),MU.set(a,d,g*1e3));let w={};if(l!=null&&l.length>0){let x=l.split("&");for(let S of x){let[E,b]=S.split("=");w[E]=decodeURIComponent(b)}w.download!=null&&(w.download=w.download==="true"),w.filename!=null&&(w.filename=w.filename.toString())}return{protocol:s,cid:u,path:Bee(f,c??""),query:w,ttl:g,ipfsPath:`/${s}/${a}${c!=null&&c!==""?`/${c}`:""}`,serverTimings:m}}function Bee(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 FU(r){return r.match(/\.[a-zA-Z0-9]{1,4}$/)!=null||r.endsWith("/")?r:`${r}/`}async function $U({resource:r,options:e,logger:t,cid:n,fetch:i=globalThis.fetch}){let o=t.forComponent("helia:verified-fetch:get-redirect-response");if(typeof r!="string"||e==null||["ipfs://","ipns://"].some(u=>r.startsWith(u)))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 o.trace("no redirect info found in headers"),null;o.trace("checking for redirect info");try{let u=Jm(r),f=new URL(r),h=a??f.host,d=new URL(f);if(u.protocol==="ipfs"&&n.version===0?d.host=`${n.toV1()}.ipfs.${h}`:d.host=`${u.cidOrPeerIdOrDnsLink}.${u.protocol}.${h}`,c?.includes(u.protocol)===!0&&d.host.includes(c))return o.trace("request was for a subdomain already, not setting location header"),null;if(c!=null&&!d.host.includes(c))return o.trace("host header is not the same as the subdomain url host, not setting location header"),null;if(f.host===d.host)return o.trace("req url is the same as the subdomain url, not setting location header"),null;d.pathname=FU(f.pathname.replace(`/${u.cidOrPeerIdOrDnsLink}`,"").replace(`/${u.protocol}`,"")),o.trace("subdomain url %s",d.href);let m=new URL(f,`${f.protocol}//${h}`);m.pathname=FU(f.pathname),o.trace("path url %s",m.href);try{let g=await i(d,{method:"HEAD"});if(g.ok)return o("subdomain supported, redirecting to subdomain"),Mm(r.toString(),d.href);throw o("subdomain not supported, subdomain failed with status %s %s",g.status,g.statusText),new Y6("subdomain not supported")}catch(g){return o("subdomain not supported",g),m.href===f.href?(o("path url is the same as the request url, not setting location header"),null):Mm(r.toString(),m.href)}}catch(u){o.error("error setting location header for x-forwarded-host",u)}return null}async function HU(r,{ipns:e,logger:t},{withServerTiming:n=!1,...i}={withServerTiming:!1}){if(typeof r=="string")return UU({urlString:r,ipns:e,logger:t,withServerTiming:n},i);let o=W.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ipfsPath:`/ipfs/${o.toString()}`,ttl:29030400,serverTimings:[]};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function VU(r){let e=W.asCID(r);if(e!=null)return`ipfs://${e}`;try{return`ipfs://${W.parse(r.toString())}`}catch{}let{protocol:t,cidOrPeerIdOrDnsLink:n}=Jm(r.toString());return`${t}://${n}`}var Lee=100,Mee=60*1e3;function Uee(r){if(r==null)return;let e;return r?.signal===null?e=void 0:e=r?.signal,{...r,signal:e}}var o8=class{helia;ipns;log;contentTypeParser;blockstoreSessions;serverTimingHeaders=[];withServerTiming;plugins=[];constructor({helia:e,ipns:t},n){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipns=t??aL(e),this.contentTypeParser=n?.contentTypeParser??EU,this.blockstoreSessions=new Ru({maxSize:n?.sessionCacheSize??Lee,maxAge:n?.sessionTTLms??Mee,onEviction:(a,c)=>{c.close()}}),this.withServerTiming=n?.withServerTiming??!1;let i={...n,logger:A_("helia:verified-fetch"),getBlockstore:(a,c,l,u)=>this.getBlockstore(a,c,l,u),handleServerTiming:async(a,c,l)=>this.handleServerTiming(a,c,l,this.withServerTiming),helia:e,contentTypeParser:this.contentTypeParser},o=[new X5(i),new J6(i),new Q5(i),new u5(i),new J5(i),new r8(i),new Z5(i),new E5(i),new G5(i)],s=n?.plugins?.map(a=>a(i))??[];if(s.length>0){let a=new Map(o.map(l=>[l.id,l])),c=new Map(s.map(l=>[l.id,l]));this.plugins=o.map(l=>c.get(l.id)??l),this.plugins.push(...s.filter(l=>!a.has(l.id)))}else this.plugins=o;this.log.trace("created VerifiedFetch instance")}getBlockstore(e,t,n=!0,i={}){let o=VU(t);if(!n)return this.helia.blockstore;let s=this.blockstoreSessions.get(o);return s==null&&(s=this.helia.blockstore.createSession(e,i),this.blockstoreSessions.set(o,s)),s}async handleServerTiming(e,t,n,i){if(!i)return n();let{error:o,result:s,header:a}=await Zm(e,t,n);if(this.serverTimingHeaders.push(a),o!=null)throw o;return s}handleFinalResponse(e,{query:t,cid:n,reqFormat:i,ttl:o,protocol:s,ipfsPath:a,pathDetails:c,byteRangeContext:l,options:u}={}){if(this.serverTimingHeaders.length>0){let h=this.serverTimingHeaders.join(", ");e.headers.set("Server-Timing",h),this.serverTimingHeaders=[]}if(e.headers.get("Transfer-Encoding")!=="chunked"&&l!=null){let h=l.length;h!=null&&(this.log.trace("Setting Content-Length from byteRangeContext: %d",h),e.headers.set("Content-Length",h.toString()))}let f;if(this.log.trace("checking for content disposition"),t?.download===!0?f="attachment":this.log.trace("download not requested"),t?.filename!=null?(f==null&&(f="inline"),f=`${f}; ${DU(t.filename)}`):this.log.trace("no filename specified in query"),f!=null?e.headers.set("Content-Disposition",f):this.log.trace("no content disposition specified"),n!=null&&e.headers.get("etag")==null&&e.headers.set("etag",xh({cid:c?.terminalElement.cid??n,reqFormat:i,weak:!1})),s!=null&&uL({response:e,ttl:o,protocol:s}),a!=null&&e.headers.set("X-Ipfs-Path",a),e.headers.set("Access-Control-Allow-Origin","*"),e.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),e.headers.set("Access-Control-Allow-Headers","Range, X-Requested-With"),e.headers.set("Access-Control-Expose-Headers","Content-Range, Content-Length, X-Ipfs-Path, X-Stream-Output"),i!=="car"?e.headers.set("Accept-Ranges","bytes"):e.headers.set("Accept-Ranges","none"),u?.method==="HEAD"){let h=e?.headers;return new Response(null,{status:200,headers:h})}return e}async runPluginPipeline(e,t=3){let n,i=0,o=new Set,s=e.modified;for(;i<t;){this.log(`Starting pipeline pass #${i+1}`),i++;let a=this.plugins.filter(u=>!o.has(u.id)).filter(u=>u.canHandle(e));if(a.length===0){this.log.trace("No plugins can handle the current context.. checking by CID code");let u=this.plugins.filter(f=>f.codes.includes(e.cid.code));if(u.length>0)a.push(...u);else{this.log.trace("No plugins found that can handle request by CID code; exiting pipeline.");break}}this.log.trace("Plugins ready to handle request: ",a.map(u=>u.id).join(", "));let c=!1,l=!1;for(let u of a){try{this.log.trace("Invoking plugin:",u.id),o.add(u.id);let f=await u.handle(e);if(f!=null){n=f,l=!0;break}}catch(f){if(e.options?.signal?.aborted)throw new ft(e.options?.signal?.reason);if(this.log.error("Error in plugin:",u.constructor.name,f),f.name==="PluginFatalError")return f.response??rh(e.resource,"Failed to fetch")}finally{let f=e.modified;c=f!==s,c&&(s=f)}if(n!=null){this.log.trace("Plugin produced final response:",u.id);break}}if(l&&n!=null)break;if(!c){this.log.trace("No context changes and no final response; exiting pipeline.");break}}return n}async fetch(e,t){if(this.log("fetch %s",e),t?.method==="OPTIONS")return this.handleFinalResponse(new Response(null,{status:200}));let n=Uee(t),i=n?.withServerTiming??this.withServerTiming;n?.onProgress?.(new X("verified-fetch:request:start",{resource:e}));let o;try{o=await this.handleServerTiming("parse-resource","",async()=>HU(e,{ipns:this.ipns,logger:this.helia.logger},{withServerTiming:i,...n}),i),this.serverTimingHeaders.push(...o.serverTimings.map(({header:h})=>h))}catch(h){if(n?.signal?.aborted)throw new ft(n?.signal?.reason);return this.log.error("error parsing resource %s",e,h),this.handleFinalResponse(Lm(e.toString(),h))}n?.onProgress?.(new X("verified-fetch:request:resolve",{cid:o.cid,path:o.path}));let s=LU({query:o.query,headers:n?.headers,logger:this.helia.logger}),a=NU(o.cid,s);if(this.log("output type %s",a),s!=null&&a==null)return this.handleFinalResponse(ra(e.toString()));let c=a?.split(";")[0]??"application/octet-stream",l=await $U({resource:e,options:n,logger:this.helia.logger,cid:o.cid});if(l!=null)return this.handleFinalResponse(l);let u={...o,resource:e.toString(),accept:a,options:n,withServerTiming:i,onProgress:n?.onProgress,modified:0};this.log.trace('finding handler for cid code "%s" and response content type "%s"',o.cid.code,c);let f=await this.runPluginPipeline(u);return n?.onProgress?.(new X("verified-fetch:request:end",{cid:o.cid,path:o.path})),this.handleFinalResponse(f??c5(e.toString()),u)}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};var e0,s8=async function(e,t){return e0==null&&(e0=await ZE()),e0(e,t)};s8.start=async function(){await e0?.start()};s8.stop=async function(){await e0?.stop()};function Fee(r){return"ipfs-_blank"}function $ee(r,e){let t=e.globalData.gatewayURLWithoutSubdomain.host;return`<a class="ipfs-hash" translate="no" href="${e.globalData.gatewayURLWithoutSubdomain.protocol}//${t}/ipfs/${r.hash}?filename=${r.name}">${r.shortHash}</a>`}function Hee(r){let e=r.split("."),t=[];for(let n=e.length-1;n>=0;n--){let i=e[n];if(i==="ipfs"||i==="ipns")break;t.push(i)}return t.reverse(),t.join(".")}function Vee(r){let e;try{e=new URL(r)}catch{e=new URL("https://inbrowser.link")}return e.host=Hee(e.host),e}function zee(r){return r.path!=null?`Index of <a href="${`${r.globalData.gatewayURL}/${r.path}`}">${r.name}</a>`:`Index of ${r.name} ${r.path}`}function Kee(r){return r.listing.map(e=>`<div class="type-icon">
|
|
87
87
|
<div class="${Fee(e.name)}"> </div>
|
|
88
88
|
</div>
|
|
89
89
|
<div>
|
|
@@ -405,7 +405,7 @@ a=ice-pwd:`+e+t),r}var oE=R("libp2p-webrtc-noise:");function IB(r,e,t){let n=r.t
|
|
|
405
405
|
.dn-mobile {
|
|
406
406
|
display: none;
|
|
407
407
|
}
|
|
408
|
-
}`;async function Gee(r){let e=r.reduce((n,i)=>`${n}${i.name}${i.cid.toString()}`,""),t=await $e.encode(new TextEncoder().encode(e));return er.encode(t)}var t0=class extends Lt{codes=[st];canHandle(e){let{cid:t,pathDetails:n,directoryEntries:i}=e;return n==null||n.terminalElement?.type!=="directory"||i==null||i.length===0?!1:t.code===st}async handle(e){let{resource:t,pathDetails:n,directoryEntries:i}=e,{terminalElement:o,ipfsRoots:s}=n,c=zU(o,i,{gatewayURL:t,log:this.log});e.byteRangeContext.setBody(c);let l=`DirIndex-${await Gee(i)}_CID-`;return cn(t,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:this.log},{headers:{"Content-Type":"text/html","Cache-Control":"public, max-age=604800, stale-while-revalidate=2678400","X-Ipfs-Roots":mE(s),Etag:xh({cid:o.cid,reqFormat:e.reqFormat,contentPrefix:l})}})}},KU=r=>new t0(r);async function ZE(r,e){let t;if(!Xee(r)){let o=Yee(r?.dnsResolvers),s=ZB();s.dns=o;let a=r?.routers??["https://delegated-ipfs.dev"];for(let u=0;u<a.length;u++){let f=a[u];s.services[`delegatedRouting${u}`]=()=>Ig(f)}r?.libp2pConfig!=null&&Object.assign(s,r.libp2pConfig),t=await Qy(s);let c=[Sp()],l=[Mp(t)];(r?.gateways==null||r.gateways.length>0)&&(c.push(Rp({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})),l.push(Lp({gateways:r?.gateways??["https://trustless-gateway.link"]}))),r=await QB({libp2p:t,blockBrokers:c,dns:o,routers:l,hashers:r?.hashers}),r.logger.forComponent("helia:verified-fetch").trace("created verified-fetch with libp2p config: %j",s)}let n=new o8({helia:r},e);async function i(o,s){return n.fetch(o,s)}return i.start=n.start.bind(n),i.stop=n.stop.bind(n),i}function Xee(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function Yee(r){if(r!=null)return Array.isArray(r)?nl({resolvers:{".":r}}):nl({resolvers:r})}return oF(Qee);})();
|
|
408
|
+
}`;async function Gee(r){let e=r.reduce((n,i)=>`${n}${i.name}${i.cid.toString()}`,""),t=await $e.encode(new TextEncoder().encode(e));return er.encode(t)}var t0=class extends Lt{id="dir-index-html-plugin";codes=[st];canHandle(e){let{cid:t,pathDetails:n,directoryEntries:i}=e;return n==null||n.terminalElement?.type!=="directory"||i==null||i.length===0?!1:t.code===st}async handle(e){let{resource:t,pathDetails:n,directoryEntries:i}=e,{terminalElement:o,ipfsRoots:s}=n,c=zU(o,i,{gatewayURL:t,log:this.log});e.byteRangeContext.setBody(c);let l=`DirIndex-${await Gee(i)}_CID-`;return cn(t,e.byteRangeContext.getBody(),{byteRangeContext:e.byteRangeContext,log:this.log},{headers:{"Content-Type":"text/html","Cache-Control":"public, max-age=604800, stale-while-revalidate=2678400","X-Ipfs-Roots":mE(s),Etag:xh({cid:o.cid,reqFormat:e.reqFormat,contentPrefix:l})}})}},KU=r=>new t0(r);async function ZE(r,e){let t;if(!Xee(r)){let o=Yee(r?.dnsResolvers),s=ZB();s.dns=o;let a=r?.routers??["https://delegated-ipfs.dev"];for(let u=0;u<a.length;u++){let f=a[u];s.services[`delegatedRouting${u}`]=()=>Ig(f)}r?.libp2pConfig!=null&&Object.assign(s,r.libp2pConfig),t=await Qy(s);let c=[Sp()],l=[Mp(t)];(r?.gateways==null||r.gateways.length>0)&&(c.push(Rp({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})),l.push(Lp({gateways:r?.gateways??["https://trustless-gateway.link"]}))),r=await QB({libp2p:t,blockBrokers:c,dns:o,routers:l,hashers:r?.hashers}),r.logger.forComponent("helia:verified-fetch").trace("created verified-fetch with libp2p config: %j",s)}let n=new o8({helia:r},e);async function i(o,s){return n.fetch(o,s)}return i.start=n.start.bind(n),i.stop=n.stop.bind(n),i}function Xee(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function Yee(r){if(r!=null)return Array.isArray(r)?nl({resolvers:{".":r}}):nl({resolvers:r})}return oF(Qee);})();
|
|
409
409
|
/*! Bundled license information:
|
|
410
410
|
|
|
411
411
|
pvtsutils/build/index.js:
|