@helia/mfs 8.0.8 → 8.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -9,6 +9,6 @@ ${e}`)}`:n!=null?`${n.split(`
9
9
  ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function xd(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function su(r,e=""){if(xd(r)){let t=iu(r,e);return r.errors.length>0?(e=`${e} `,t+=`
10
10
  ${e}${r.errors.map(n=>`${su(n,`${e}`)}`).join(`
11
11
  ${e}`)}`):t+=`
12
- ${e}[Error list was empty]`,t.trim()}return iu(r,e)}ae.formatters.e=r=>r==null?"undefined":su(r);function _d(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function M(r,e){let t=_d(`${r}:trace`);return ae.enabled(`${r}:trace`)&&ae.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=ae(`${r}:trace`,e)),Object.assign(ae(r,e),{error:ae(`${r}:error`,e),trace:t,newScope:n=>M(`${r}:${n}`,e)})}function ou(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Lo=Rr(cn(),1);function ri(r){function e(t){return t instanceof ti?t:new ti(t,r)}return e}var ti=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?Te([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new Do(t);this._buffers.push(n),this._availableBits+=n.availableBits()}},Ed=[255,254,252,248,240,224,192,128],kd=[1,3,7,15,31,63,127,255],Do=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=Sd(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 Sd(r,e,t){let n=vd(e,t);return(r&n)>>>e}function vd(r,e){return Ed[r]&kd[Math.min(e+r-1,7)]}var au=BigInt(wt.code),Be=8;async function ni(r){return(await wt.encode(r)).subarray(0,8).reverse()}var cu=Rr(cn(),1);var qe=async(r,e,t)=>{t.codec==null&&(t.codec=O);let n=await fe.digest(r),i=S.create(t.cidVersion??1,t.codec.code,n);return await e.put(i,r,{...t,signal:t.signal}),i};var No=M("helia:unixfs:commands:utils:hamt-utils"),ii=(r,e=Be)=>{let t=(Math.pow(2,e)-1).toString(16).length;return r.toString(16).toUpperCase().padStart(t,"0").substring(0,t)},uu=async(r,e,t)=>{let n=new xr({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 Se(n.flush(r));if(i==null)throw new Error("Flushing shard yielded no result");return i},oi=async(r,e,t)=>{let n=k.unmarshal(r[0].node.Data??new Uint8Array(0)),i=BigInt(Math.pow(2,t.shardFanoutBits??Be));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()),h=new k({type:"hamt-sharded-directory",data:u,fanout:i,hashType:au});c&&(h.mtime=n.mtime,h.mode=n.mode),s={Data:h.marshal(),Links:l.node.Links};let d=I(U(s));if(o=await qe(d,e,t),!c){let p=r[a+1];if(p==null)throw new Error("Was not operating on shard root but also had no parent?");No("updating link in parent sub-shard with prefix %s",p.prefix),p.node.Links=p.node.Links.filter(_=>_.Name!==p.prefix),p.node.Links.push({Name:p.prefix,Hash:o,Tsize:l.node.Links.reduce((_,g)=>_+(g.Tsize??0),d.byteLength)})}}if(o==null||s==null)throw new Error("Noting persisted");return{cid:o,node:s}},si=async(r,e,t,n)=>{let o=ri(ni)(D(e)),s=[],a=n.shardFanoutBits??Be;for(;;){let c=await v(t.get(r,n)),l=q(c),u=new cu.default,h=await o.take(a),d=ii(h,a);s.push({prefix:d,children:u,node:l});let p;for(let g of l.Links){let m=g.Name??"";if(m.length<d.length)throw new Error("Invalid HAMT - link name was too short");let w=parseInt(m.substring(0,d.length),16);u.set(w,!0),m.startsWith(d)&&(p=g)}if(p==null){No("no link found with prefix %s for %s",d,e);break}let _=p.Name??"";if(_.length<d.length)throw new Error("Invalid HAMT - link name was too short");if(_.length===d.length){r=p.Hash,No("descend into sub-shard with prefix %s",_);continue}break}return{path:s,hash:o}};var ai=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};async function ci(r,e,t){if(r.Data==null)throw new Error("DagPB node had no data");let n=t.shardSplitThresholdBytes??262144,i=t.shardSplitStrategy??"links-bytes";t.profile==="unixfs-v0-2015"&&(i="links-bytes");let o=k.unmarshal(r.Data);if(!o.isDirectory())throw new Error("Can only estimate the size of directories or shards");if(i!=="links-bytes"&&i!=="block-bytes")throw new ai(`Invalid shard split threshold "${i}"`);let s=0;return o.type==="directory"?s=i==="links-bytes"?Bd(r):Ad(o,r):o.type==="hamt-sharded-directory"&&(s=i==="links-bytes"?await lu(r,0,n,e,t):await fu(r,br(o.mode,o.mtime),n,e,t)),s>n}function Bd(r){let e=0;for(let t of r.Links)e+=$e(t.Name??""),e+=t.Hash.byteLength;return e}function Ad(r,e){let t=br(r.mode,r.mtime);for(let n of e.Links)t+=wr($e(n.Name??""),n.Hash.byteLength,Number(n.Tsize??0));return t}async function lu(r,e,t,n,i){if(e>t)return t;if(r.Data==null||!k.unmarshal(r.Data).isDirectory())return e;let s=(Math.pow(2,i.shardFanoutBits??Be)-1).toString(16).length;for(let a of r.Links){let c=a.Name??"";if(c=c.substring(s),e+=$e(c),e+=a.Hash.bytes.byteLength,a.Hash.code===$){let l=await v(n.get(a.Hash,i)),u=q(l);e+=await lu(u,e,t,n,i)}}return e}async function fu(r,e,t,n,i){if(e>t)return t;if(r.Data==null||!k.unmarshal(r.Data).isDirectory())return e;let s=(Math.pow(2,i.shardFanoutBits??Be)-1).toString(16).length;for(let a of r.Links){let c=a.Name??"";if(c=c.substring(s),e+=wr($e(c),a.Hash.byteLength,Number(a.Tsize??0)),a.Hash.code===$){let l=await v(n.get(a.Hash,i)),u=q(l);e+=await fu(u,e,t,n,i)}}return e}var Pe=M("helia:unixfs:components:utils:add-link");async function Xt(r,e,t,n){if(r.node.Data==null)throw new L("Invalid parent passed to addLink");if(k.unmarshal(r.node.Data).type==="hamt-sharded-directory")return Pe("adding link to sharded directory"),Dd(r,e,t,n);Pe(`adding ${e.Name} (${e.Hash}) to regular directory`);let o=await Cd(r,e,t,n);if(await ci(o.node,t,n)){Pe("converting directory to sharded directory");let s=await Td(o,t,n);o.cid=s.cid,o.node=q(await v(t.get(s.cid,n)))}return o}var Td=async(r,e,t)=>{if(r.node.Data==null)throw new L("Invalid parent passed to convertToShardedDirectory");let n=k.unmarshal(r.node.Data),i=await uu(e,r.node.Links.map(o=>({name:o.Name??"",size:BigInt(o.Tsize??0),cid:o.Hash})),{...t,mode:n.mode,mtime:n.mtime,cidVersion:r.cid.version});return Pe(`converted directory to sharded directory ${i.cid}`),i},Cd=async(r,e,t,n)=>{let i=r.node.Links.filter(u=>{let h=u.Name===e.Name;if(h&&!n.allowOverwriting)throw new xt;return!h});if(i.push(e),r.node.Data==null)throw new ie("Parent node with no data passed to addToDirectory");let o=k.unmarshal(r.node.Data),s;if(o.mtime!=null){let u=Date.now(),h=Math.floor(u/1e3);o.mtime={secs:BigInt(h),nsecs:(u-h*1e3)*1e3},s=o.marshal()}else s=r.node.Data;r.node=U({Data:s,Links:i});let a=I(r.node),c=await fe.digest(a);n?.signal?.throwIfAborted();let l=S.create(r.cid.version,$,c);return await t.put(l,a,n),{node:r.node,cid:l}},Dd=async(r,e,t,n)=>{let{path:i,hash:o}=await si(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);Pe("next prefix for %s is %s",e.Name,a);let l=`${a}${e.Name}`,u=s.node.Links.find(d=>(d.Name??"").startsWith(a)),h=a.length;if(u!=null)if(Pe("link %s was present in shard",l),u.Name===l){if(!n.allowOverwriting)throw new xt;Pe("overwriting %s in sub-shard",e.Name),s.node.Links=s.node.Links.filter(d=>d.Name!==l),s.node.Links.push({Name:l,Hash:e.Hash,Tsize:e.Tsize})}else{if(u.Name?.length===h)throw new Error("Existing link was sub-shard?!");{Pe("prefix %s already exists, creating new sub-shard",a);let d=s.node.Links.findIndex(E=>E.Name?.startsWith(a)),p=s.node.Links.splice(d,1)[0],_=(p.Name??"").substring(h),m=ri(ni)(D(_)),w=n.shardFanoutBits??Be;for(let E=0;E<i.length;E++)await m.take(w),n?.signal?.throwIfAborted();for(;;){let E=await m.take(w);n?.signal?.throwIfAborted();let B=ii(E,w);p.Name=`${B}${_}`;let z=await o.take(w);n?.signal?.throwIfAborted();let C=ii(z,w);if(B===C){let H=new Lo.default;H.set(z,!0),i.push({prefix:C,children:H,node:{Links:[]}});continue}let Z=new Lo.default;Z.set(z,!0),Z.set(E,!0),i.push({prefix:a,children:Z,node:{Links:[p,{Name:`${C}${e.Name}`,Hash:e.Hash,Tsize:e.Tsize}]}});break}}}else Pe("link %s was not present in sub-shard",l),e.Name=l,s.node.Links.push(e),s.children.set(c,!0),Pe("adding %s to existing sub-shard",l);return oi(i,t,n)};async function ft(r,e,t={}){let n=await R(r,e,t);if(n.type!=="directory")throw new ot(`${r.toString()} was not a UnixFS directory`);return{cid:r,node:n.node}}async function Zt(r,e,t,n){let i=await R(r,t,n);if(i.type!=="directory"&&i.type!=="file"&&i.type!=="raw")throw new Le(`${r.toString()} was not a UnixFS node`);return{Name:e,Tsize:i.node instanceof Uint8Array?i.node.byteLength:Nd(i.node),Hash:r}}function Nd(r){let e=r.Links.reduce((t,n)=>t+(n.Tsize??0),0);return I(r).byteLength+e}var Ld=M("helia:unixfs:components:utils:resolve");async function Ue(r,e,t,n){if(e==null||e==="")return{cid:r};let i=`/ipfs/${r}${e==null?"":`/${e}`}`,o=await na(jn(i,t,n));if(o.length===0)throw new Oe("Could not find path in directory");return Ld("resolved %s to %c",e,r),{cid:o[o.length-1].cid,path:e,segments:o}}async function Qt(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([ft(o.cid,t,n),Zt(i.cid,i.name,t,n)]);r=(await Xt(s,a,t,{...n,allowOverwriting:!0,cidVersion:r.version})).cid,o.cid=r,i=o}return r}async function*hu(r,e,t={}){let n=await Ue(r,t.path,e,t),i=await R(n.cid,e,t);if(i.type!=="file"&&i.type!=="raw")throw new dn;if(i.content==null)throw new hn;yield*i.content(t)}var Fd=M("helia:unixfs:chmod");async function du(r,e,t,n={}){let i=await Ue(r,n.path,t,n);if(Fd("chmod %c %d",i.cid,e),n.recursive===!0){let h=await Yt(async function*(){for await(let d of Zn(i.cid,t,n)){let p,_=[],g=await R(d.cid,t,n);if(g.type==="raw")p=new k({type:"file",data:g.node});else if(g.type==="file"||g.type==="directory")p=g.unixfs,_=g.node.Links;else throw new Le;p.mode=e;let m={Data:p.marshal(),Links:_};yield{path:d.path,content:m}}},d=>bt(d,t,{...n,dagBuilder:async function*(p,_){for await(let g of p)yield async function(){let m=g.content,w=I(m),E=await qe(w,_,{...n,cidVersion:r.version});if(m.Data==null)throw new ie(`${E} had no data`);let B=k.unmarshal(m.Data);return{cid:E,size:BigInt(w.length),path:g.path,unixfs:B}}}}),async d=>Se(d));if(h==null)throw new it(`Could not chmod ${i.cid.toString()}`);return Qt(h.cid,i,t,n)}let o=await v(t.get(i.cid,n)),s,a=[];if(i.cid.code===J)s=new k({type:"file",data:o});else{let h=q(o);if(h.Data==null)throw new ie(`${i.cid.toString()} had no data`);a=h.Links,s=k.unmarshal(h.Data)}s.mode=e;let c=I({Data:s.marshal(),Links:a}),l=await fe.digest(c),u=S.create(i.cid.version,$,l);return await t.put(u,c),Qt(u,i,t,n)}var zd=M("helia:unixfs:cp");async function mu(r,e,t,n,i={}){if(t.includes("/"))throw new L("Name must not have slashes");let[o,s]=await Promise.all([ft(e,n,i),Zt(r,t,n,i)]);return zd('Adding %c as "%s" to %c',r,t,e),(await Xt(o,s,n,{allowOverwriting:i.force,cidVersion:e.version,...i})).cid}async function*pu(r,e,t={}){let n=await Ue(r,t.path,e,t),i=await R(n.cid,e,t);if(i.type==="directory"){yield*i.entries(t);return}yield i}var yu=M("helia:unixfs:mkdir");async function gu(r,e,t,n={}){if(e.includes("/"))throw new L("Path must not have slashes");if((await R(r,t,n)).type!=="directory")throw new ot(`${r.toString()} was not a UnixFS directory`);yu("creating %s",e);let s={Data:new k({type:"directory",mode:n.mode,mtime:n.mtime}).marshal(),Links:[]},a=I(s),c=await fe.digest(a),l=S.create(n.cidVersion??1,$,c);await t.put(l,a);let[u,h]=await Promise.all([ft(r,t,n),Zt(l,e,t,n)]);return yu("adding empty dir called %s to %c",e,r),(await Xt(u,h,t,{...n,allowOverwriting:n.force})).cid}var ui=M("helia:unixfs:utils:remove-link");async function wu(r,e,t,n){if(r.node.Data==null)throw new ie("Parent node had no data");if(k.unmarshal(r.node.Data).type==="hamt-sharded-directory"){ui(`removing ${e} from sharded directory`);let o=await Ud(r,e,t,n);return await ci(o.node,t,n)?o:(ui("converting shard to flat directory %c",r.cid),Rd(o,t,n))}return ui(`removing link ${e} regular directory`),Pd(r,e,t,n)}var Pd=async(r,e,t,n)=>{r.node.Links=r.node.Links.filter(s=>s.Name!==e);let i=I(r.node),o=await qe(i,t,{...n,cidVersion:r.cid.version});return ui(`Updated regular directory ${o}`),{node:r.node,cid:o}},Ud=async(r,e,t,n)=>{let{path:i}=await si(r.cid,e,t,n),o=i[i.length-1];if(o==null)throw new Error("Invalid HAMT, could not generate path");let s=(Math.pow(2,n.shardFanoutBits??Be)-1).toString(16).length,a=o.node.Links.filter(u=>(u.Name??"").substring(s)===e).map(u=>u.Name).pop();if(a==null)throw new Error("File not found");let c=a.substring(0,s),l=parseInt(c,16);if(o.node.Links=o.node.Links.filter(u=>u.Name!==a),o.children.unset(l),o.node.Links.length===1)for(;i.length!==1;){let u=i[i.length-1];if(u==null||u.node.Links.length>1)break;i.pop();let h=i[i.length-1];if(h==null)break;let d=u.node.Links[0];h.node.Links=h.node.Links.filter(p=>!(p.Name??"").startsWith(h.prefix)),h.node.Links.push({Hash:d.Hash,Name:`${h.prefix}${(d.Name??"").substring(s)}`,Tsize:d.Tsize})}return oi(i,t,n)},Rd=async(r,e,t)=>{if(r.node.Data==null)throw new L("Invalid parent passed to convertToFlatDirectory");let n={Links:[]},i=await R(r.cid,e,t);if(i.type!=="directory")throw new Error("Unexpected node type");for await(let c of i.entries()){let l=0,u=await R(c.cid,e,t);u.node instanceof Uint8Array?l=u.node.byteLength:l=I(u.node).length,n.Links.push({Hash:c.cid,Name:c.name,Tsize:l})}let o=k.unmarshal(r.node.Data);n.Data=new k({type:"directory",mode:o.mode,mtime:o.mtime}).marshal();let s=I(U(n));return{cid:await qe(s,e,{codec:O,cidVersion:r.cid.version,signal:t.signal}),node:n}};var Md=M("helia:unixfs:rm");async function bu(r,e,t,n={}){if(e.includes("/"))throw new L("Name must not have slashes");let i=await ft(r,t,n);return Md("Removing %s from %c",e,r),(await wu(i,e,t,{...n,cidVersion:r.version})).cid}var Fo={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},xu={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},_u=new globalThis.TextEncoder;function $d(r,e){let t=Fo[e],n=xu[e];for(let i=0;i<r.length;i++)n^=BigInt(r[i]),n=BigInt.asUintN(e,n*t);return n}function Od(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Fo[e],i=xu[e],o=r;for(;o.length>0;){let s=_u.encodeInto(o,t);o=o.slice(s.read);for(let a=0;a<s.written;a++)i^=BigInt(t[a]),i=BigInt.asUintN(e,i*n)}return i}function zo(r,{size:e=32,utf8Buffer:t}={}){if(!Fo[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Od(r,e,t);r=_u.encode(r)}return $d(r,e)}var Nr={hash:r=>Number(zo(r,{size:32})),hashV:(r,e)=>Hd(Nr.hash(r,e))};function Hd(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),D(e,"base16")}var Eu=64,Ae=class{fp;h;seed;constructor(e,t,n,i=2){if(i>Eu)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),s=_e(i);for(let a=0;a<s.length;a++)s[a]=o[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Vr(this.fp,e.fp):!1}};function St(r,e){return Math.floor(Math.random()*(e-r))+r}var vt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Ae))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Ae))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Ae))throw new TypeError("Invalid Fingerprint");let t=St(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Ae))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Vd=500,Lr=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??Nr,this.seed=e.seed??St(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=D(e));let t=new Ae(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new vt(this.bucketSize)),this.buckets[i]==null&&(this.buckets[i]=new vt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[i].add(t))return this.count++,!0;let o=[n,i],s=o[St(0,o.length-1)];this.buckets[s]==null&&(this.buckets[s]=new vt(this.bucketSize));for(let a=0;a<Vd;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new vt(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=D(e));let t=new Ae(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.has(t)??!1;if(i)return i;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=D(e));let t=new Ae(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.remove(t)??!1;if(i)return this.count--,i;let o=(n^t.hash())%this.filterSize,s=this.buckets[o]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}};var Fr=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??Nr,this.seed=e.seed??St(0,Math.pow(2,10)),this.filterSeries=[new Lr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=D(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Lr({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function ku(r,e="utf8"){let t=Qr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Su=1877,li=1604,jd=M("helia:unixfs:stat");async function vu(r,e,t={}){let n=await Ue(r,t.path,e,t);jd("stat %c",n.cid);let i=await R(n.cid,e,t);if(i.type==="raw")return t.extended===!0?Kd(i):Gd(i);if(i.type==="file"||i.type==="directory")return t.extended===!0?Wd(i,e,t.filter??new Fr({filterSize:1024}),t):qd(i);throw new Le}function qd(r){return{type:r.type,cid:r.cid,unixfs:r.unixfs,mode:r.unixfs.mode??(r.unixfs.isDirectory()?Su:li),mtime:r.unixfs.mtime,size:r.unixfs.fileSize()}}async function Wd(r,e,t,n){let i=await Iu(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()?Su:li),mtime:r.unixfs.mtime,localSize:i.localSize,dagSize:i.dagSize,deduplicatedDagSize:i.deduplicatedDagSize,blocks:i.blocks,uniqueBlocks:i.uniqueBlocks}}function Gd(r){return{type:r.type,cid:r.cid,unixfs:void 0,mode:li,mtime:void 0,size:BigInt(r.node.byteLength)}}function Kd(r){return{type:r.type,cid:r.cid,unixfs:void 0,mode:li,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 Iu(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 v(e.get(r,i));if(o.blocks++,o.dagSize+=BigInt(a.byteLength),s||(o.uniqueBlocks++,o.deduplicatedDagSize+=BigInt(a.byteLength)),r.code===J)o.localSize+=BigInt(a.byteLength),t&&(o.dirSize+=BigInt(a.byteLength));else if(r.code===$){let c=q(a),l;if(c.Data!=null&&(l=k.unmarshal(c.Data)),c.Links.length>0){for(let u of c.Links){let h=await Iu(u.Hash,e,Yd(u,l),n,i);o.localSize+=h.localSize,o.dagSize+=h.dagSize,o.deduplicatedDagSize+=h.deduplicatedDagSize,o.blocks+=h.blocks,o.uniqueBlocks+=h.uniqueBlocks,o.dirSize+=h.dirSize}t&&l!=null&&(o.dirSize+=l.fileSize())}else{if(l==null)throw new ie(`PBNode ${r.toString()} had no data`);l.data!=null&&(o.localSize+=BigInt(l.data.byteLength??0)),t&&(o.dirSize+=l.fileSize())}}else throw new it(`${r.toString()} was neither DAG_PB nor RAW`)}catch(s){if(s.name!=="NotFoundError"&&s.name!=="BlockNotFoundWhileOfflineError"||i.offline!==!0)throw s}return o}function Yd(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 Jd=M("helia:unixfs:touch");async function Bu(r,e,t={}){let n=await Ue(r,t.path,e,t),i=t.mtime??{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(Jd("touch %c %o",n.cid,i),t.recursive){let h=await Yt(async function*(){for await(let d of Zn(n.cid,e)){let p,_,g=await R(d.cid,e,t);if(g.type==="raw")p=new k({data:g.node}),_=[];else if(g.type==="file"||g.type==="directory")p=g.unixfs,_=g.node.Links;else throw new Le;p.mtime=i;let m={Data:p.marshal(),Links:_};yield{path:d.path,content:m}}},d=>bt(d,e,{...t,dagBuilder:async function*(p,_){for await(let g of p)yield async function(){let m=g.content,w=I(m),E=await qe(w,_,{...t,cidVersion:r.version});if(m.Data==null)throw new ie(`${E} had no data`);let B=k.unmarshal(m.Data);return{cid:E,size:BigInt(w.length),path:g.path,unixfs:B}}}}),async d=>Se(d));if(h==null)throw new it(`Could not chmod ${n.cid.toString()}`);return Qt(h.cid,n,e,t)}let o=await v(e.get(n.cid,t)),s,a=[];if(n.cid.code===J)s=new k({data:o});else{let h=q(o);if(a=h.Links,h.Data==null)throw new ie(`${n.cid.toString()} had no data`);s=k.unmarshal(h.Data)}s.mtime=i;let c=I({Data:s.marshal(),Links:a}),l=await fe.digest(c),u=S.create(n.cid.version,$,l);return await e.put(u,c),Qt(u,n,e,t)}var fi=class{components;constructor(e){this.components=e}async*addAll(e,t={}){yield*mn(e,this.components.blockstore,t)}async addBytes(e,t={}){return wa(e,this.components.blockstore,t)}async addByteStream(e,t={}){return ba(e,this.components.blockstore,t)}async addFile(e,t={}){return xa(e,this.components.blockstore,t)}async addDirectory(e={},t={}){return _a(e,this.components.blockstore,t)}async*cat(e,t={}){yield*hu(e,this.components.blockstore,t)}async chmod(e,t,n={}){return du(e,t,this.components.blockstore,n)}async cp(e,t,n,i={}){return mu(e,t,n,this.components.blockstore,i)}async*ls(e,t={}){yield*pu(e,this.components.blockstore,t)}async mkdir(e,t,n={}){return gu(e,t,this.components.blockstore,n)}async rm(e,t,n={}){return bu(e,t,this.components.blockstore,n)}async stat(e,t={}){return vu(e,this.components.blockstore,t)}async touch(e,t={}){return Bu(e,this.components.blockstore,t)}};function Au(r){return new fi(r)}var We="/",Tu=new TextEncoder().encode(We),hi=Tu[0],zr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==hi)throw new Error("Invalid key")}toString(e="utf8"){return ku(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(We))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Tu),this._buf[0]!==hi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(hi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===hi;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let o=t[i],s=n[i];if(o<s)return!0;if(o>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(We).slice(1)}type(){return Xd(this.baseNamespace())}name(){return Zd(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(We)||(e+=We),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(We):new r(e.slice(0,-1).join(We))}child(e){return this.toString()===We?e:e.toString()===We?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Qd(e.map(t=>t.namespaces()))])}};function Xd(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Zd(r){let e=r.split(":");return e[e.length-1]}function Qd(r){return[].concat(...r)}function di(r){return r.split("/").pop()??""}var mi=class{components;unixfs;root;key;log;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("helia:mfs"),this.key=new zr(t.key??"/locals/filesroot"),this.unixfs=Au(e)}async#e(){if(this.root==null)try{let e=await this.components.datastore.get(this.key);this.root=S.decode(e)}catch(e){if(e.name!=="NotFoundError")throw e;this.root=await this.unixfs.addDirectory()}return this.root}async writeBytes(e,t,n){let i=await this.unixfs.addBytes(e,n);await this.cp(i,t,n),n?.mode!=null&&await this.chmod(t,n.mode,n),n?.mtime!=null&&await this.touch(t,n)}async writeByteStream(e,t,n){let i=await this.unixfs.addByteStream(e,n);await this.cp(i,t,n),n?.mode!=null&&await this.chmod(t,n.mode,n),n?.mtime!=null&&await this.touch(t,n)}async*cat(e,t={}){let n=await this.#e(),i=await this.#t(n,e,{...t,createMissingDirectories:!1,finalSegmentMustBeDirectory:!1});yield*this.unixfs.cat(i[i.length-1].cid,t)}async chmod(e,t,n={}){let i=await this.#e();this.root=await this.unixfs.chmod(i,t,{...n,path:e})}async cp(e,t,n){let i=await this.#e(),o=n?.force??!1;typeof e=="string"&&(e=(await this.stat(e,n)).cid),o||await this.#u(t,n);let s=di(t),a=t.substring(0,t.length-`/${s}`.length),c=[{cid:i,name:""}];a!==""&&(c=await this.#t(i,a,{...n,createMissingDirectories:n?.force??!1,finalSegmentMustBeDirectory:!0})),c.push({cid:e,name:s}),this.root=await this.#n(c,n)}async*ls(e,t){let n=await this.#e();t?.path!=null&&(e=`${e}/${t.path}`);let i=n.toString();yield*Gn(this.unixfs.ls(n,{...t,path:e}),o=>{let s=o.path.split("/").slice(1).join("/");return s.startsWith(i)&&(s=s.substring(0,i.length)),{...o,path:`${e==="/"?"":e}/${s}`}})}async mkdir(e,t){let n=t?.force??!1;n||await this.#u(e,t);let i=di(e),o=e.substring(0,e.length-`/${i}`.length),s=await this.#e(),a=[{cid:s,name:""}];o!==""&&(a=await this.#t(s,o,{...t,createMissingDirectories:n,finalSegmentMustBeDirectory:!0})),a.push({cid:await this.unixfs.addDirectory({mode:t?.mode,mtime:t?.mtime},t),name:di(e)}),this.root=await this.#n(a,t)}async rm(e,t){(t?.force??!1)||await this.#c(e,t);let i=await this.#e(),o=await this.#t(i,e,{...t,createMissingDirectories:!1,finalSegmentMustBeDirectory:!1}),s=o.pop();if(s==null)throw new L("path was too short");let a=o[o.length-1];a.cid=await this.unixfs.rm(a.cid,s.name,t),this.root=await this.#n(o,t)}async stat(e,t){let n=await this.#e(),o=(await this.#t(n,e,{...t,createMissingDirectories:!1,finalSegmentMustBeDirectory:!1})).pop();if(o==null)throw new Oe;return this.unixfs.stat(o.cid,t)}async touch(e,t){let n=await this.#e(),i=await this.#t(n,e,{...t,createMissingDirectories:!1,finalSegmentMustBeDirectory:!1}),o=i[i.length-1];if(o==null)throw new Oe;o.cid=await this.unixfs.touch(o.cid,t),this.root=await this.#n(i,t)}async#t(e,t,n){if(!t.startsWith("/"))throw new L("path must be absolute");let i=await this.unixfs.stat(e,{...n,offline:!0}),o=[{cid:e,name:"",unixfs:i.unixfs}],s=e,a=t.split("/").filter(Boolean);for(let l=0;l<a.length;l++){let u=a[l];try{let h=await this.unixfs.stat(s,{...n,offline:!0,path:u});o.push({cid:h.cid,name:u,unixfs:h.unixfs}),s=h.cid}catch{if(this.log.error("could not resolve path segment %s of %s under %c",u,t,e),n.createMissingDirectories){let d=await this.unixfs.addDirectory();o.push({cid:d,name:u,unixfs:new k({type:"directory"})})}else throw new Oe(`${t} does not exist`)}}let c=o[o.length-1];if(n.finalSegmentMustBeDirectory&&c.unixfs?.isDirectory()!==!0)throw new ot(`${t} was not a directory`);return o}async#n(e,t={}){let n=e.pop();if(n==null)throw new L("path was too short");let i=n.cid;for(let o=e.length-1;o>-1;o--){let s=e[o];s.cid=await this.unixfs.cp(n.cid,s.cid,n.name,{...t,force:!0}),n=s,i=s.cid}return await this.components.datastore.put(this.key,i.bytes,t),i}async#c(e,t={}){if(!await this.#f(e,t))throw new Oe}async#u(e,t={}){if(await this.#f(e,t))throw new xt}async#f(e,t={}){try{return await this.stat(e,{...t,offline:!0}),!0}catch{return!1}}};function em(r,e={}){return new mi(r,e)}return zu(tm);})();
12
+ ${e}[Error list was empty]`,t.trim()}return iu(r,e)}ae.formatters.e=r=>r==null?"undefined":su(r);function _d(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function M(r,e){let t=_d(`${r}:trace`);return ae.enabled(`${r}:trace`)&&ae.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=ae(`${r}:trace`,e)),Object.assign(ae(r,e),{error:ae(`${r}:error`,e),trace:t,newScope:n=>M(`${r}:${n}`,e)})}function ou(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Lo=Rr(cn(),1);function ri(r){function e(t){return t instanceof ti?t:new ti(t,r)}return e}var ti=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?Te([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new Do(t);this._buffers.push(n),this._availableBits+=n.availableBits()}},Ed=[255,254,252,248,240,224,192,128],kd=[1,3,7,15,31,63,127,255],Do=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=Sd(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 Sd(r,e,t){let n=vd(e,t);return(r&n)>>>e}function vd(r,e){return Ed[r]&kd[Math.min(e+r-1,7)]}var au=BigInt(wt.code),Be=8;async function ni(r){return(await wt.encode(r)).subarray(0,8).reverse()}var cu=Rr(cn(),1);var qe=async(r,e,t)=>{t.codec==null&&(t.codec=O);let n=await fe.digest(r),i=S.create(t.cidVersion??1,t.codec.code,n);return await e.put(i,r,{...t,signal:t.signal}),i};var No=M("helia:unixfs:commands:utils:hamt-utils"),ii=(r,e=Be)=>{let t=(Math.pow(2,e)-1).toString(16).length;return r.toString(16).toUpperCase().padStart(t,"0").substring(0,t)},uu=async(r,e,t)=>{let n=new xr({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 Se(n.flush(r));if(i==null)throw new Error("Flushing shard yielded no result");return i},oi=async(r,e,t)=>{let n=k.unmarshal(r[0].node.Data??new Uint8Array(0)),i=BigInt(Math.pow(2,t.shardFanoutBits??Be));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()),h=new k({type:"hamt-sharded-directory",data:u,fanout:i,hashType:au});c&&(h.mtime=n.mtime,h.mode=n.mode),s={Data:h.marshal(),Links:l.node.Links};let d=I(U(s));if(o=await qe(d,e,t),!c){let p=r[a+1];if(p==null)throw new Error("Was not operating on shard root but also had no parent?");No("updating link in parent sub-shard with prefix %s",p.prefix),p.node.Links=p.node.Links.filter(_=>_.Name!==p.prefix),p.node.Links.push({Name:p.prefix,Hash:o,Tsize:l.node.Links.reduce((_,g)=>_+(g.Tsize??0),d.byteLength)})}}if(o==null||s==null)throw new Error("Noting persisted");return{cid:o,node:s}},si=async(r,e,t,n)=>{let o=ri(ni)(D(e)),s=[],a=n.shardFanoutBits??Be;for(;;){let c=await v(t.get(r,n)),l=q(c),u=new cu.default,h=await o.take(a),d=ii(h,a);s.push({prefix:d,children:u,node:l});let p;for(let g of l.Links){let m=g.Name??"";if(m.length<d.length)throw new Error("Invalid HAMT - link name was too short");let w=parseInt(m.substring(0,d.length),16);u.set(w,!0),m.startsWith(d)&&(p=g)}if(p==null){No("no link found with prefix %s for %s",d,e);break}let _=p.Name??"";if(_.length<d.length)throw new Error("Invalid HAMT - link name was too short");if(_.length===d.length){r=p.Hash,No("descend into sub-shard with prefix %s",_);continue}break}return{path:s,hash:o}};var ai=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};async function ci(r,e,t){if(r.Data==null)throw new Error("DagPB node had no data");let n=t.shardSplitThresholdBytes??262144,i=t.shardSplitStrategy??"links-bytes";t.profile==="unixfs-v0-2015"&&(i="links-bytes");let o=k.unmarshal(r.Data);if(!o.isDirectory())throw new Error("Can only estimate the size of directories or shards");if(i!=="links-bytes"&&i!=="block-bytes")throw new ai(`Invalid shard split threshold "${i}"`);let s=0;return o.type==="directory"?s=i==="links-bytes"?Bd(r):Ad(o,r):o.type==="hamt-sharded-directory"&&(s=i==="links-bytes"?await lu(r,0,n,e,t):await fu(r,br(o.mode,o.mtime),n,e,t)),s>n}function Bd(r){let e=0;for(let t of r.Links)e+=$e(t.Name??""),e+=t.Hash.byteLength;return e}function Ad(r,e){let t=br(r.mode,r.mtime);for(let n of e.Links)t+=wr($e(n.Name??""),n.Hash.byteLength,Number(n.Tsize??0));return t}async function lu(r,e,t,n,i){if(e>t)return t;if(r.Data==null||!k.unmarshal(r.Data).isDirectory())return e;let s=(Math.pow(2,i.shardFanoutBits??Be)-1).toString(16).length;for(let a of r.Links){let c=a.Name??"";if(c=c.substring(s),e+=$e(c),e+=a.Hash.bytes.byteLength,a.Hash.code===$){let l=await v(n.get(a.Hash,i)),u=q(l);e+=await lu(u,e,t,n,i)}}return e}async function fu(r,e,t,n,i){if(e>t)return t;if(r.Data==null||!k.unmarshal(r.Data).isDirectory())return e;let s=(Math.pow(2,i.shardFanoutBits??Be)-1).toString(16).length;for(let a of r.Links){let c=a.Name??"";if(c=c.substring(s),e+=wr($e(c),a.Hash.byteLength,Number(a.Tsize??0)),a.Hash.code===$){let l=await v(n.get(a.Hash,i)),u=q(l);e+=await fu(u,e,t,n,i)}}return e}var Pe=M("helia:unixfs:components:utils:add-link");async function Xt(r,e,t,n){if(r.node.Data==null)throw new L("Invalid parent passed to addLink");if(k.unmarshal(r.node.Data).type==="hamt-sharded-directory")return Pe("adding link to sharded directory"),Dd(r,e,t,n);Pe(`adding ${e.Name} (${e.Hash}) to regular directory`);let o=await Cd(r,e,t,n);if(await ci(o.node,t,n)){Pe("converting directory to sharded directory");let s=await Td(o,t,n);o.cid=s.cid,o.node=q(await v(t.get(s.cid,n)))}return o}var Td=async(r,e,t)=>{if(r.node.Data==null)throw new L("Invalid parent passed to convertToShardedDirectory");let n=k.unmarshal(r.node.Data),i=await uu(e,r.node.Links.map(o=>({name:o.Name??"",size:BigInt(o.Tsize??0),cid:o.Hash})),{...t,mode:n.mode,mtime:n.mtime,cidVersion:r.cid.version});return Pe(`converted directory to sharded directory ${i.cid}`),i},Cd=async(r,e,t,n)=>{let i=r.node.Links.filter(u=>{let h=u.Name===e.Name;if(h&&!n.allowOverwriting)throw new xt;return!h});if(i.push(e),r.node.Data==null)throw new ie("Parent node with no data passed to addToDirectory");let o=k.unmarshal(r.node.Data),s;if(o.mtime!=null){let u=Date.now(),h=Math.floor(u/1e3);o.mtime={secs:BigInt(h),nsecs:(u-h*1e3)*1e3},s=o.marshal()}else s=r.node.Data;r.node=U({Data:s,Links:i});let a=I(r.node),c=await fe.digest(a);n?.signal?.throwIfAborted();let l=S.create(r.cid.version,$,c);return await t.put(l,a,n),{node:r.node,cid:l}},Dd=async(r,e,t,n)=>{let{path:i,hash:o}=await si(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);Pe("next prefix for %s is %s",e.Name,a);let l=`${a}${e.Name}`,u=s.node.Links.find(d=>(d.Name??"").startsWith(a)),h=a.length;if(u!=null)if(Pe("link %s was present in shard",l),u.Name===l){if(!n.allowOverwriting)throw new xt;Pe("overwriting %s in sub-shard",e.Name),s.node.Links=s.node.Links.filter(d=>d.Name!==l),s.node.Links.push({Name:l,Hash:e.Hash,Tsize:e.Tsize})}else{if(u.Name?.length===h)throw new Error("Existing link was sub-shard?!");{Pe("prefix %s already exists, creating new sub-shard",a);let d=s.node.Links.findIndex(E=>E.Name?.startsWith(a)),p=s.node.Links.splice(d,1)[0],_=(p.Name??"").substring(h),m=ri(ni)(D(_)),w=n.shardFanoutBits??Be;for(let E=0;E<i.length;E++)await m.take(w),n?.signal?.throwIfAborted();for(;;){let E=await m.take(w);n?.signal?.throwIfAborted();let B=ii(E,w);p.Name=`${B}${_}`;let z=await o.take(w);n?.signal?.throwIfAborted();let C=ii(z,w);if(B===C){let H=new Lo.default;H.set(z,!0),i.push({prefix:C,children:H,node:{Links:[]}});continue}let Z=new Lo.default;Z.set(z,!0),Z.set(E,!0),i.push({prefix:a,children:Z,node:{Links:[p,{Name:`${C}${e.Name}`,Hash:e.Hash,Tsize:e.Tsize}]}});break}}}else Pe("link %s was not present in sub-shard",l),e.Name=l,s.node.Links.push(e),s.children.set(c,!0),Pe("adding %s to existing sub-shard",l);return oi(i,t,n)};async function ft(r,e,t={}){let n=await R(r,e,t);if(n.type!=="directory")throw new ot(`${r.toString()} was not a UnixFS directory`);return{cid:r,node:n.node}}async function Zt(r,e,t,n){let i=await R(r,t,n);if(i.type!=="directory"&&i.type!=="file"&&i.type!=="raw")throw new Le(`${r.toString()} was not a UnixFS node`);return{Name:e,Tsize:i.node instanceof Uint8Array?i.node.byteLength:Nd(i.node),Hash:r}}function Nd(r){let e=r.Links.reduce((t,n)=>t+(n.Tsize??0),0);return I(r).byteLength+e}var Ld=M("helia:unixfs:components:utils:resolve");async function Ue(r,e,t,n){if(e==null||e==="")return{cid:r};let i=`/ipfs/${r}${e==null?"":`/${e}`}`,o=await na(jn(i,t,n));if(o.length===0)throw new Oe("Could not find path in directory");return Ld("resolved %s to %c",e,r),{cid:o[o.length-1].cid,path:e,segments:o}}async function Qt(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([ft(o.cid,t,n),Zt(i.cid,i.name,t,n)]);r=(await Xt(s,a,t,{...n,allowOverwriting:!0,cidVersion:r.version})).cid,o.cid=r,i=o}return r}async function*hu(r,e,t={}){let n=await Ue(r,t.path,e,t),i=await R(n.cid,e,t);if(i.type!=="file"&&i.type!=="raw")throw new dn;if(i.content==null)throw new hn;yield*i.content(t)}var Fd=M("helia:unixfs:chmod");async function du(r,e,t,n={}){let i=await Ue(r,n.path,t,n);if(Fd("chmod %c %d",i.cid,e),n.recursive===!0){let h=await Yt(async function*(){for await(let d of Zn(i.cid,t,n)){let p,_=[],g=await R(d.cid,t,n);if(g.type==="raw")p=new k({type:"file",data:g.node});else if(g.type==="file"||g.type==="directory")p=g.unixfs,_=g.node.Links;else throw new Le;p.mode=e;let m={Data:p.marshal(),Links:_};yield{path:d.path,content:m}}},d=>bt(d,t,{...n,dagBuilder:async function*(p,_){for await(let g of p)yield async function(){let m=g.content,w=I(m),E=await qe(w,_,{...n,cidVersion:r.version});if(m.Data==null)throw new ie(`${E} had no data`);let B=k.unmarshal(m.Data);return{cid:E,size:BigInt(w.length),path:g.path,unixfs:B}}}}),async d=>Se(d));if(h==null)throw new it(`Could not chmod ${i.cid.toString()}`);return Qt(h.cid,i,t,n)}let o=await v(t.get(i.cid,n)),s,a=[];if(i.cid.code===J)s=new k({type:"file",data:o});else{let h=q(o);if(h.Data==null)throw new ie(`${i.cid.toString()} had no data`);a=h.Links,s=k.unmarshal(h.Data)}s.mode=e;let c=I({Data:s.marshal(),Links:a}),l=await fe.digest(c),u=S.create(i.cid.version,$,l);return await t.put(u,c),Qt(u,i,t,n)}var zd=M("helia:unixfs:cp");async function mu(r,e,t,n,i={}){if(t.includes("/"))throw new L("Name must not have slashes");let[o,s]=await Promise.all([ft(e,n,i),Zt(r,t,n,i)]);return zd('Adding %c as "%s" to %c',r,t,e),(await Xt(o,s,n,{allowOverwriting:i.force,cidVersion:e.version,...i})).cid}async function*pu(r,e,t={}){let n=await Ue(r,t.path,e,t),i=await R(n.cid,e,t);if(i.type==="directory"){yield*i.entries(t);return}yield i}var yu=M("helia:unixfs:mkdir");async function gu(r,e,t,n={}){if(e.includes("/"))throw new L("Path must not have slashes");if((await R(r,t,n)).type!=="directory")throw new ot(`${r.toString()} was not a UnixFS directory`);yu("creating %s",e);let s={Data:new k({type:"directory",mode:n.mode,mtime:n.mtime}).marshal(),Links:[]},a=I(s),c=await fe.digest(a),l=S.create(n.cidVersion??1,$,c);await t.put(l,a);let[u,h]=await Promise.all([ft(r,t,n),Zt(l,e,t,n)]);return yu("adding empty dir called %s to %c",e,r),(await Xt(u,h,t,{...n,allowOverwriting:n.force})).cid}var ui=M("helia:unixfs:utils:remove-link");async function wu(r,e,t,n){if(r.node.Data==null)throw new ie("Parent node had no data");if(k.unmarshal(r.node.Data).type==="hamt-sharded-directory"){ui(`removing ${e} from sharded directory`);let o=await Ud(r,e,t,n);return await ci(o.node,t,n)?o:(ui("converting shard to flat directory %c",r.cid),Rd(o,t,n))}return ui(`removing link ${e} regular directory`),Pd(r,e,t,n)}var Pd=async(r,e,t,n)=>{r.node.Links=r.node.Links.filter(s=>s.Name!==e);let i=I(r.node),o=await qe(i,t,{...n,cidVersion:r.cid.version});return ui(`Updated regular directory ${o}`),{node:r.node,cid:o}},Ud=async(r,e,t,n)=>{let{path:i}=await si(r.cid,e,t,n),o=i[i.length-1];if(o==null)throw new Error("Invalid HAMT, could not generate path");let s=(Math.pow(2,n.shardFanoutBits??Be)-1).toString(16).length,a=o.node.Links.filter(u=>(u.Name??"").substring(s)===e).map(u=>u.Name).pop();if(a==null)throw new Error("File not found");let c=a.substring(0,s),l=parseInt(c,16);if(o.node.Links=o.node.Links.filter(u=>u.Name!==a),o.children.unset(l),o.node.Links.length===1)for(;i.length!==1;){let u=i[i.length-1];if(u==null||u.node.Links.length>1||(u.node.Links[0].Name??"").length===s)break;i.pop();let h=i[i.length-1];if(h==null)break;let d=u.node.Links[0];h.node.Links=h.node.Links.filter(p=>!(p.Name??"").startsWith(h.prefix)),h.node.Links.push({Hash:d.Hash,Name:`${h.prefix}${(d.Name??"").substring(s)}`,Tsize:d.Tsize})}return oi(i,t,n)},Rd=async(r,e,t)=>{if(r.node.Data==null)throw new L("Invalid parent passed to convertToFlatDirectory");let n={Links:[]},i=await R(r.cid,e,t);if(i.type!=="directory")throw new Error("Unexpected node type");for await(let c of i.entries()){let l=0,u=await R(c.cid,e,t);u.node instanceof Uint8Array?l=u.node.byteLength:l=I(u.node).length,n.Links.push({Hash:c.cid,Name:c.name,Tsize:l})}let o=k.unmarshal(r.node.Data);n.Data=new k({type:"directory",mode:o.mode,mtime:o.mtime}).marshal();let s=I(U(n));return{cid:await qe(s,e,{codec:O,cidVersion:r.cid.version,signal:t.signal}),node:n}};var Md=M("helia:unixfs:rm");async function bu(r,e,t,n={}){if(e.includes("/"))throw new L("Name must not have slashes");let i=await ft(r,t,n);return Md("Removing %s from %c",e,r),(await wu(i,e,t,{...n,cidVersion:r.version})).cid}var Fo={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},xu={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},_u=new globalThis.TextEncoder;function $d(r,e){let t=Fo[e],n=xu[e];for(let i=0;i<r.length;i++)n^=BigInt(r[i]),n=BigInt.asUintN(e,n*t);return n}function Od(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Fo[e],i=xu[e],o=r;for(;o.length>0;){let s=_u.encodeInto(o,t);o=o.slice(s.read);for(let a=0;a<s.written;a++)i^=BigInt(t[a]),i=BigInt.asUintN(e,i*n)}return i}function zo(r,{size:e=32,utf8Buffer:t}={}){if(!Fo[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Od(r,e,t);r=_u.encode(r)}return $d(r,e)}var Nr={hash:r=>Number(zo(r,{size:32})),hashV:(r,e)=>Hd(Nr.hash(r,e))};function Hd(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),D(e,"base16")}var Eu=64,Ae=class{fp;h;seed;constructor(e,t,n,i=2){if(i>Eu)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),s=_e(i);for(let a=0;a<s.length;a++)s[a]=o[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Vr(this.fp,e.fp):!1}};function St(r,e){return Math.floor(Math.random()*(e-r))+r}var vt=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Ae))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Ae))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Ae))throw new TypeError("Invalid Fingerprint");let t=St(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof Ae))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Vd=500,Lr=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??Nr,this.seed=e.seed??St(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=D(e));let t=new Ae(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new vt(this.bucketSize)),this.buckets[i]==null&&(this.buckets[i]=new vt(this.bucketSize)),this.buckets[n].add(t)||this.buckets[i].add(t))return this.count++,!0;let o=[n,i],s=o[St(0,o.length-1)];this.buckets[s]==null&&(this.buckets[s]=new vt(this.bucketSize));for(let a=0;a<Vd;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new vt(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=D(e));let t=new Ae(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.has(t)??!1;if(i)return i;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=D(e));let t=new Ae(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.remove(t)??!1;if(i)return this.count--,i;let o=(n^t.hash())%this.filterSize,s=this.buckets[o]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}};var Fr=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??Nr,this.seed=e.seed??St(0,Math.pow(2,10)),this.filterSeries=[new Lr({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=D(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Lr({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function ku(r,e="utf8"){let t=Qr[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Su=1877,li=1604,jd=M("helia:unixfs:stat");async function vu(r,e,t={}){let n=await Ue(r,t.path,e,t);jd("stat %c",n.cid);let i=await R(n.cid,e,t);if(i.type==="raw")return t.extended===!0?Kd(i):Gd(i);if(i.type==="file"||i.type==="directory")return t.extended===!0?Wd(i,e,t.filter??new Fr({filterSize:1024}),t):qd(i);throw new Le}function qd(r){return{type:r.type,cid:r.cid,unixfs:r.unixfs,mode:r.unixfs.mode??(r.unixfs.isDirectory()?Su:li),mtime:r.unixfs.mtime,size:r.unixfs.fileSize()}}async function Wd(r,e,t,n){let i=await Iu(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()?Su:li),mtime:r.unixfs.mtime,localSize:i.localSize,dagSize:i.dagSize,deduplicatedDagSize:i.deduplicatedDagSize,blocks:i.blocks,uniqueBlocks:i.uniqueBlocks}}function Gd(r){return{type:r.type,cid:r.cid,unixfs:void 0,mode:li,mtime:void 0,size:BigInt(r.node.byteLength)}}function Kd(r){return{type:r.type,cid:r.cid,unixfs:void 0,mode:li,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 Iu(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 v(e.get(r,i));if(o.blocks++,o.dagSize+=BigInt(a.byteLength),s||(o.uniqueBlocks++,o.deduplicatedDagSize+=BigInt(a.byteLength)),r.code===J)o.localSize+=BigInt(a.byteLength),t&&(o.dirSize+=BigInt(a.byteLength));else if(r.code===$){let c=q(a),l;if(c.Data!=null&&(l=k.unmarshal(c.Data)),c.Links.length>0){for(let u of c.Links){let h=await Iu(u.Hash,e,Yd(u,l),n,i);o.localSize+=h.localSize,o.dagSize+=h.dagSize,o.deduplicatedDagSize+=h.deduplicatedDagSize,o.blocks+=h.blocks,o.uniqueBlocks+=h.uniqueBlocks,o.dirSize+=h.dirSize}t&&l!=null&&(o.dirSize+=l.fileSize())}else{if(l==null)throw new ie(`PBNode ${r.toString()} had no data`);l.data!=null&&(o.localSize+=BigInt(l.data.byteLength??0)),t&&(o.dirSize+=l.fileSize())}}else throw new it(`${r.toString()} was neither DAG_PB nor RAW`)}catch(s){if(s.name!=="NotFoundError"&&s.name!=="BlockNotFoundWhileOfflineError"||i.offline!==!0)throw s}return o}function Yd(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 Jd=M("helia:unixfs:touch");async function Bu(r,e,t={}){let n=await Ue(r,t.path,e,t),i=t.mtime??{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(Jd("touch %c %o",n.cid,i),t.recursive){let h=await Yt(async function*(){for await(let d of Zn(n.cid,e)){let p,_,g=await R(d.cid,e,t);if(g.type==="raw")p=new k({data:g.node}),_=[];else if(g.type==="file"||g.type==="directory")p=g.unixfs,_=g.node.Links;else throw new Le;p.mtime=i;let m={Data:p.marshal(),Links:_};yield{path:d.path,content:m}}},d=>bt(d,e,{...t,dagBuilder:async function*(p,_){for await(let g of p)yield async function(){let m=g.content,w=I(m),E=await qe(w,_,{...t,cidVersion:r.version});if(m.Data==null)throw new ie(`${E} had no data`);let B=k.unmarshal(m.Data);return{cid:E,size:BigInt(w.length),path:g.path,unixfs:B}}}}),async d=>Se(d));if(h==null)throw new it(`Could not chmod ${n.cid.toString()}`);return Qt(h.cid,n,e,t)}let o=await v(e.get(n.cid,t)),s,a=[];if(n.cid.code===J)s=new k({data:o});else{let h=q(o);if(a=h.Links,h.Data==null)throw new ie(`${n.cid.toString()} had no data`);s=k.unmarshal(h.Data)}s.mtime=i;let c=I({Data:s.marshal(),Links:a}),l=await fe.digest(c),u=S.create(n.cid.version,$,l);return await e.put(u,c),Qt(u,n,e,t)}var fi=class{components;constructor(e){this.components=e}async*addAll(e,t={}){yield*mn(e,this.components.blockstore,t)}async addBytes(e,t={}){return wa(e,this.components.blockstore,t)}async addByteStream(e,t={}){return ba(e,this.components.blockstore,t)}async addFile(e,t={}){return xa(e,this.components.blockstore,t)}async addDirectory(e={},t={}){return _a(e,this.components.blockstore,t)}async*cat(e,t={}){yield*hu(e,this.components.blockstore,t)}async chmod(e,t,n={}){return du(e,t,this.components.blockstore,n)}async cp(e,t,n,i={}){return mu(e,t,n,this.components.blockstore,i)}async*ls(e,t={}){yield*pu(e,this.components.blockstore,t)}async mkdir(e,t,n={}){return gu(e,t,this.components.blockstore,n)}async rm(e,t,n={}){return bu(e,t,this.components.blockstore,n)}async stat(e,t={}){return vu(e,this.components.blockstore,t)}async touch(e,t={}){return Bu(e,this.components.blockstore,t)}};function Au(r){return new fi(r)}var We="/",Tu=new TextEncoder().encode(We),hi=Tu[0],zr=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==hi)throw new Error("Invalid key")}toString(e="utf8"){return ku(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(We))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Tu),this._buf[0]!==hi){let e=new Uint8Array(this._buf.byteLength+1);e.fill(hi,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===hi;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let o=t[i],s=n[i];if(o<s)return!0;if(o>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(We).slice(1)}type(){return Xd(this.baseNamespace())}name(){return Zd(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(We)||(e+=We),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(We):new r(e.slice(0,-1).join(We))}child(e){return this.toString()===We?e:e.toString()===We?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Qd(e.map(t=>t.namespaces()))])}};function Xd(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Zd(r){let e=r.split(":");return e[e.length-1]}function Qd(r){return[].concat(...r)}function di(r){return r.split("/").pop()??""}var mi=class{components;unixfs;root;key;log;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("helia:mfs"),this.key=new zr(t.key??"/locals/filesroot"),this.unixfs=Au(e)}async#e(){if(this.root==null)try{let e=await this.components.datastore.get(this.key);this.root=S.decode(e)}catch(e){if(e.name!=="NotFoundError")throw e;this.root=await this.unixfs.addDirectory()}return this.root}async writeBytes(e,t,n){let i=await this.unixfs.addBytes(e,n);await this.cp(i,t,n),n?.mode!=null&&await this.chmod(t,n.mode,n),n?.mtime!=null&&await this.touch(t,n)}async writeByteStream(e,t,n){let i=await this.unixfs.addByteStream(e,n);await this.cp(i,t,n),n?.mode!=null&&await this.chmod(t,n.mode,n),n?.mtime!=null&&await this.touch(t,n)}async*cat(e,t={}){let n=await this.#e(),i=await this.#t(n,e,{...t,createMissingDirectories:!1,finalSegmentMustBeDirectory:!1});yield*this.unixfs.cat(i[i.length-1].cid,t)}async chmod(e,t,n={}){let i=await this.#e();this.root=await this.unixfs.chmod(i,t,{...n,path:e})}async cp(e,t,n){let i=await this.#e(),o=n?.force??!1;typeof e=="string"&&(e=(await this.stat(e,n)).cid),o||await this.#u(t,n);let s=di(t),a=t.substring(0,t.length-`/${s}`.length),c=[{cid:i,name:""}];a!==""&&(c=await this.#t(i,a,{...n,createMissingDirectories:n?.force??!1,finalSegmentMustBeDirectory:!0})),c.push({cid:e,name:s}),this.root=await this.#n(c,n)}async*ls(e,t){let n=await this.#e();t?.path!=null&&(e=`${e}/${t.path}`);let i=n.toString();yield*Gn(this.unixfs.ls(n,{...t,path:e}),o=>{let s=o.path.split("/").slice(1).join("/");return s.startsWith(i)&&(s=s.substring(0,i.length)),{...o,path:`${e==="/"?"":e}/${s}`}})}async mkdir(e,t){let n=t?.force??!1;n||await this.#u(e,t);let i=di(e),o=e.substring(0,e.length-`/${i}`.length),s=await this.#e(),a=[{cid:s,name:""}];o!==""&&(a=await this.#t(s,o,{...t,createMissingDirectories:n,finalSegmentMustBeDirectory:!0})),a.push({cid:await this.unixfs.addDirectory({mode:t?.mode,mtime:t?.mtime},t),name:di(e)}),this.root=await this.#n(a,t)}async rm(e,t){(t?.force??!1)||await this.#c(e,t);let i=await this.#e(),o=await this.#t(i,e,{...t,createMissingDirectories:!1,finalSegmentMustBeDirectory:!1}),s=o.pop();if(s==null)throw new L("path was too short");let a=o[o.length-1];a.cid=await this.unixfs.rm(a.cid,s.name,t),this.root=await this.#n(o,t)}async stat(e,t){let n=await this.#e(),o=(await this.#t(n,e,{...t,createMissingDirectories:!1,finalSegmentMustBeDirectory:!1})).pop();if(o==null)throw new Oe;return this.unixfs.stat(o.cid,t)}async touch(e,t){let n=await this.#e(),i=await this.#t(n,e,{...t,createMissingDirectories:!1,finalSegmentMustBeDirectory:!1}),o=i[i.length-1];if(o==null)throw new Oe;o.cid=await this.unixfs.touch(o.cid,t),this.root=await this.#n(i,t)}async#t(e,t,n){if(!t.startsWith("/"))throw new L("path must be absolute");let i=await this.unixfs.stat(e,{...n,offline:!0}),o=[{cid:e,name:"",unixfs:i.unixfs}],s=e,a=t.split("/").filter(Boolean);for(let l=0;l<a.length;l++){let u=a[l];try{let h=await this.unixfs.stat(s,{...n,offline:!0,path:u});o.push({cid:h.cid,name:u,unixfs:h.unixfs}),s=h.cid}catch{if(this.log.error("could not resolve path segment %s of %s under %c",u,t,e),n.createMissingDirectories){let d=await this.unixfs.addDirectory();o.push({cid:d,name:u,unixfs:new k({type:"directory"})})}else throw new Oe(`${t} does not exist`)}}let c=o[o.length-1];if(n.finalSegmentMustBeDirectory&&c.unixfs?.isDirectory()!==!0)throw new ot(`${t} was not a directory`);return o}async#n(e,t={}){let n=e.pop();if(n==null)throw new L("path was too short");let i=n.cid;for(let o=e.length-1;o>-1;o--){let s=e[o];s.cid=await this.unixfs.cp(n.cid,s.cid,n.name,{...t,force:!0}),n=s,i=s.cid}return await this.components.datastore.put(this.key,i.bytes,t),i}async#c(e,t={}){if(!await this.#f(e,t))throw new Oe}async#u(e,t={}){if(await this.#f(e,t))throw new xt}async#f(e,t={}){try{return await this.stat(e,{...t,offline:!0}),!0}catch{return!1}}};function em(r,e={}){return new mi(r,e)}return zu(tm);})();
13
13
  return HeliaMfs}));
14
14
  //# sourceMappingURL=index.min.js.map