@fireproof/core 0.13.3-dev → 0.13.4-dev

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,6 +1,6 @@
1
1
  "use strict";var lw=Object.create;var Io=Object.defineProperty;var fw=Object.getOwnPropertyDescriptor;var dw=Object.getOwnPropertyNames;var hw=Object.getPrototypeOf,pw=Object.prototype.hasOwnProperty;var $=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),G=(t,e)=>{for(var r in e)Io(t,r,{get:e[r],enumerable:!0})},gl=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dw(e))!pw.call(t,o)&&o!==r&&Io(t,o,{get:()=>e[o],enumerable:!(n=fw(e,o))||n.enumerable});return t};var V=(t,e,r)=>(r=t!=null?lw(hw(t)):{},gl(e||!t||!t.__esModule?Io(r,"default",{value:t,enumerable:!0}):r,t)),yw=t=>gl(Io({},"__esModule",{value:!0}),t);var Yf=$((aA,Xf)=>{Xf.exports=Ea;var Jf=128,p0=127,y0=~p0,m0=Math.pow(2,31);function Ea(t,e,r){if(Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw Ea.bytes=0,new RangeError("Could not encode varint");e=e||[],r=r||0;for(var n=r;t>=m0;)e[r++]=t&255|Jf,t/=128;for(;t&y0;)e[r++]=t&255|Jf,t>>>=7;return e[r]=t|0,Ea.bytes=r-n+1,e}});var td=$((cA,ed)=>{ed.exports=Sa;var g0=128,Zf=127;function Sa(t,n){var r=0,n=n||0,o=0,i=n,s,c=t.length;do{if(i>=c||o>49)throw Sa.bytes=0,new RangeError("Could not decode varint");s=t[i++],r+=o<28?(s&Zf)<<o:(s&Zf)*Math.pow(2,o),o+=7}while(s>=g0);return Sa.bytes=i-n,r}});var nd=$((uA,rd)=>{var w0=Math.pow(2,7),b0=Math.pow(2,14),x0=Math.pow(2,21),k0=Math.pow(2,28),v0=Math.pow(2,35),E0=Math.pow(2,42),S0=Math.pow(2,49),A0=Math.pow(2,56),_0=Math.pow(2,63);rd.exports=function(t){return t<w0?1:t<b0?2:t<x0?3:t<k0?4:t<v0?5:t<E0?6:t<S0?7:t<A0?8:t<_0?9:10}});var Go=$((lA,od)=>{od.exports={encode:Yf(),decode:td(),encodingLength:nd()}});var Kh=$(lc=>{lc.encode=function(t){if(isNaN(t))return"DaN";if(t===0)return"FE 0M0";if(t===1/0)return"FF";if(t===-1/0)return"DD";var e=t.toExponential().split("e"),r=Number(e[1])+500,n=e[0]+(e[0].indexOf(".")===-1?".":"")+"0".repeat(20),o="E"+Z1(String(r),3)+"M"+String(n);return t>0?"F"+o:"D"+Wh(o)};lc.decode=function(t){if(t==="DaN")return NaN;if(t==="FF")return 1/0;if(t==="DD")return-1/0;var e=t[0]==="D",r=(e?Wh(t):t).slice(2).split("M");return+((e?"-":"")+r[1]+"e"+String(Number(r[0])-500))};function Wh(t){for(var e="",r=0;r<t.length;r++){var n=t[r];isNaN(Number(n))||n===" "?n!=="-"&&(e+=n):e+=String(9-Number(n))}return e}function Z1(t,e){return" ".repeat(e-t.length).substr(0,e)+t}});var Qh=$(Gh=>{var ex={"?":"?@","!":"??",'"':"?%"};function tx(t){return/[!"]/.test(t)?t.replace(/[\?!"]/g,function(e){return ex[e]}):t}var rx={"?@":"?","??":"!","?%":'"'};function nx(t){return/\?[%\?@]/.test(t)?t.replace(/\?[%\?@]/g,function(e){return rx[e]}):t}Gh.factory=function(t){return{encode:e,decode:n};function e(o){if(o===null)return"A";if(!Array.isArray(o))throw new Error("can only encode arrays");var i=o.length;if(i==0)return"K!";for(var s=r(o[0]),c=1;c<i;c++)s+='"'+r(o[c]);return"K"+s+"!"}function r(o){return typeof o=="object"?e(o):tx(t.encode(o))}function n(o){if(o==="A")return null;if(o==="K!")return[];for(var i=o.split('"'),s=[[]],c,a=0,u=i.length,l=0;l<u;l++){for(var d=i[l],m=d.length,f=0;d[f]=="K";)f++;for(var h=0;d[m-h-1]=="!";)h++;for(var p=d.slice(f,m-h),g=a+f,w=a;w<g;w++)s[w+1]=[],s[w].push(s[w+1]),a=g,c=s[a];p.length!==0&&c.push(t.decode(nx(p)));for(var g=a-h,w=g;w<a;w++)s[w+1]=[],a=g,c=s[a]}return s[0][0]}}});var Xh=$(Q=>{var ox=Kh(),ix=Qh(),tB=Q.flip=function(t){var e=t.toString(),r="";for(var n in e)r+=e[n]=="."?".":9-+e[n];return r};Q.number=ox;Q.string={encode:function(t){return/\x00|\x01/.test(t)?"J"+t.replace(/\x01/g,"").replace(/\x00/g,""):"J"+t},decode:function(t){if(t[0]==="J")return t.substring(1)}};Q.encode=function(t){return Q[typeof t].encode(t)};Q.decode=function(t){if(t==="")return t;if(!Jh[t[0]])throw new Error("no decoder for:"+JSON.stringify(t));return Jh[t[0]](t)};Q.object=ix.factory(Q);Q.boolean={encode:function(t){return t?"C":"B"},decode:function(t){return t==="C"}};Q.undefined={encode:function(t){return"L"},decode:function(){}};var Jh={A:Q.object.decode,B:Q.boolean.decode,C:Q.boolean.decode,D:Q.number.decode,F:Q.number.decode,J:Q.string.decode,K:Q.object.decode,L:Q.undefined.decode};Q.buffer=!1;Q.type="charwise"});var Tp=$((JB,Cp)=>{"use strict";Cp.exports=Rx;function Rx(t,e){for(var r=new Array(arguments.length-1),n=0,o=2,i=!0;o<arguments.length;)r[n++]=arguments[o++];return new Promise(function(c,a){r[n]=function(l){if(i)if(i=!1,l)a(l);else{for(var d=new Array(arguments.length-1),m=0;m<d.length;)d[m++]=arguments[m];c.apply(null,d)}};try{t.apply(e||null,r)}catch(u){i&&(i=!1,a(u))}})}});var Np=$(Dp=>{"use strict";var ji=Dp;ji.length=function(e){var r=e.length;if(!r)return 0;for(var n=0;--r%4>1&&e.charAt(r)==="=";)++n;return Math.ceil(e.length*3)/4-n};var $r=new Array(64),Lp=new Array(123);for(Fe=0;Fe<64;)Lp[$r[Fe]=Fe<26?Fe+65:Fe<52?Fe+71:Fe<62?Fe-4:Fe-59|43]=Fe++;var Fe;ji.encode=function(e,r,n){for(var o=null,i=[],s=0,c=0,a;r<n;){var u=e[r++];switch(c){case 0:i[s++]=$r[u>>2],a=(u&3)<<4,c=1;break;case 1:i[s++]=$r[a|u>>4],a=(u&15)<<2,c=2;break;case 2:i[s++]=$r[a|u>>6],i[s++]=$r[u&63],c=0;break}s>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,i)),s=0)}return c&&(i[s++]=$r[a],i[s++]=61,c===1&&(i[s++]=61)),o?(s&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))};var Ip="invalid encoding";ji.decode=function(e,r,n){for(var o=n,i=0,s,c=0;c<e.length;){var a=e.charCodeAt(c++);if(a===61&&i>1)break;if((a=Lp[a])===void 0)throw Error(Ip);switch(i){case 0:s=a,i=1;break;case 1:r[n++]=s<<2|(a&48)>>4,s=a,i=2;break;case 2:r[n++]=(s&15)<<4|(a&60)>>2,s=a,i=3;break;case 3:r[n++]=(s&3)<<6|a,i=0;break}}if(i===1)throw Error(Ip);return n-o};ji.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var Pp=$((YB,Up)=>{"use strict";Up.exports=Vi;function Vi(){this._listeners={}}Vi.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};Vi.prototype.off=function(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=[];else for(var n=this._listeners[e],o=0;o<n.length;)n[o].fn===r?n.splice(o,1):++o;return this};Vi.prototype.emit=function(e){var r=this._listeners[e];if(r){for(var n=[],o=1;o<arguments.length;)n.push(arguments[o++]);for(o=0;o<r.length;)r[o].fn.apply(r[o++].ctx,n)}return this}});var Hp=$((ZB,$p)=>{"use strict";$p.exports=Fp(Fp);function Fp(t){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function o(a,u,l){e[0]=a,u[l]=r[0],u[l+1]=r[1],u[l+2]=r[2],u[l+3]=r[3]}function i(a,u,l){e[0]=a,u[l]=r[3],u[l+1]=r[2],u[l+2]=r[1],u[l+3]=r[0]}t.writeFloatLE=n?o:i,t.writeFloatBE=n?i:o;function s(a,u){return r[0]=a[u],r[1]=a[u+1],r[2]=a[u+2],r[3]=a[u+3],e[0]}function c(a,u){return r[3]=a[u],r[2]=a[u+1],r[1]=a[u+2],r[0]=a[u+3],e[0]}t.readFloatLE=n?s:c,t.readFloatBE=n?c:s}():function(){function e(n,o,i,s){var c=o<0?1:0;if(c&&(o=-o),o===0)n(1/o>0?0:2147483648,i,s);else if(isNaN(o))n(2143289344,i,s);else if(o>34028234663852886e22)n((c<<31|2139095040)>>>0,i,s);else if(o<11754943508222875e-54)n((c<<31|Math.round(o/1401298464324817e-60))>>>0,i,s);else{var a=Math.floor(Math.log(o)/Math.LN2),u=Math.round(o*Math.pow(2,-a)*8388608)&8388607;n((c<<31|a+127<<23|u)>>>0,i,s)}}t.writeFloatLE=e.bind(null,Mp),t.writeFloatBE=e.bind(null,Rp);function r(n,o,i){var s=n(o,i),c=(s>>31)*2+1,a=s>>>23&255,u=s&8388607;return a===255?u?NaN:c*(1/0):a===0?c*1401298464324817e-60*u:c*Math.pow(2,a-150)*(u+8388608)}t.readFloatLE=r.bind(null,Op),t.readFloatBE=r.bind(null,zp)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function o(a,u,l){e[0]=a,u[l]=r[0],u[l+1]=r[1],u[l+2]=r[2],u[l+3]=r[3],u[l+4]=r[4],u[l+5]=r[5],u[l+6]=r[6],u[l+7]=r[7]}function i(a,u,l){e[0]=a,u[l]=r[7],u[l+1]=r[6],u[l+2]=r[5],u[l+3]=r[4],u[l+4]=r[3],u[l+5]=r[2],u[l+6]=r[1],u[l+7]=r[0]}t.writeDoubleLE=n?o:i,t.writeDoubleBE=n?i:o;function s(a,u){return r[0]=a[u],r[1]=a[u+1],r[2]=a[u+2],r[3]=a[u+3],r[4]=a[u+4],r[5]=a[u+5],r[6]=a[u+6],r[7]=a[u+7],e[0]}function c(a,u){return r[7]=a[u],r[6]=a[u+1],r[5]=a[u+2],r[4]=a[u+3],r[3]=a[u+4],r[2]=a[u+5],r[1]=a[u+6],r[0]=a[u+7],e[0]}t.readDoubleLE=n?s:c,t.readDoubleBE=n?c:s}():function(){function e(n,o,i,s,c,a){var u=s<0?1:0;if(u&&(s=-s),s===0)n(0,c,a+o),n(1/s>0?0:2147483648,c,a+i);else if(isNaN(s))n(0,c,a+o),n(2146959360,c,a+i);else if(s>17976931348623157e292)n(0,c,a+o),n((u<<31|2146435072)>>>0,c,a+i);else{var l;if(s<22250738585072014e-324)l=s/5e-324,n(l>>>0,c,a+o),n((u<<31|l/4294967296)>>>0,c,a+i);else{var d=Math.floor(Math.log(s)/Math.LN2);d===1024&&(d=1023),l=s*Math.pow(2,-d),n(l*4503599627370496>>>0,c,a+o),n((u<<31|d+1023<<20|l*1048576&1048575)>>>0,c,a+i)}}}t.writeDoubleLE=e.bind(null,Mp,0,4),t.writeDoubleBE=e.bind(null,Rp,4,0);function r(n,o,i,s,c){var a=n(s,c+o),u=n(s,c+i),l=(u>>31)*2+1,d=u>>>20&2047,m=4294967296*(u&1048575)+a;return d===2047?m?NaN:l*(1/0):d===0?l*5e-324*m:l*Math.pow(2,d-1075)*(m+4503599627370496)}t.readDoubleLE=r.bind(null,Op,0,4),t.readDoubleBE=r.bind(null,zp,4,0)}(),t}function Mp(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Rp(t,e,r){e[r]=t>>>24,e[r+1]=t>>>16&255,e[r+2]=t>>>8&255,e[r+3]=t&255}function Op(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function zp(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var jp=$((exports,module)=>{"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}});var qp=$(Vp=>{"use strict";var Fc=Vp;Fc.length=function(e){for(var r=0,n=0,o=0;o<e.length;++o)n=e.charCodeAt(o),n<128?r+=1:n<2048?r+=2:(n&64512)===55296&&(e.charCodeAt(o+1)&64512)===56320?(++o,r+=4):r+=3;return r};Fc.read=function(e,r,n){var o=n-r;if(o<1)return"";for(var i=null,s=[],c=0,a;r<n;)a=e[r++],a<128?s[c++]=a:a>191&&a<224?s[c++]=(a&31)<<6|e[r++]&63:a>239&&a<365?(a=((a&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,s[c++]=55296+(a>>10),s[c++]=56320+(a&1023)):s[c++]=(a&15)<<12|(e[r++]&63)<<6|e[r++]&63,c>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),c=0);return i?(c&&i.push(String.fromCharCode.apply(String,s.slice(0,c))),i.join("")):String.fromCharCode.apply(String,s.slice(0,c))};Fc.write=function(e,r,n){for(var o=n,i,s,c=0;c<e.length;++c)i=e.charCodeAt(c),i<128?r[n++]=i:i<2048?(r[n++]=i>>6|192,r[n++]=i&63|128):(i&64512)===55296&&((s=e.charCodeAt(c+1))&64512)===56320?(i=65536+((i&1023)<<10)+(s&1023),++c,r[n++]=i>>18|240,r[n++]=i>>12&63|128,r[n++]=i>>6&63|128,r[n++]=i&63|128):(r[n++]=i>>12|224,r[n++]=i>>6&63|128,r[n++]=i&63|128);return n-o}});var Kp=$((t3,Wp)=>{"use strict";Wp.exports=Ox;function Ox(t,e,r){var n=r||8192,o=n>>>1,i=null,s=n;return function(a){if(a<1||a>o)return t(a);s+a>n&&(i=t(n),s=0);var u=e.call(i,s,s+=a);return s&7&&(s=(s|7)+1),u}}});var Qp=$((r3,Gp)=>{"use strict";Gp.exports=ee;var Wn=ot();function ee(t,e){this.lo=t>>>0,this.hi=e>>>0}var Xt=ee.zero=new ee(0,0);Xt.toNumber=function(){return 0};Xt.zzEncode=Xt.zzDecode=function(){return this};Xt.length=function(){return 1};var zx=ee.zeroHash="\0\0\0\0\0\0\0\0";ee.fromNumber=function(e){if(e===0)return Xt;var r=e<0;r&&(e=-e);var n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new ee(n,o)};ee.from=function(e){if(typeof e=="number")return ee.fromNumber(e);if(Wn.isString(e))if(Wn.Long)e=Wn.Long.fromString(e);else return ee.fromNumber(parseInt(e,10));return e.low||e.high?new ee(e.low>>>0,e.high>>>0):Xt};ee.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var r=~this.lo+1>>>0,n=~this.hi>>>0;return r||(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296};ee.prototype.toLong=function(e){return Wn.Long?new Wn.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var kt=String.prototype.charCodeAt;ee.fromHash=function(e){return e===zx?Xt:new ee((kt.call(e,0)|kt.call(e,1)<<8|kt.call(e,2)<<16|kt.call(e,3)<<24)>>>0,(kt.call(e,4)|kt.call(e,5)<<8|kt.call(e,6)<<16|kt.call(e,7)<<24)>>>0)};ee.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};ee.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this};ee.prototype.zzDecode=function(){var e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this};ee.prototype.length=function(){var e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}});var ot=$(Mc=>{"use strict";var L=Mc;L.asPromise=Tp();L.base64=Np();L.EventEmitter=Pp();L.float=Hp();L.inquire=jp();L.utf8=qp();L.pool=Kp();L.LongBits=Qp();L.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);L.global=L.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||Mc;L.emptyArray=Object.freeze?Object.freeze([]):[];L.emptyObject=Object.freeze?Object.freeze({}):{};L.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};L.isString=function(e){return typeof e=="string"||e instanceof String};L.isObject=function(e){return e&&typeof e=="object"};L.isset=L.isSet=function(e,r){var n=e[r];return n!=null&&e.hasOwnProperty(r)?typeof n!="object"||(Array.isArray(n)?n.length:Object.keys(n).length)>0:!1};L.Buffer=function(){try{var t=L.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();L._Buffer_from=null;L._Buffer_allocUnsafe=null;L.newBuffer=function(e){return typeof e=="number"?L.Buffer?L._Buffer_allocUnsafe(e):new L.Array(e):L.Buffer?L._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};L.Array=typeof Uint8Array<"u"?Uint8Array:Array;L.Long=L.global.dcodeIO&&L.global.dcodeIO.Long||L.global.Long||L.inquire("long");L.key2Re=/^true|false|0|1$/;L.key32Re=/^-?(?:0|[1-9][0-9]*)$/;L.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;L.longToHash=function(e){return e?L.LongBits.from(e).toHash():L.LongBits.zeroHash};L.longFromHash=function(e,r){var n=L.LongBits.fromHash(e);return L.Long?L.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function Jp(t,e,r){for(var n=Object.keys(e),o=0;o<n.length;++o)(t[n[o]]===void 0||!r)&&(t[n[o]]=e[n[o]]);return t}L.merge=Jp;L.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function Xp(t){function e(r,n){if(!(this instanceof e))return new e(r,n);Object.defineProperty(this,"message",{get:function(){return r}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:new Error().stack||""}),n&&Jp(this,n)}return e.prototype=Object.create(Error.prototype,{constructor:{value:e,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return t},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),e}L.newError=Xp;L.ProtocolError=Xp("ProtocolError");L.oneOfGetter=function(e){for(var r={},n=0;n<e.length;++n)r[e[n]]=1;return function(){for(var o=Object.keys(this),i=o.length-1;i>-1;--i)if(r[o[i]]===1&&this[o[i]]!==void 0&&this[o[i]]!==null)return o[i]}};L.oneOfSetter=function(e){return function(r){for(var n=0;n<e.length;++n)e[n]!==r&&delete this[e[n]]}};L.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};L._configure=function(){var t=L.Buffer;if(!t){L._Buffer_from=L._Buffer_allocUnsafe=null;return}L._Buffer_from=t.from!==Uint8Array.from&&t.from||function(r,n){return new t(r,n)},L._Buffer_allocUnsafe=t.allocUnsafe||function(r){return new t(r)}}});var Wi=$((o3,ty)=>{"use strict";ty.exports=M;var Ie=ot(),Rc,qi=Ie.LongBits,Yp=Ie.base64,Zp=Ie.utf8;function Kn(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function zc(){}function $x(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function M(){this.len=0,this.head=new Kn(zc,0,0),this.tail=this.head,this.states=null}var ey=function(){return Ie.Buffer?function(){return(M.create=function(){return new Rc})()}:function(){return new M}};M.create=ey();M.alloc=function(e){return new Ie.Array(e)};Ie.Array!==Array&&(M.alloc=Ie.pool(M.alloc,Ie.Array.prototype.subarray));M.prototype._push=function(e,r,n){return this.tail=this.tail.next=new Kn(e,r,n),this.len+=r,this};function $c(t,e,r){e[r]=t&255}function Hx(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function Hc(t,e){this.len=t,this.next=void 0,this.val=e}Hc.prototype=Object.create(Kn.prototype);Hc.prototype.fn=Hx;M.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new Hc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};M.prototype.int32=function(e){return e<0?this._push(jc,10,qi.fromNumber(e)):this.uint32(e)};M.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function jc(t,e,r){for(;t.hi;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}M.prototype.uint64=function(e){var r=qi.from(e);return this._push(jc,r.length(),r)};M.prototype.int64=M.prototype.uint64;M.prototype.sint64=function(e){var r=qi.from(e).zzEncode();return this._push(jc,r.length(),r)};M.prototype.bool=function(e){return this._push($c,1,e?1:0)};function Oc(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}M.prototype.fixed32=function(e){return this._push(Oc,4,e>>>0)};M.prototype.sfixed32=M.prototype.fixed32;M.prototype.fixed64=function(e){var r=qi.from(e);return this._push(Oc,4,r.lo)._push(Oc,4,r.hi)};M.prototype.sfixed64=M.prototype.fixed64;M.prototype.float=function(e){return this._push(Ie.float.writeFloatLE,4,e)};M.prototype.double=function(e){return this._push(Ie.float.writeDoubleLE,8,e)};var jx=Ie.Array.prototype.set?function(e,r,n){r.set(e,n)}:function(e,r,n){for(var o=0;o<e.length;++o)r[n+o]=e[o]};M.prototype.bytes=function(e){var r=e.length>>>0;if(!r)return this._push($c,1,0);if(Ie.isString(e)){var n=M.alloc(r=Yp.length(e));Yp.decode(e,n,0),e=n}return this.uint32(r)._push(jx,r,e)};M.prototype.string=function(e){var r=Zp.length(e);return r?this.uint32(r)._push(Zp.write,r,e):this._push($c,1,0)};M.prototype.fork=function(){return this.states=new $x(this),this.head=this.tail=new Kn(zc,0,0),this.len=0,this};M.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Kn(zc,0,0),this.len=0),this};M.prototype.ldelim=function(){var e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=r,this.len+=n),this};M.prototype.finish=function(){for(var e=this.head.next,r=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r};M._configure=function(t){Rc=t,M.create=ey(),Rc._configure()}});var Vc=$((i3,ny)=>{"use strict";ny.exports=Qe;var ry=Wi();(Qe.prototype=Object.create(ry.prototype)).constructor=Qe;var vt=ot();function Qe(){ry.call(this)}Qe._configure=function(){Qe.alloc=vt._Buffer_allocUnsafe,Qe.writeBytesBuffer=vt.Buffer&&vt.Buffer.prototype instanceof Uint8Array&&vt.Buffer.prototype.set.name==="set"?function(e,r,n){r.set(e,n)}:function(e,r,n){if(e.copy)e.copy(r,n,0,e.length);else for(var o=0;o<e.length;)r[n++]=e[o++]}};Qe.prototype.bytes=function(e){vt.isString(e)&&(e=vt._Buffer_from(e,"base64"));var r=e.length>>>0;return this.uint32(r),r&&this._push(Qe.writeBytesBuffer,r,e),this};function Vx(t,e,r){t.length<40?vt.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}Qe.prototype.string=function(e){var r=vt.Buffer.byteLength(e);return this.uint32(r),r&&this._push(Vx,r,e),this};Qe._configure()});var Gi=$((s3,cy)=>{"use strict";cy.exports=J;var Je=ot(),Wc,sy=Je.LongBits,qx=Je.utf8;function Me(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function J(t){this.buf=t,this.pos=0,this.len=t.length}var oy=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new J(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new J(e);throw Error("illegal buffer")},ay=function(){return Je.Buffer?function(r){return(J.create=function(o){return Je.Buffer.isBuffer(o)?new Wc(o):oy(o)})(r)}:oy};J.create=ay();J.prototype._slice=Je.Array.prototype.subarray||Je.Array.prototype.slice;J.prototype.uint32=function(){var e=4294967295;return function(){if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Me(this,10);return e}}();J.prototype.int32=function(){return this.uint32()|0};J.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function qc(){var t=new sy(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Me(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Me(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}J.prototype.bool=function(){return this.uint32()!==0};function Ki(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}J.prototype.fixed32=function(){if(this.pos+4>this.len)throw Me(this,4);return Ki(this.buf,this.pos+=4)};J.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Me(this,4);return Ki(this.buf,this.pos+=4)|0};function iy(){if(this.pos+8>this.len)throw Me(this,8);return new sy(Ki(this.buf,this.pos+=4),Ki(this.buf,this.pos+=4))}J.prototype.float=function(){if(this.pos+4>this.len)throw Me(this,4);var e=Je.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};J.prototype.double=function(){if(this.pos+8>this.len)throw Me(this,4);var e=Je.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};J.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw Me(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(r,n):r===n?new this.buf.constructor(0):this._slice.call(this.buf,r,n)};J.prototype.string=function(){var e=this.bytes();return qx.read(e,0,e.length)};J.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Me(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Me(this);while(this.buf[this.pos++]&128);return this};J.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this};J._configure=function(t){Wc=t,J.create=ay(),Wc._configure();var e=Je.Long?"toLong":"toNumber";Je.merge(J.prototype,{int64:function(){return qc.call(this)[e](!1)},uint64:function(){return qc.call(this)[e](!0)},sint64:function(){return qc.call(this).zzDecode()[e](!1)},fixed64:function(){return iy.call(this)[e](!0)},sfixed64:function(){return iy.call(this)[e](!1)}})}});var Kc=$((a3,fy)=>{"use strict";fy.exports=Yt;var ly=Gi();(Yt.prototype=Object.create(ly.prototype)).constructor=Yt;var uy=ot();function Yt(t){ly.call(this,t)}Yt._configure=function(){uy.Buffer&&(Yt.prototype._slice=uy.Buffer.prototype.slice)};Yt.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))};Yt._configure()});var hy=$((c3,dy)=>{"use strict";dy.exports=Gn;var Gc=ot();(Gn.prototype=Object.create(Gc.EventEmitter.prototype)).constructor=Gn;function Gn(t,e,r){if(typeof t!="function")throw TypeError("rpcImpl must be a function");Gc.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!r}Gn.prototype.rpcCall=function t(e,r,n,o,i){if(!o)throw TypeError("request must be specified");var s=this;if(!i)return Gc.asPromise(t,s,e,r,n,o);if(!s.rpcImpl){setTimeout(function(){i(Error("already ended"))},0);return}try{return s.rpcImpl(e,r[s.requestDelimited?"encodeDelimited":"encode"](o).finish(),function(a,u){if(a)return s.emit("error",a,e),i(a);if(u===null){s.end(!0);return}if(!(u instanceof n))try{u=n[s.responseDelimited?"decodeDelimited":"decode"](u)}catch(l){return s.emit("error",l,e),i(l)}return s.emit("data",u,e),i(null,u)})}catch(c){s.emit("error",c,e),setTimeout(function(){i(c)},0);return}};Gn.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var yy=$(py=>{"use strict";var Wx=py;Wx.Service=hy()});var gy=$((l3,my)=>{"use strict";my.exports={}});var xy=$(by=>{"use strict";var fe=by;fe.build="minimal";fe.Writer=Wi();fe.BufferWriter=Vc();fe.Reader=Gi();fe.BufferReader=Kc();fe.util=ot();fe.rpc=yy();fe.roots=gy();fe.configure=wy;function wy(){fe.util._configure(),fe.Writer._configure(fe.BufferWriter),fe.Reader._configure(fe.BufferReader)}wy()});var vy=$((d3,ky)=>{"use strict";ky.exports=xy()});var bm=$((io,ys)=>{(function(t,e){"use strict";var r={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(f){if(!Array.isArray(f)&&!ArrayBuffer.isView(f))return!1;for(var h=0;h<f.length;h++)if(!Number.isInteger(f[h])||f[h]<0||f[h]>255)return!1;return!0}function o(f,h){return(f&65535)*h+(((f>>>16)*h&65535)<<16)}function i(f,h){return f<<h|f>>>32-h}function s(f){return f^=f>>>16,f=o(f,2246822507),f^=f>>>13,f=o(f,3266489909),f^=f>>>16,f}function c(f,h){f=[f[0]>>>16,f[0]&65535,f[1]>>>16,f[1]&65535],h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535];var p=[0,0,0,0];return p[3]+=f[3]+h[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=f[2]+h[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=f[1]+h[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=f[0]+h[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function a(f,h){f=[f[0]>>>16,f[0]&65535,f[1]>>>16,f[1]&65535],h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535];var p=[0,0,0,0];return p[3]+=f[3]*h[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=f[2]*h[3],p[1]+=p[2]>>>16,p[2]&=65535,p[2]+=f[3]*h[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=f[1]*h[3],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=f[2]*h[2],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=f[3]*h[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=f[0]*h[3]+f[1]*h[2]+f[2]*h[1]+f[3]*h[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function u(f,h){return h%=64,h===32?[f[1],f[0]]:h<32?[f[0]<<h|f[1]>>>32-h,f[1]<<h|f[0]>>>32-h]:(h-=32,[f[1]<<h|f[0]>>>32-h,f[0]<<h|f[1]>>>32-h])}function l(f,h){return h%=64,h===0?f:h<32?[f[0]<<h|f[1]>>>32-h,f[1]<<h]:[f[1]<<h-32,0]}function d(f,h){return[f[0]^h[0],f[1]^h[1]]}function m(f){return f=d(f,[0,f[0]>>>1]),f=a(f,[4283543511,3981806797]),f=d(f,[0,f[0]>>>1]),f=a(f,[3301882366,444984403]),f=d(f,[0,f[0]>>>1]),f}r.x86.hash32=function(f,h){if(r.inputValidation&&!n(f))return e;h=h||0;for(var p=f.length%4,w=f.length-p,g=h,b=0,k=3432918353,v=461845907,C=0;C<w;C=C+4)b=f[C]|f[C+1]<<8|f[C+2]<<16|f[C+3]<<24,b=o(b,k),b=i(b,15),b=o(b,v),g^=b,g=i(g,13),g=o(g,5)+3864292196;switch(b=0,p){case 3:b^=f[C+2]<<16;case 2:b^=f[C+1]<<8;case 1:b^=f[C],b=o(b,k),b=i(b,15),b=o(b,v),g^=b}return g^=f.length,g=s(g),g>>>0},r.x86.hash128=function(f,h){if(r.inputValidation&&!n(f))return e;h=h||0;for(var p=f.length%16,w=f.length-p,g=h,b=h,k=h,v=h,C=0,N=0,S=0,U=0,ue=597399067,Bo=2869860233,Co=951274213,To=2716044179,F=0;F<w;F=F+16)C=f[F]|f[F+1]<<8|f[F+2]<<16|f[F+3]<<24,N=f[F+4]|f[F+5]<<8|f[F+6]<<16|f[F+7]<<24,S=f[F+8]|f[F+9]<<8|f[F+10]<<16|f[F+11]<<24,U=f[F+12]|f[F+13]<<8|f[F+14]<<16|f[F+15]<<24,C=o(C,ue),C=i(C,15),C=o(C,Bo),g^=C,g=i(g,19),g+=b,g=o(g,5)+1444728091,N=o(N,Bo),N=i(N,16),N=o(N,Co),b^=N,b=i(b,17),b+=k,b=o(b,5)+197830471,S=o(S,Co),S=i(S,17),S=o(S,To),k^=S,k=i(k,15),k+=v,k=o(k,5)+2530024501,U=o(U,To),U=i(U,18),U=o(U,ue),v^=U,v=i(v,13),v+=g,v=o(v,5)+850148119;switch(C=0,N=0,S=0,U=0,p){case 15:U^=f[F+14]<<16;case 14:U^=f[F+13]<<8;case 13:U^=f[F+12],U=o(U,To),U=i(U,18),U=o(U,ue),v^=U;case 12:S^=f[F+11]<<24;case 11:S^=f[F+10]<<16;case 10:S^=f[F+9]<<8;case 9:S^=f[F+8],S=o(S,Co),S=i(S,17),S=o(S,To),k^=S;case 8:N^=f[F+7]<<24;case 7:N^=f[F+6]<<16;case 6:N^=f[F+5]<<8;case 5:N^=f[F+4],N=o(N,Bo),N=i(N,16),N=o(N,Co),b^=N;case 4:C^=f[F+3]<<24;case 3:C^=f[F+2]<<16;case 2:C^=f[F+1]<<8;case 1:C^=f[F],C=o(C,ue),C=i(C,15),C=o(C,Bo),g^=C}return g^=f.length,b^=f.length,k^=f.length,v^=f.length,g+=b,g+=k,g+=v,b+=g,k+=g,v+=g,g=s(g),b=s(b),k=s(k),v=s(v),g+=b,g+=k,g+=v,b+=g,k+=g,v+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(k>>>0).toString(16)).slice(-8)+("00000000"+(v>>>0).toString(16)).slice(-8)},r.x64.hash128=function(f,h){if(r.inputValidation&&!n(f))return e;h=h||0;for(var p=f.length%16,w=f.length-p,g=[0,h],b=[0,h],k=[0,0],v=[0,0],C=[2277735313,289559509],N=[1291169091,658871167],S=0;S<w;S=S+16)k=[f[S+4]|f[S+5]<<8|f[S+6]<<16|f[S+7]<<24,f[S]|f[S+1]<<8|f[S+2]<<16|f[S+3]<<24],v=[f[S+12]|f[S+13]<<8|f[S+14]<<16|f[S+15]<<24,f[S+8]|f[S+9]<<8|f[S+10]<<16|f[S+11]<<24],k=a(k,C),k=u(k,31),k=a(k,N),g=d(g,k),g=u(g,27),g=c(g,b),g=c(a(g,[0,5]),[0,1390208809]),v=a(v,N),v=u(v,33),v=a(v,C),b=d(b,v),b=u(b,31),b=c(b,g),b=c(a(b,[0,5]),[0,944331445]);switch(k=[0,0],v=[0,0],p){case 15:v=d(v,l([0,f[S+14]],48));case 14:v=d(v,l([0,f[S+13]],40));case 13:v=d(v,l([0,f[S+12]],32));case 12:v=d(v,l([0,f[S+11]],24));case 11:v=d(v,l([0,f[S+10]],16));case 10:v=d(v,l([0,f[S+9]],8));case 9:v=d(v,[0,f[S+8]]),v=a(v,N),v=u(v,33),v=a(v,C),b=d(b,v);case 8:k=d(k,l([0,f[S+7]],56));case 7:k=d(k,l([0,f[S+6]],48));case 6:k=d(k,l([0,f[S+5]],40));case 5:k=d(k,l([0,f[S+4]],32));case 4:k=d(k,l([0,f[S+3]],24));case 3:k=d(k,l([0,f[S+2]],16));case 2:k=d(k,l([0,f[S+1]],8));case 1:k=d(k,[0,f[S]]),k=a(k,C),k=u(k,31),k=a(k,N),g=d(g,k)}return g=d(g,[0,f.length]),b=d(b,[0,f.length]),g=c(g,b),b=c(b,g),g=m(g),b=m(b),g=c(g,b),b=c(b,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof io<"u"?(typeof ys<"u"&&ys.exports&&(io=ys.exports=r),io.murmurHash3=r):typeof define=="function"&&define.amd?define([],function(){return r}):(r._murmurHash3=t.murmurHash3,r.noConflict=function(){return t.murmurHash3=r._murmurHash3,r._murmurHash3=e,r.noConflict=e,r},t.murmurHash3=r)})(io)});var Tu=$((R3,xm)=>{xm.exports=bm()});var Ye=$((EC,Gm)=>{"use strict";function Km(t,e){for(let r in e)Object.defineProperty(t,r,{value:e[r],enumerable:!0,configurable:!0});return t}function U2(t,e,r){if(!t||typeof t=="string")throw new TypeError("Please pass an Error to err-code");r||(r={}),typeof e=="object"&&(r=e,e=""),e&&(r.code=e);try{return Km(t,r)}catch{r.message=t.message,r.stack=t.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(t)),Km(new o,r)}}Gm.exports=U2});var yg=$((aT,pg)=>{"use strict";pg.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,r){let n=this._internalPositionFor(e,!1);if(r===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let o=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):o=!0,this._setInternalPos(n,e,r,o),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let r=this._internalPositionFor(e,!0);if(r!==-1)return this._data[r][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let r=0;for(;r<this.length;)e(this.get(r),r,this),r++}map(e){let r=0,n=new Array(this.length);for(;r<this.length;)n[r]=e(this.get(r),r,this),r++;return n}reduce(e,r){let n=0,o=r;for(;n<this.length;){let i=this.get(n);o=e(o,i,n),n++}return o}find(e){let r=0,n,o;for(;r<this.length&&!n;)o=this.get(r),n=e(o),r++;return n?o:void 0}_internalPositionFor(e,r){let n=this._bytePosFor(e,r);if(n>=this._bitArrays.length)return-1;let o=this._bitArrays[n],i=e-n*7;if(!((o&1<<i)>0))return-1;let c=this._bitArrays.slice(0,n).reduce(J2,0),a=~(4294967295<<i+1),u=hg(o&a);return c+u-1}_bytePosFor(e,r){let n=Math.floor(e/7),o=n+1;for(;!r&&this._bitArrays.length<o;)this._bitArrays.push(0);return n}_setBit(e){let r=this._bytePosFor(e,!1);this._bitArrays[r]|=1<<e-r*7}_unsetBit(e){let r=this._bytePosFor(e,!1);this._bitArrays[r]&=~(1<<e-r*7)}_setInternalPos(e,r,n,o){let i=this._data,s=[r,n];if(o)this._sortData(),i[e]=s;else{if(i.length)if(i[i.length-1][0]>=r)i.push(s);else if(i[0][0]<=r)i.unshift(s);else{let c=Math.round(i.length/2);this._data=i.slice(0,c).concat(s).concat(i.slice(c))}else this._data.push(s);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(X2),this._changedData=!1}bitField(){let e=[],r=8,n=0,o=0,i,s=this._bitArrays.slice();for(;s.length||n;){n===0&&(i=s.shift(),n=7);let a=Math.min(n,r),u=~(255<<a),l=i&u;o|=l<<8-r,i=i>>>a,n-=a,r-=a,(!r||!n&&!s.length)&&(e.push(o),o=0,r=8)}for(var c=e.length-1;c>0&&e[c]===0;c--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(Y2)}};function J2(t,e){return t+hg(e)}function hg(t){let e=t;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function X2(t,e){return t[0]-e[0]}function Y2(t){return t[1]}});var Mg=$((w4,il)=>{"use strict";var jv=Object.prototype.hasOwnProperty,ce="~";function mo(){}Object.create&&(mo.prototype=Object.create(null),new mo().__proto__||(ce=!1));function Vv(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function Fg(t,e,r,n,o){if(typeof r!="function")throw new TypeError("The listener must be a function");var i=new Vv(r,n||t,o),s=ce?ce+e:e;return t._events[s]?t._events[s].fn?t._events[s]=[t._events[s],i]:t._events[s].push(i):(t._events[s]=i,t._eventsCount++),t}function Ds(t,e){--t._eventsCount===0?t._events=new mo:delete t._events[e]}function oe(){this._events=new mo,this._eventsCount=0}oe.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)jv.call(r,n)&&e.push(ce?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};oe.prototype.listeners=function(e){var r=ce?ce+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};oe.prototype.listenerCount=function(e){var r=ce?ce+e:e,n=this._events[r];return n?n.fn?1:n.length:0};oe.prototype.emit=function(e,r,n,o,i,s){var c=ce?ce+e:e;if(!this._events[c])return!1;var a=this._events[c],u=arguments.length,l,d;if(a.fn){switch(a.once&&this.removeListener(e,a.fn,void 0,!0),u){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,r),!0;case 3:return a.fn.call(a.context,r,n),!0;case 4:return a.fn.call(a.context,r,n,o),!0;case 5:return a.fn.call(a.context,r,n,o,i),!0;case 6:return a.fn.call(a.context,r,n,o,i,s),!0}for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];a.fn.apply(a.context,l)}else{var m=a.length,f;for(d=0;d<m;d++)switch(a[d].once&&this.removeListener(e,a[d].fn,void 0,!0),u){case 1:a[d].fn.call(a[d].context);break;case 2:a[d].fn.call(a[d].context,r);break;case 3:a[d].fn.call(a[d].context,r,n);break;case 4:a[d].fn.call(a[d].context,r,n,o);break;default:if(!l)for(f=1,l=new Array(u-1);f<u;f++)l[f-1]=arguments[f];a[d].fn.apply(a[d].context,l)}}return!0};oe.prototype.on=function(e,r,n){return Fg(this,e,r,n,!1)};oe.prototype.once=function(e,r,n){return Fg(this,e,r,n,!0)};oe.prototype.removeListener=function(e,r,n,o){var i=ce?ce+e:e;if(!this._events[i])return this;if(!r)return Ds(this,i),this;var s=this._events[i];if(s.fn)s.fn===r&&(!o||s.once)&&(!n||s.context===n)&&Ds(this,i);else{for(var c=0,a=[],u=s.length;c<u;c++)(s[c].fn!==r||o&&!s[c].once||n&&s[c].context!==n)&&a.push(s[c]);a.length?this._events[i]=a.length===1?a[0]:a:Ds(this,i)}return this};oe.prototype.removeAllListeners=function(e){var r;return e?(r=ce?ce+e:e,this._events[r]&&Ds(this,r)):(this._events=new mo,this._eventsCount=0),this};oe.prototype.off=oe.prototype.removeListener;oe.prototype.addListener=oe.prototype.on;oe.prefixed=ce;oe.EventEmitter=oe;typeof il<"u"&&(il.exports=oe)});var cE={};G(cE,{DataStore:()=>zn,Database:()=>ir,Index:()=>Ti,Loader:()=>Fr,MetaStore:()=>On,STORAGE_VERSION:()=>$n,cidListIncludes:()=>cc,encodeCarFile:()=>Pn,encodeCarHeader:()=>Wa,fireproof:()=>sE,index:()=>Rr,parseCarFile:()=>Ka,toHexString:()=>qh});module.exports=yw(cE);var Lo="0123456789abcdef",Do=class t{constructor(e){this.bytes=e}static ofInner(e){if(e.length!==16)throw new TypeError("not 128-bit length");return new t(e)}static fromFieldsV7(e,r,n,o){if(!Number.isInteger(e)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(o)||e<0||r<0||n<0||o<0||e>0xffffffffffff||r>4095||n>1073741823||o>4294967295)throw new RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/2**16,i[4]=e/2**8,i[5]=e,i[6]=112|r>>>8,i[7]=r,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=o>>>24,i[13]=o>>>16,i[14]=o>>>8,i[15]=o,new t(i)}static parse(e){var r,n,o,i;let s;switch(e.length){case 32:s=(r=/^[0-9a-f]{32}$/i.exec(e))===null||r===void 0?void 0:r[0];break;case 36:s=(n=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e))===null||n===void 0?void 0:n.slice(1,6).join("");break;case 38:s=(o=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e))===null||o===void 0?void 0:o.slice(1,6).join("");break;case 45:s=(i=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e))===null||i===void 0?void 0:i.slice(1,6).join("");break;default:break}if(s){let c=new Uint8Array(16);for(let a=0;a<16;a+=4){let u=parseInt(s.substring(2*a,2*a+8),16);c[a+0]=u>>>24,c[a+1]=u>>>16,c[a+2]=u>>>8,c[a+3]=u}return new t(c)}else throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let r=0;r<this.bytes.length;r++)e+=Lo.charAt(this.bytes[r]>>>4),e+=Lo.charAt(this.bytes[r]&15),(r===3||r===5||r===7||r===9)&&(e+="-");return e}toHex(){let e="";for(let r=0;r<this.bytes.length;r++)e+=Lo.charAt(this.bytes[r]>>>4),e+=Lo.charAt(this.bytes[r]&15);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(r=>r===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(r=>r===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new t(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let r=0;r<16;r++){let n=this.bytes[r]-e.bytes[r];if(n!==0)return Math.sign(n)}return 0}},Vs=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??mw()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,r){let n=this.generateOrAbortCore(e,r);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,r)),n}generateOrAbortCore(e,r){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(r<0||r>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else if(e+r>=this.timestamp)this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter());else return;return Do.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,Do.ofInner(e)}},mw=()=>{if(typeof crypto<"u"&&typeof crypto.getRandomValues<"u")return new qs;if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");return{nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}},qs=class{constructor(){this.buffer=new Uint32Array(8),this.cursor=65535}nextUint32(){return this.cursor>=this.buffer.length&&(crypto.getRandomValues(this.buffer),this.cursor=0),this.buffer[this.cursor++]}},wl,bl=()=>gw().toString(),gw=()=>(wl||(wl=new Vs)).generate();function xl(t,e=1/0,r=!1){let n=[],o=!1;async function i(){if(o||n.length===0)return;o=!0;let s=n.splice(0,e),c=s.map(a=>a.task);if(r){let a=c.map(async(u,l)=>{try{let d=await t([u]);s[l].resolve(d)}catch(d){s[l].reject(d)}});await Promise.all(a)}else try{let a=await t(c);s.forEach(u=>u.resolve(a))}catch(a){s.forEach(u=>u.reject(a))}o=!1,i()}return{push(s){return new Promise((c,a)=>{n.push({task:s,resolve:c,reject:a}),i()})}}}var ww=El,kl=128,bw=127,xw=~bw,kw=Math.pow(2,31);function El(t,e,r){e=e||[],r=r||0;for(var n=r;t>=kw;)e[r++]=t&255|kl,t/=128;for(;t&xw;)e[r++]=t&255|kl,t>>>=7;return e[r]=t|0,El.bytes=r-n+1,e}var vw=Ws,Ew=128,vl=127;function Ws(t,n){var r=0,n=n||0,o=0,i=n,s,c=t.length;do{if(i>=c)throw Ws.bytes=0,new RangeError("Could not decode varint");s=t[i++],r+=o<28?(s&vl)<<o:(s&vl)*Math.pow(2,o),o+=7}while(s>=Ew);return Ws.bytes=i-n,r}var Sw=Math.pow(2,7),Aw=Math.pow(2,14),_w=Math.pow(2,21),Bw=Math.pow(2,28),Cw=Math.pow(2,35),Tw=Math.pow(2,42),Iw=Math.pow(2,49),Lw=Math.pow(2,56),Dw=Math.pow(2,63),Nw=function(t){return t<Sw?1:t<Aw?2:t<_w?3:t<Bw?4:t<Cw?5:t<Tw?6:t<Iw?7:t<Lw?8:t<Dw?9:10},Uw={encode:ww,decode:vw,encodingLength:Nw},Pw=Uw,cn=Pw;var un=(t,e=0)=>[cn.decode(t,e),cn.decode.bytes],sr=(t,e,r=0)=>(cn.encode(t,e,r),e),ar=t=>cn.encodingLength(t);var pE=new Uint8Array(0);var Sl=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},Se=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")};var Al=t=>new TextEncoder().encode(t),_l=t=>new TextDecoder().decode(t);var Tt=(t,e)=>{let r=e.byteLength,n=ar(t),o=n+ar(r),i=new Uint8Array(o+r);return sr(t,i,0),sr(r,i,n),i.set(e,o),new cr(t,r,e,i)},ur=t=>{let e=Se(t),[r,n]=un(e),[o,i]=un(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new cr(r,o,s,e)},Bl=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Sl(t.bytes,r.bytes)}},cr=class{constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};var Ys={};G(Ys,{base58btc:()=>ze,base58flickr:()=>$w});function Fw(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<t.length;o++){var i=t.charAt(o),s=i.charCodeAt(0);if(r[s]!==255)throw new TypeError(i+" is ambiguous");r[s]=o}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),l=Math.log(256)/Math.log(c);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var p=0,w=0,g=0,b=h.length;g!==b&&h[g]===0;)g++,p++;for(var k=(b-g)*l+1>>>0,v=new Uint8Array(k);g!==b;){for(var C=h[g],N=0,S=k-1;(C!==0||N<w)&&S!==-1;S--,N++)C+=256*v[S]>>>0,v[S]=C%c>>>0,C=C/c>>>0;if(C!==0)throw new Error("Non-zero carry");w=N,g++}for(var U=k-w;U!==k&&v[U]===0;)U++;for(var ue=a.repeat(p);U<k;++U)ue+=t.charAt(v[U]);return ue}function m(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var p=0;if(h[p]!==" "){for(var w=0,g=0;h[p]===a;)w++,p++;for(var b=(h.length-p)*u+1>>>0,k=new Uint8Array(b);h[p];){var v=r[h.charCodeAt(p)];if(v===255)return;for(var C=0,N=b-1;(v!==0||C<g)&&N!==-1;N--,C++)v+=c*k[N]>>>0,k[N]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");g=C,p++}if(h[p]!==" "){for(var S=b-g;S!==b&&k[S]===0;)S++;for(var U=new Uint8Array(w+(b-S)),ue=w;S!==b;)U[ue++]=k[S++];return U}}}function f(h){var p=m(h);if(p)return p;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:m,decode:f}}var Mw=Fw,Rw=Mw,Cl=Rw;var Gs=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Qs=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Tl(this,e)}},Js=class{constructor(e){this.decoders=e}or(e){return Tl(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Tl=(t,e)=>new Js({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Xs=class{constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Gs(e,r,n),this.decoder=new Qs(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},lr=({name:t,prefix:e,encode:r,decode:n})=>new Xs(t,e,r,n),ut=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:o}=Cl(r,e);return lr({prefix:t,name:e,encode:n,decode:i=>Se(o(i))})},Ow=(t,e,r,n)=>{let o={};for(let l=0;l<e.length;++l)o[e[l]]=l;let i=t.length;for(;t[i-1]==="=";)--i;let s=new Uint8Array(i*r/8|0),c=0,a=0,u=0;for(let l=0;l<i;++l){let d=o[t[l]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|d,c+=r,c>=8&&(c-=8,s[u++]=255&a>>c)}if(c>=r||255&a<<8-c)throw new SyntaxError("Unexpected end of data");return s},zw=(t,e,r)=>{let n=e[e.length-1]==="=",o=(1<<r)-1,i="",s=0,c=0;for(let a=0;a<t.length;++a)for(c=c<<8|t[a],s+=8;s>r;)s-=r,i+=e[o&c>>s];if(s&&(i+=e[o&c<<r-s]),n)for(;i.length*r&7;)i+="=";return i},K=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>lr({prefix:e,name:t,encode(o){return zw(o,n,r)},decode(o){return Ow(o,n,r,t)}});var ze=ut({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),$w=ut({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Zs={};G(Zs,{base32:()=>fr,base32hex:()=>qw,base32hexpad:()=>Kw,base32hexpadupper:()=>Gw,base32hexupper:()=>Ww,base32pad:()=>jw,base32padupper:()=>Vw,base32upper:()=>Hw,base32z:()=>Qw});var fr=K({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Hw=K({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),jw=K({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Vw=K({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),qw=K({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ww=K({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Kw=K({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Gw=K({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Qw=K({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ea=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return Xw(r,ta(t),e||ze.encoder);default:return Yw(r,ta(t),e||fr.encoder)}};var Il=new WeakMap,ta=t=>{let e=Il.get(t);if(e==null){let r=new Map;return Il.set(t,r),r}return e},H=class t{constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==ln)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Zw)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Tt(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return t.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&Bl(e.multihash,n.multihash)}toString(e){return ea(this,e)}toJSON(){return{"/":ea(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:i,bytes:s}=r;return new t(n,o,i,s||Ll(n,o,i.bytes))}else if(r[eb]===!0){let{version:n,multihash:o,code:i}=r,s=ur(o);return t.create(n,i,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==ln)throw new Error(`Version 0 CID must use dag-pb (code: ${ln}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=Ll(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,ln,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=Se(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let i=o.subarray(r.multihashSize-r.digestSize),s=new cr(r.multihashCode,r.digestSize,i,o);return[r.version===0?t.createV0(s):t.createV1(r.codec,s),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[d,m]=un(e.subarray(r));return r+=m,d},o=n(),i=ln;if(o===18?(o=0,r=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=r,c=n(),a=n(),u=r+a,l=u-s;return{version:o,codec:i,multihashCode:c,digestSize:a,multihashSize:l,size:u}}static parse(e,r){let[n,o]=Jw(e,r),i=t.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ta(i).set(n,e),i}},Jw=(t,e)=>{switch(t[0]){case"Q":{let r=e||ze;return[ze.prefix,r.decode(`${ze.prefix}${t}`)]}case ze.prefix:{let r=e||ze;return[ze.prefix,r.decode(t)]}case fr.prefix:{let r=e||fr;return[fr.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},Xw=(t,e,r)=>{let{prefix:n}=r;if(n!==ze.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let i=r.encode(t).slice(1);return e.set(n,i),i}else return o},Yw=(t,e,r)=>{let{prefix:n}=r,o=e.get(n);if(o==null){let i=r.encode(t);return e.set(n,i),i}else return o},ln=112,Zw=18,Ll=(t,e,r)=>{let n=ar(t),o=n+ar(e),i=new Uint8Array(o+r.byteLength);return sr(t,i,0),sr(e,i,n),i.set(r,o),i},eb=Symbol.for("@ipld/js-cid/CID");var Dl=(t,e)=>H.parse(t,e);var Ae=class{#e=new Map;constructor(e){e&&(this.#e=new Map(e.map(r=>[r.cid.toString(),r.bytes])))}async get(e){let r=this.#e.get(e.toString());if(r)return{cid:e,bytes:r}}async put(e,r){this.#e.set(e.toString(),r)}putSync(e,r){this.#e.set(e.toString(),r)}async delete(e){this.#e.delete(e.toString())}deleteSync(e){this.#e.delete(e.toString())}*entries(){for(let[e,r]of this.#e)yield{cid:Dl(e),bytes:r}}},Lt=class{#e;constructor(...e){this.#e=e}async get(e){for(let r of this.#e){let n=await r.get(e);if(n)return n}}};var ra=class{value;next;constructor(e){this.value=e}},fn=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let r=new ra(e);this.#e?(this.#t.next=r,this.#t=r):(this.#e=r,this.#t=r),this.#r++}dequeue(){let e=this.#e;if(e)return this.#e=this.#e.next,this.#r--,e.value}clear(){this.#e=void 0,this.#t=void 0,this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let e=this.#e;for(;e;)yield e.value,e=e.next}};function dn(t){if(!((Number.isInteger(t)||t===Number.POSITIVE_INFINITY)&&t>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");let e=new fn,r=0,n=()=>{r--,e.size>0&&e.dequeue()()},o=async(c,a,u)=>{r++;let l=(async()=>c(...u))();a(l);try{await l}catch{}n()},i=(c,a,u)=>{e.enqueue(o.bind(void 0,c,a,u)),(async()=>(await Promise.resolve(),r<t&&e.size>0&&e.dequeue()()))()},s=(c,...a)=>new Promise(u=>{i(c,u,a)});return Object.defineProperties(s,{activeCount:{get:()=>r},pendingCount:{get:()=>e.size},clearQueue:{value:()=>{e.clear()}}}),s}var cd=V(require("fs"),1),ud=require("util");var q={};G(q,{code:()=>ka,decode:()=>xr,encode:()=>Ko,name:()=>h0});var tb=["string","number","bigint","symbol"],rb=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Nl(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(tb.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(nb(t))return"Buffer";let r=ob(t);return r||"Object"}function nb(t){return t&&t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer.call(null,t)}function ob(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(rb.includes(e))return e}var y=class{constructor(e,r,n){this.major=e,this.majorEncoded=e<<5,this.name=r,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};y.uint=new y(0,"uint",!0);y.negint=new y(1,"negint",!0);y.bytes=new y(2,"bytes",!0);y.string=new y(3,"string",!0);y.array=new y(4,"array",!1);y.map=new y(5,"map",!1);y.tag=new y(6,"tag",!1);y.float=new y(7,"float",!0);y.false=new y(7,"false",!0);y.true=new y(7,"true",!0);y.null=new y(7,"null",!0);y.undefined=new y(7,"undefined",!0);y.break=new y(7,"break",!0);var E=class{constructor(e,r,n){this.type=e,this.value=r,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var dr=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ib=new TextDecoder,sb=new TextEncoder;function Uo(t){return dr&&globalThis.Buffer.isBuffer(t)}function hn(t){return t instanceof Uint8Array?Uo(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var Ml=dr?(t,e,r)=>r-e>64?globalThis.Buffer.from(t.subarray(e,r)).toString("utf8"):Pl(t,e,r):(t,e,r)=>r-e>64?ib.decode(t.subarray(e,r)):Pl(t,e,r),Po=dr?t=>t.length>64?globalThis.Buffer.from(t):Ul(t):t=>t.length>64?sb.encode(t):Ul(t),$e=t=>Uint8Array.from(t),hr=dr?(t,e,r)=>Uo(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),Rl=dr?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),hn(globalThis.Buffer.concat(t,e))):(t,e)=>{let r=new Uint8Array(e),n=0;for(let o of t)n+o.length>r.length&&(o=o.subarray(0,r.length-n)),r.set(o,n),n+=o.length;return r},Ol=dr?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function zl(t,e){if(Uo(t)&&Uo(e))return t.compare(e);for(let r=0;r<t.length;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return 0}function Ul(t,e=1/0){let r,n=t.length,o=null,i=[];for(let s=0;s<n;++s){if(r=t.charCodeAt(s),r>55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),o=r;continue}r=(o-55296<<10|r-56320)+65536}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return i}function Pl(t,e,r){let n=[];for(;e<r;){let o=t[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=r){let c,a,u,l;switch(s){case 1:o<128&&(i=o);break;case 2:c=t[e+1],(c&192)===128&&(l=(o&31)<<6|c&63,l>127&&(i=l));break;case 3:c=t[e+1],a=t[e+2],(c&192)===128&&(a&192)===128&&(l=(o&15)<<12|(c&63)<<6|a&63,l>2047&&(l<55296||l>57343)&&(i=l));break;case 4:c=t[e+1],a=t[e+2],u=t[e+3],(c&192)===128&&(a&192)===128&&(u&192)===128&&(l=(o&15)<<18|(c&63)<<12|(a&63)<<6|u&63,l>65535&&l<1114112&&(i=l))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return na(n)}var Fl=4096;function na(t){let e=t.length;if(e<=Fl)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Fl));return r}var ab=256,pn=class{constructor(e=ab){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let r=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=r.length-(this.maxCursor-this.cursor)-1;r.set(e,o)}else{if(r){let o=r.length-(this.maxCursor-this.cursor)-1;o<r.length&&(this.chunks[this.chunks.length-1]=r.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(r=Ol(this.chunkSize),this.chunks.push(r),this.maxCursor+=r.length,this._initReuseChunk===null&&(this._initReuseChunk=r),r.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let r;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(r=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):r=hr(n,0,this.cursor)}else r=Rl(this.chunks,this.cursor);return e&&this.reset(),r}};var T="CBOR decode error:",Ze="CBOR encode error:",yn=[];yn[23]=1;yn[24]=2;yn[25]=3;yn[26]=5;yn[27]=9;function et(t,e,r){if(t.length-e<r)throw new Error(`${T} not enough data for type`)}var Y=[24,256,65536,4294967296,BigInt("18446744073709551616")];function he(t,e,r){et(t,e,1);let n=t[e];if(r.strict===!0&&n<Y[0])throw new Error(`${T} integer encoded in more bytes than necessary (strict decode)`);return n}function pe(t,e,r){et(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<Y[1])throw new Error(`${T} integer encoded in more bytes than necessary (strict decode)`);return n}function ye(t,e,r){et(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<Y[2])throw new Error(`${T} integer encoded in more bytes than necessary (strict decode)`);return n}function me(t,e,r){et(t,e,8);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],o=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(r.strict===!0&&i<Y[3])throw new Error(`${T} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(r.allowBigInt===!0)return i;throw new Error(`${T} integers outside of the safe integer range are not supported`)}function $l(t,e,r,n){return new E(y.uint,he(t,e+1,n),2)}function Hl(t,e,r,n){return new E(y.uint,pe(t,e+1,n),3)}function jl(t,e,r,n){return new E(y.uint,ye(t,e+1,n),5)}function Vl(t,e,r,n){return new E(y.uint,me(t,e+1,n),9)}function _e(t,e){return te(t,0,e.value)}function te(t,e,r){if(r<Y[0]){let n=Number(r);t.push([e|n])}else if(r<Y[1]){let n=Number(r);t.push([e|24,n])}else if(r<Y[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<Y[3]){let n=Number(r);t.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(r);if(n<Y[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,t.push(o)}else throw new Error(`${T} encountered BigInt larger than allowable range`)}}_e.encodedSize=function(e){return te.encodedSize(e.value)};te.encodedSize=function(e){return e<Y[0]?1:e<Y[1]?2:e<Y[2]?3:e<Y[3]?5:9};_e.compareTokens=function(e,r){return e.value<r.value?-1:e.value>r.value?1:0};function ql(t,e,r,n){return new E(y.negint,-1-he(t,e+1,n),2)}function Wl(t,e,r,n){return new E(y.negint,-1-pe(t,e+1,n),3)}function Kl(t,e,r,n){return new E(y.negint,-1-ye(t,e+1,n),5)}var oa=BigInt(-1),Gl=BigInt(1);function Ql(t,e,r,n){let o=me(t,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new E(y.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${T} integers outside of the safe integer range are not supported`);return new E(y.negint,oa-BigInt(o),9)}function Fo(t,e){let r=e.value,n=typeof r=="bigint"?r*oa-Gl:r*-1-1;te(t,e.type.majorEncoded,n)}Fo.encodedSize=function(e){let r=e.value,n=typeof r=="bigint"?r*oa-Gl:r*-1-1;return n<Y[0]?1:n<Y[1]?2:n<Y[2]?3:n<Y[3]?5:9};Fo.compareTokens=function(e,r){return e.value<r.value?1:e.value>r.value?-1:0};function mn(t,e,r,n){et(t,e,r+n);let o=hr(t,e+r,e+r+n);return new E(y.bytes,o,r+n)}function Jl(t,e,r,n){return mn(t,e,1,r)}function Xl(t,e,r,n){return mn(t,e,2,he(t,e+1,n))}function Yl(t,e,r,n){return mn(t,e,3,pe(t,e+1,n))}function Zl(t,e,r,n){return mn(t,e,5,ye(t,e+1,n))}function ef(t,e,r,n){let o=me(t,e+1,n);if(typeof o=="bigint")throw new Error(`${T} 64-bit integer bytes lengths not supported`);return mn(t,e,9,o)}function Mo(t){return t.encodedBytes===void 0&&(t.encodedBytes=t.type===y.string?Po(t.value):t.value),t.encodedBytes}function pr(t,e){let r=Mo(e);te(t,e.type.majorEncoded,r.length),t.push(r)}pr.encodedSize=function(e){let r=Mo(e);return te.encodedSize(r.length)+r.length};pr.compareTokens=function(e,r){return ub(Mo(e),Mo(r))};function ub(t,e){return t.length<e.length?-1:t.length>e.length?1:zl(t,e)}function gn(t,e,r,n,o){let i=r+n;et(t,e,i);let s=new E(y.string,Ml(t,e+r,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=hr(t,e+r,e+i)),s}function tf(t,e,r,n){return gn(t,e,1,r,n)}function rf(t,e,r,n){return gn(t,e,2,he(t,e+1,n),n)}function nf(t,e,r,n){return gn(t,e,3,pe(t,e+1,n),n)}function of(t,e,r,n){return gn(t,e,5,ye(t,e+1,n),n)}function sf(t,e,r,n){let o=me(t,e+1,n);if(typeof o=="bigint")throw new Error(`${T} 64-bit integer string lengths not supported`);return gn(t,e,9,o,n)}var af=pr;function yr(t,e,r,n){return new E(y.array,n,r)}function cf(t,e,r,n){return yr(t,e,1,r)}function uf(t,e,r,n){return yr(t,e,2,he(t,e+1,n))}function lf(t,e,r,n){return yr(t,e,3,pe(t,e+1,n))}function ff(t,e,r,n){return yr(t,e,5,ye(t,e+1,n))}function df(t,e,r,n){let o=me(t,e+1,n);if(typeof o=="bigint")throw new Error(`${T} 64-bit integer array lengths not supported`);return yr(t,e,9,o)}function hf(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${T} indefinite length items not allowed`);return yr(t,e,1,1/0)}function Ro(t,e){te(t,y.array.majorEncoded,e.value)}Ro.compareTokens=_e.compareTokens;Ro.encodedSize=function(e){return te.encodedSize(e.value)};function mr(t,e,r,n){return new E(y.map,n,r)}function pf(t,e,r,n){return mr(t,e,1,r)}function yf(t,e,r,n){return mr(t,e,2,he(t,e+1,n))}function mf(t,e,r,n){return mr(t,e,3,pe(t,e+1,n))}function gf(t,e,r,n){return mr(t,e,5,ye(t,e+1,n))}function wf(t,e,r,n){let o=me(t,e+1,n);if(typeof o=="bigint")throw new Error(`${T} 64-bit integer map lengths not supported`);return mr(t,e,9,o)}function bf(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${T} indefinite length items not allowed`);return mr(t,e,1,1/0)}function Oo(t,e){te(t,y.map.majorEncoded,e.value)}Oo.compareTokens=_e.compareTokens;Oo.encodedSize=function(e){return te.encodedSize(e.value)};function xf(t,e,r,n){return new E(y.tag,r,1)}function kf(t,e,r,n){return new E(y.tag,he(t,e+1,n),2)}function vf(t,e,r,n){return new E(y.tag,pe(t,e+1,n),3)}function Ef(t,e,r,n){return new E(y.tag,ye(t,e+1,n),5)}function Sf(t,e,r,n){return new E(y.tag,me(t,e+1,n),9)}function zo(t,e){te(t,y.tag.majorEncoded,e.value)}zo.compareTokens=_e.compareTokens;zo.encodedSize=function(e){return te.encodedSize(e.value)};var yb=20,mb=21,gb=22,wb=23;function Af(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${T} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new E(y.null,null,1):new E(y.undefined,void 0,1)}function _f(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${T} indefinite length items not allowed`);return new E(y.break,void 0,1)}function ia(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${T} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${T} Infinity values are not supported`)}return new E(y.float,t,e)}function Bf(t,e,r,n){return ia(sa(t,e+1),3,n)}function Cf(t,e,r,n){return ia(aa(t,e+1),5,n)}function Tf(t,e,r,n){return ia(Nf(t,e+1),9,n)}function $o(t,e,r){let n=e.value;if(n===!1)t.push([y.float.majorEncoded|yb]);else if(n===!0)t.push([y.float.majorEncoded|mb]);else if(n===null)t.push([y.float.majorEncoded|gb]);else if(n===void 0)t.push([y.float.majorEncoded|wb]);else{let o,i=!1;(!r||r.float64!==!0)&&(Lf(n),o=sa(Le,1),n===o||Number.isNaN(n)?(Le[0]=249,t.push(Le.slice(0,3)),i=!0):(Df(n),o=aa(Le,1),n===o&&(Le[0]=250,t.push(Le.slice(0,5)),i=!0))),i||(bb(n),o=Nf(Le,1),Le[0]=251,t.push(Le.slice(0,9)))}}$o.encodedSize=function(e,r){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!r||r.float64!==!0){Lf(n);let o=sa(Le,1);if(n===o||Number.isNaN(n))return 3;if(Df(n),o=aa(Le,1),n===o)return 5}return 9};var If=new ArrayBuffer(9),Be=new DataView(If,1),Le=new Uint8Array(If,0);function Lf(t){if(t===1/0)Be.setUint16(0,31744,!1);else if(t===-1/0)Be.setUint16(0,64512,!1);else if(Number.isNaN(t))Be.setUint16(0,32256,!1);else{Be.setFloat32(0,t);let e=Be.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)Be.setUint16(0,31744,!1);else if(r===0)Be.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let o=r-127;o<-24?Be.setUint16(0,0):o<-14?Be.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Be.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function sa(t,e){if(t.length-e<2)throw new Error(`${T} not enough data for float16`);let r=(t[e]<<8)+t[e+1];if(r===31744)return 1/0;if(r===64512)return-1/0;if(r===32256)return NaN;let n=r>>10&31,o=r&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,r&32768?-i:i}function Df(t){Be.setFloat32(0,t,!1)}function aa(t,e){if(t.length-e<4)throw new Error(`${T} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function bb(t){Be.setFloat64(0,t,!1)}function Nf(t,e){if(t.length-e<8)throw new Error(`${T} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}$o.compareTokens=_e.compareTokens;function R(t,e,r){throw new Error(`${T} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function Ho(t){return()=>{throw new Error(`${T} ${t}`)}}var A=[];for(let t=0;t<=23;t++)A[t]=R;A[24]=$l;A[25]=Hl;A[26]=jl;A[27]=Vl;A[28]=R;A[29]=R;A[30]=R;A[31]=R;for(let t=32;t<=55;t++)A[t]=R;A[56]=ql;A[57]=Wl;A[58]=Kl;A[59]=Ql;A[60]=R;A[61]=R;A[62]=R;A[63]=R;for(let t=64;t<=87;t++)A[t]=Jl;A[88]=Xl;A[89]=Yl;A[90]=Zl;A[91]=ef;A[92]=R;A[93]=R;A[94]=R;A[95]=Ho("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)A[t]=tf;A[120]=rf;A[121]=nf;A[122]=of;A[123]=sf;A[124]=R;A[125]=R;A[126]=R;A[127]=Ho("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)A[t]=cf;A[152]=uf;A[153]=lf;A[154]=ff;A[155]=df;A[156]=R;A[157]=R;A[158]=R;A[159]=hf;for(let t=160;t<=183;t++)A[t]=pf;A[184]=yf;A[185]=mf;A[186]=gf;A[187]=wf;A[188]=R;A[189]=R;A[190]=R;A[191]=bf;for(let t=192;t<=215;t++)A[t]=xf;A[216]=kf;A[217]=vf;A[218]=Ef;A[219]=Sf;A[220]=R;A[221]=R;A[222]=R;A[223]=R;for(let t=224;t<=243;t++)A[t]=Ho("simple values are not supported");A[244]=R;A[245]=R;A[246]=R;A[247]=Af;A[248]=Ho("simple values are not supported");A[249]=Bf;A[250]=Cf;A[251]=Tf;A[252]=R;A[253]=R;A[254]=R;A[255]=_f;var De=[];for(let t=0;t<24;t++)De[t]=new E(y.uint,t,1);for(let t=-1;t>=-24;t--)De[31-t]=new E(y.negint,t,1);De[64]=new E(y.bytes,new Uint8Array(0),1);De[96]=new E(y.string,"",1);De[128]=new E(y.array,0,1);De[160]=new E(y.map,0,1);De[244]=new E(y.false,!1,1);De[245]=new E(y.true,!0,1);De[246]=new E(y.null,null,1);function Uf(t){switch(t.type){case y.false:return $e([244]);case y.true:return $e([245]);case y.null:return $e([246]);case y.bytes:return t.value.length?void 0:$e([64]);case y.string:return t.value===""?$e([96]):void 0;case y.array:return t.value===0?$e([128]):void 0;case y.map:return t.value===0?$e([160]):void 0;case y.uint:return t.value<24?$e([Number(t.value)]):void 0;case y.negint:if(t.value>=-24)return $e([31-Number(t.value)])}}var kb={float64:!1,mapSorter:Sb,quickEncodeToken:Uf};function vb(){let t=[];return t[y.uint.major]=_e,t[y.negint.major]=Fo,t[y.bytes.major]=pr,t[y.string.major]=af,t[y.array.major]=Ro,t[y.map.major]=Oo,t[y.tag.major]=zo,t[y.float.major]=$o,t}var Pf=vb(),ca=new pn,Vo=class t{constructor(e,r){this.obj=e,this.parent=r}includes(e){let r=this;do if(r.obj===e)return!0;while(r=r.parent);return!1}static createCheck(e,r){if(e&&e.includes(r))throw new Error(`${Ze} object contains circular references`);return new t(r,e)}},lt={null:new E(y.null,null),undefined:new E(y.undefined,void 0),true:new E(y.true,!0),false:new E(y.false,!1),emptyArray:new E(y.array,0),emptyMap:new E(y.map,0)},ft={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new E(y.float,t):t>=0?new E(y.uint,t):new E(y.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new E(y.uint,t):new E(y.negint,t)},Uint8Array(t,e,r,n){return new E(y.bytes,t)},string(t,e,r,n){return new E(y.string,t)},boolean(t,e,r,n){return t?lt.true:lt.false},null(t,e,r,n){return lt.null},undefined(t,e,r,n){return lt.undefined},ArrayBuffer(t,e,r,n){return new E(y.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new E(y.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[lt.emptyArray,new E(y.break)]:lt.emptyArray;n=Vo.createCheck(n,t);let o=[],i=0;for(let s of t)o[i++]=jo(s,r,n);return r.addBreakTokens?[new E(y.array,t.length),o,new E(y.break)]:[new E(y.array,t.length),o]},Object(t,e,r,n){let o=e!=="Object",i=o?t.keys():Object.keys(t),s=o?t.size:i.length;if(!s)return r.addBreakTokens===!0?[lt.emptyMap,new E(y.break)]:lt.emptyMap;n=Vo.createCheck(n,t);let c=[],a=0;for(let u of i)c[a++]=[jo(u,r,n),jo(o?t.get(u):t[u],r,n)];return Eb(c,r),r.addBreakTokens?[new E(y.map,s),c,new E(y.break)]:[new E(y.map,s),c]}};ft.Map=ft.Object;ft.Buffer=ft.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))ft[`${t}Array`]=ft.DataView;function jo(t,e={},r){let n=Nl(t),o=e&&e.typeEncoders&&e.typeEncoders[n]||ft[n];if(typeof o=="function"){let s=o(t,n,e,r);if(s!=null)return s}let i=ft[n];if(!i)throw new Error(`${Ze} unsupported type: ${n}`);return i(t,n,e,r)}function Eb(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Sb(t,e){let r=Array.isArray(t[0])?t[0][0]:t[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(r.type!==n.type)return r.type.compare(n.type);let o=r.type.major,i=Pf[o].compareTokens(r,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function Ff(t,e,r,n){if(Array.isArray(e))for(let o of e)Ff(t,o,r,n);else r[e.type.major](t,e,n)}function ua(t,e,r){let n=jo(t,r);if(!Array.isArray(n)&&r.quickEncodeToken){let o=r.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,r),c=new pn(s);if(i(c,n,r),c.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return hn(c.chunks[0])}}return ca.reset(),Ff(ca,n,e,r),ca.toBytes(!0)}function la(t,e){return e=Object.assign({},kb,e),ua(t,Pf,e)}var Ab={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},fa=class{constructor(e,r={}){this.pos=0,this.data=e,this.options=r}done(){return this.pos>=this.data.length}next(){let e=this.data[this.pos],r=De[e];if(r===void 0){let n=A[e];if(!n)throw new Error(`${T} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;r=n(this.data,this.pos,o,this.options)}return this.pos+=r.encodedLength,r}},wn=Symbol.for("DONE"),qo=Symbol.for("BREAK");function _b(t,e,r){let n=[];for(let o=0;o<t.value;o++){let i=bn(e,r);if(i===qo){if(t.value===1/0)break;throw new Error(`${T} got unexpected break to lengthed array`)}if(i===wn)throw new Error(`${T} found array but not enough entries (got ${o}, expected ${t.value})`);n[o]=i}return n}function Bb(t,e,r){let n=r.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<t.value;s++){let c=bn(e,r);if(c===qo){if(t.value===1/0)break;throw new Error(`${T} got unexpected break to lengthed map`)}if(c===wn)throw new Error(`${T} found map but not enough entries (got ${s} [no key], expected ${t.value})`);if(n!==!0&&typeof c!="string")throw new Error(`${T} non-string keys not supported (got ${typeof c})`);if(r.rejectDuplicateMapKeys===!0&&(n&&i.has(c)||!n&&c in o))throw new Error(`${T} found repeat map key "${c}"`);let a=bn(e,r);if(a===wn)throw new Error(`${T} found map but not enough entries (got ${s} [no value], expected ${t.value})`);n?i.set(c,a):o[c]=a}return n?i:o}function bn(t,e){if(t.done())return wn;let r=t.next();if(r.type===y.break)return qo;if(r.type.terminal)return r.value;if(r.type===y.array)return _b(r,t,e);if(r.type===y.map)return Bb(r,t,e);if(r.type===y.tag){if(e.tags&&typeof e.tags[r.value]=="function"){let n=bn(t,e);return e.tags[r.value](n)}throw new Error(`${T} tag not supported (${r.value})`)}throw new Error("unsupported")}function xn(t,e){if(!(t instanceof Uint8Array))throw new Error(`${T} data to decode must be a Uint8Array`);e=Object.assign({},Ab,e);let r=e.tokenizer||new fa(t,e),n=bn(r,e);if(n===wn)throw new Error(`${T} did not find any content to decode`);if(n===qo)throw new Error(`${T} got unexpected break`);if(!r.done())throw new Error(`${T} too many terminals, data makes no sense`);return n}var Tb=Of,Mf=128,Ib=127,Lb=~Ib,Db=Math.pow(2,31);function Of(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Db;)e[r++]=t&255|Mf,t/=128;for(;t&Lb;)e[r++]=t&255|Mf,t>>>=7;return e[r]=t|0,Of.bytes=r-n+1,e}var Nb=da,Ub=128,Rf=127;function da(t,n){var r=0,n=n||0,o=0,i=n,s,c=t.length;do{if(i>=c)throw da.bytes=0,new RangeError("Could not decode varint");s=t[i++],r+=o<28?(s&Rf)<<o:(s&Rf)*Math.pow(2,o),o+=7}while(s>=Ub);return da.bytes=i-n,r}var Pb=Math.pow(2,7),Fb=Math.pow(2,14),Mb=Math.pow(2,21),Rb=Math.pow(2,28),Ob=Math.pow(2,35),zb=Math.pow(2,42),$b=Math.pow(2,49),Hb=Math.pow(2,56),jb=Math.pow(2,63),Vb=function(t){return t<Pb?1:t<Fb?2:t<Mb?3:t<Rb?4:t<Ob?5:t<zb?6:t<$b?7:t<Hb?8:t<jb?9:10},qb={encode:Tb,decode:Nb,encodingLength:Vb},Wb=qb,kn=Wb;var vn=(t,e=0)=>[kn.decode(t,e),kn.decode.bytes],gr=(t,e,r=0)=>(kn.encode(t,e,r),e),wr=t=>kn.encodingLength(t);var Nt={};G(Nt,{coerce:()=>ie,empty:()=>zf,equals:()=>pa,fromHex:()=>Gb,fromString:()=>Jb,isBinary:()=>Qb,toHex:()=>Kb,toString:()=>Xb});var zf=new Uint8Array(0),Kb=t=>t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),""),Gb=t=>{let e=t.match(/../g);return e?new Uint8Array(e.map(r=>parseInt(r,16))):zf},pa=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},ie=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},Qb=t=>t instanceof ArrayBuffer||ArrayBuffer.isView(t),Jb=t=>new TextEncoder().encode(t),Xb=t=>new TextDecoder().decode(t);var Ut=(t,e)=>{let r=e.byteLength,n=wr(t),o=n+wr(r),i=new Uint8Array(o+r);return gr(t,i,0),gr(r,i,n),i.set(e,o),new br(t,r,e,i)},Wo=t=>{let e=ie(t),[r,n]=vn(e),[o,i]=vn(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new br(r,o,s,e)},$f=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&pa(t.bytes,r.bytes)}},br=class{constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};function Yb(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<t.length;o++){var i=t.charAt(o),s=i.charCodeAt(0);if(r[s]!==255)throw new TypeError(i+" is ambiguous");r[s]=o}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),l=Math.log(256)/Math.log(c);function d(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var p=0,w=0,g=0,b=h.length;g!==b&&h[g]===0;)g++,p++;for(var k=(b-g)*l+1>>>0,v=new Uint8Array(k);g!==b;){for(var C=h[g],N=0,S=k-1;(C!==0||N<w)&&S!==-1;S--,N++)C+=256*v[S]>>>0,v[S]=C%c>>>0,C=C/c>>>0;if(C!==0)throw new Error("Non-zero carry");w=N,g++}for(var U=k-w;U!==k&&v[U]===0;)U++;for(var ue=a.repeat(p);U<k;++U)ue+=t.charAt(v[U]);return ue}function m(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var p=0;if(h[p]!==" "){for(var w=0,g=0;h[p]===a;)w++,p++;for(var b=(h.length-p)*u+1>>>0,k=new Uint8Array(b);h[p];){var v=r[h.charCodeAt(p)];if(v===255)return;for(var C=0,N=b-1;(v!==0||C<g)&&N!==-1;N--,C++)v+=c*k[N]>>>0,k[N]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");g=C,p++}if(h[p]!==" "){for(var S=b-g;S!==b&&k[S]===0;)S++;for(var U=new Uint8Array(w+(b-S)),ue=w;S!==b;)U[ue++]=k[S++];return U}}}function f(h){var p=m(h);if(p)return p;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:m,decode:f}}var Zb=Yb,e0=Zb,Hf=e0;var ya=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ma=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return jf(this,e)}},ga=class{constructor(e){this.decoders=e}or(e){return jf(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},jf=(t,e)=>new ga({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),wa=class{constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new ya(e,r,n),this.decoder=new ma(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Vf=({name:t,prefix:e,encode:r,decode:n})=>new wa(t,e,r,n),ba=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:o}=Hf(r,e);return Vf({prefix:t,name:e,encode:n,decode:i=>ie(o(i))})},t0=(t,e,r,n)=>{let o={};for(let l=0;l<e.length;++l)o[e[l]]=l;let i=t.length;for(;t[i-1]==="=";)--i;let s=new Uint8Array(i*r/8|0),c=0,a=0,u=0;for(let l=0;l<i;++l){let d=o[t[l]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|d,c+=r,c>=8&&(c-=8,s[u++]=255&a>>c)}if(c>=r||255&a<<8-c)throw new SyntaxError("Unexpected end of data");return s},r0=(t,e,r)=>{let n=e[e.length-1]==="=",o=(1<<r)-1,i="",s=0,c=0;for(let a=0;a<t.length;++a)for(c=c<<8|t[a],s+=8;s>r;)s-=r,i+=e[o&c>>s];if(s&&(i+=e[o&c<<r-s]),n)for(;i.length*r&7;)i+="=";return i},se=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Vf({prefix:e,name:t,encode(o){return r0(o,n,r)},decode(o){return t0(o,n,r,t)}});var tt=ba({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),HS=ba({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Sn=se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),qS=se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),WS=se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),KS=se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),GS=se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),QS=se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),JS=se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),XS=se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),YS=se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var qf=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return o0(r,xa(t),e||tt.encoder);default:return i0(r,xa(t),e||Sn.encoder)}};var Wf=new WeakMap,xa=t=>{let e=Wf.get(t);if(e==null){let r=new Map;return Wf.set(t,r),r}return e},j=class t{constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==An)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==s0)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Ut(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return t.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&$f(e.multihash,n.multihash)}toString(e){return qf(this,e)}toJSON(){return{"/":qf(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:i,bytes:s}=r;return new t(n,o,i,s||Kf(n,o,i.bytes))}else if(r[a0]===!0){let{version:n,multihash:o,code:i}=r,s=Wo(o);return t.create(n,i,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==An)throw new Error(`Version 0 CID must use dag-pb (code: ${An}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=Kf(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,An,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=ie(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let i=o.subarray(r.multihashSize-r.digestSize),s=new br(r.multihashCode,r.digestSize,i,o);return[r.version===0?t.createV0(s):t.createV1(r.codec,s),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[d,m]=vn(e.subarray(r));return r+=m,d},o=n(),i=An;if(o===18?(o=0,r=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=r,c=n(),a=n(),u=r+a,l=u-s;return{version:o,codec:i,multihashCode:c,digestSize:a,multihashSize:l,size:u}}static parse(e,r){let[n,o]=n0(e,r),i=t.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return xa(i).set(n,e),i}},n0=(t,e)=>{switch(t[0]){case"Q":{let r=e||tt;return[tt.prefix,r.decode(`${tt.prefix}${t}`)]}case tt.prefix:{let r=e||tt;return[tt.prefix,r.decode(t)]}case Sn.prefix:{let r=e||Sn;return[Sn.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},o0=(t,e,r)=>{let{prefix:n}=r;if(n!==tt.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let i=r.encode(t).slice(1);return e.set(n,i),i}else return o},i0=(t,e,r)=>{let{prefix:n}=r,o=e.get(n);if(o==null){let i=r.encode(t);return e.set(n,i),i}else return o},An=112,s0=18,Kf=(t,e,r)=>{let n=wr(t),o=n+wr(e),i=new Uint8Array(o+r.byteLength);return gr(t,i,0),gr(e,i,n),i.set(r,o),i},a0=Symbol.for("@ipld/js-cid/CID");var Gf=42;function c0(t){if(t.asCID!==t&&t["/"]!==t.bytes)return null;let e=j.asCID(t);if(!e)return null;let r=new Uint8Array(e.bytes.byteLength+1);return r.set(e.bytes,1),[new E(y.tag,Gf),new E(y.bytes,r)]}function u0(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function l0(t){if(Number.isNaN(t))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(t===1/0||t===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var f0={float64:!0,typeEncoders:{Object:c0,undefined:u0,number:l0}};function d0(t){if(t[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return j.decode(t.subarray(1))}var Qf={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Qf.tags[Gf]=d0;var h0="dag-cbor",ka=113,Ko=t=>la(t,f0),xr=t=>xn(t,Qf);var dt={Null:t=>t===null,Int:t=>Number.isInteger(t),Float:t=>typeof t=="number"&&Number.isFinite(t),String:t=>typeof t=="string",Bool:t=>typeof t=="boolean",Bytes:t=>t instanceof Uint8Array,Link:t=>!dt.Null(t)&&typeof t=="object"&&t.asCID===t,List:t=>Array.isArray(t),Map:t=>!dt.Null(t)&&typeof t=="object"&&t.asCID!==t&&!dt.List(t)&&!dt.Bytes(t)},kr={Int:dt.Int,"CarHeader > version":t=>kr.Int(t),"CarHeader > roots (anon) > valueType (anon)":dt.Link,"CarHeader > roots (anon)":t=>dt.List(t)&&Array.prototype.every.call(t,kr["CarHeader > roots (anon) > valueType (anon)"]),"CarHeader > roots":t=>kr["CarHeader > roots (anon)"](t),CarHeader:t=>{let e=t&&Object.keys(t);return dt.Map(t)&&["version"].every(r=>e.includes(r))&&Object.entries(t).every(([r,n])=>kr["CarHeader > "+r]&&kr["CarHeader > "+r](n))}},va=kr.CarHeader;var ht=V(Go(),1),_n={SHA2_256:18,LENGTH:32,DAG_PB:112},Aa=16+8+8+8;function vr(t,e){if(!t.length)throw new Error("Unexpected end of data");let r=ht.default.decode(t);return e.seek(ht.default.decode.bytes),r}function _a(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0;return{version:2,characteristics:[e.getBigUint64(r,!0),e.getBigUint64(r+=8,!0)],dataOffset:Number(e.getBigUint64(r+=8,!0)),dataSize:Number(e.getBigUint64(r+=8,!0)),indexOffset:Number(e.getBigUint64(r+=8,!0))}}function Ba(t){ht.default.decode(t);let e=ht.default.decode.bytes,r=ht.default.decode(t.subarray(ht.default.decode.bytes)),n=ht.default.decode.bytes;return e+n+r}async function Qo(t,e){let r=vr(await t.upTo(8),t);if(r===0)throw new Error("Invalid CAR header (zero length)");let n=await t.exactly(r,!0),o=xr(n);if(!va(o))throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||e!==void 0&&o.version!==e)throw new Error(`Invalid CAR version: ${o.version}${e!==void 0?` (expected ${e})`:""}`);let i=Array.isArray(o.roots);if(o.version===1&&!i||o.version===2&&i)throw new Error("Invalid CAR header format");if(o.version===1)return o;let s=_a(await t.exactly(Aa,!0));t.seek(s.dataOffset-t.pos);let c=await Qo(t,1);return Object.assign(c,s)}async function B0(t){let e=await t.exactly(2,!1);if(e[0]===_n.SHA2_256&&e[1]===_n.LENGTH){let s=await t.exactly(34,!0),c=ur(s);return H.create(0,_n.DAG_PB,c)}let r=vr(await t.upTo(8),t);if(r!==1)throw new Error(`Unexpected CID version (${r})`);let n=vr(await t.upTo(8),t),o=await t.exactly(Ba(await t.upTo(8)),!0),i=ur(o);return H.create(r,n,i)}async function id(t){let e=t.pos,r=vr(await t.upTo(8),t);if(r===0)throw new Error("Invalid CAR section (zero length)");r+=t.pos-e;let n=await B0(t),o=r-Number(t.pos-e);return{cid:n,length:r,blockLength:o}}async function C0(t){let{cid:e,blockLength:r}=await id(t);return{bytes:await t.exactly(r,!0),cid:e}}async function T0(t){let e=t.pos,{cid:r,length:n,blockLength:o}=await id(t),i={cid:r,length:n,blockLength:o,offset:e,blockOffset:t.pos};return t.seek(i.blockLength),i}function Er(t){let e=(async()=>{let r=await Qo(t);if(r.version===2){let n=t.pos-r.dataOffset;t=I0(t,r.dataSize-n)}return r})();return{header:()=>e,async*blocks(){for(await e;(await t.upTo(8)).length>0;)yield await C0(t)},async*blocksIndex(){for(await e;(await t.upTo(8)).length>0;)yield await T0(t)}}}function Pt(t){let e=0;return{async upTo(r){return t.subarray(e,e+Math.min(r,t.length-e))},async exactly(r,n=!1){if(r>t.length-e)throw new Error("Unexpected end of data");let o=t.subarray(e,e+r);return n&&(e+=r),o},seek(r){e+=r},get pos(){return e}}}function sd(t){let e=0,r=0,n=0,o=new Uint8Array(0),i=async s=>{r=o.length-n;let c=[o.subarray(n)];for(;r<s;){let u=await t();if(u==null)break;r<0?u.length>r&&c.push(u.subarray(-r)):c.push(u),r+=u.length}o=new Uint8Array(c.reduce((u,l)=>u+l.length,0));let a=0;for(let u of c)o.set(u,a),a+=u.length;n=0};return{async upTo(s){return o.length-n<s&&await i(s),o.subarray(n,n+Math.min(o.length-n,s))},async exactly(s,c=!1){if(o.length-n<s&&await i(s),o.length-n<s)throw new Error("Unexpected end of data");let a=o.subarray(n,n+s);return c&&(e+=s,n+=s),a},seek(s){e+=s,n+=s},get pos(){return e}}}function Sr(t){let e=t[Symbol.asyncIterator]();async function r(){let n=await e.next();return n.done?null:n.value}return sd(r)}function I0(t,e){let r=0;return{async upTo(n){let o=await t.upTo(n);return o.length+r>e&&(o=o.subarray(0,e-r)),o},async exactly(n,o=!1){let i=await t.exactly(n,o);if(i.length+r>e)throw new Error("Unexpected end of data");return o&&(r+=n),i},seek(n){r+=n,t.seek(n)},get pos(){return t.pos}}}var Bn=class{constructor(e,r){this._header=e,this._blocks=r,this._keys=r.map(n=>n.cid.toString())}get version(){return this._header.version}async getRoots(){return this._header.roots}async has(e){return this._keys.indexOf(e.toString())>-1}async get(e){let r=this._keys.indexOf(e.toString());return r>-1?this._blocks[r]:void 0}async*blocks(){for(let e of this._blocks)yield e}async*cids(){for(let e of this._blocks)yield e.cid}static async fromBytes(e){if(!(e instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return ad(Pt(e))}static async fromIterable(e){if(!e||typeof e[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return ad(Sr(e))}};async function ad(t){let e=Er(t),r=await e.header(),n=[];for await(let o of e.blocks())n.push(o);return new Bn(r,n)}var L0=(0,ud.promisify)(cd.default.read),Ar=class extends Bn{static async readRaw(e,r){let{cid:n,blockLength:o,blockOffset:i}=r,s=new Uint8Array(o),c;if(typeof e=="number")c=(await L0(e,s,0,o,i)).bytesRead;else if(typeof e=="object"&&typeof e.read=="function")c=(await e.read(s,0,o,i)).bytesRead;else throw new TypeError("Bad fd");if(c!==o)throw new Error(`Failed to read entire block (${c} instead of ${o})`);return{cid:n,bytes:s}}};var ld=V(require("fs"),1);var TA=ld.default.readSync;var Cn=class{constructor(e,r,n){this._version=e,this._roots=r,this._iterator=n}get version(){return this._version}async getRoots(){return this._roots}[Symbol.asyncIterator](){return this._iterator}static async fromBytes(e){if(!(e instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return fd(Pt(e))}static async fromIterable(e){if(!e||typeof e[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return fd(Sr(e))}};async function fd(t){let e=Er(t),{version:r,roots:n}=await e.header();return new Cn(r,n,e.blocksIndex())}var Jo=class{constructor(e,r,n){this._version=e,this._roots=r,this._iterable=n,this._decoded=!1}get version(){return this._version}async getRoots(){return this._roots}},Ca=class t extends Jo{[Symbol.asyncIterator](){if(this._decoded)throw new Error("Cannot decode more than once");if(!this._iterable)throw new Error("Block iterable not found");return this._decoded=!0,this._iterable[Symbol.asyncIterator]()}static async fromBytes(e){let{version:r,roots:n,iterator:o}=await dd(e);return new t(r,n,o)}static async fromIterable(e){let{version:r,roots:n,iterator:o}=await hd(e);return new t(r,n,o)}},Ta=class t extends Jo{[Symbol.asyncIterator](){if(this._decoded)throw new Error("Cannot decode more than once");if(!this._iterable)throw new Error("Block iterable not found");this._decoded=!0;let e=this._iterable[Symbol.asyncIterator]();return{async next(){let r=await e.next();return r.done?r:{done:!1,value:r.value.cid}}}}static async fromBytes(e){let{version:r,roots:n,iterator:o}=await dd(e);return new t(r,n,o)}static async fromIterable(e){let{version:r,roots:n,iterator:o}=await hd(e);return new t(r,n,o)}};async function dd(t){if(!(t instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return pd(Pt(t))}async function hd(t){if(!t||typeof t[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return pd(Sr(t))}async function pd(t){let e=Er(t),{version:r,roots:n}=await e.header();return{version:r,roots:n,iterator:e.blocks()}}var Ia=V(require("fs"),1),La=require("util");var N0=V(Go(),1);var yd=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};var QA=(0,La.promisify)(Ia.default.read),JA=(0,La.promisify)(Ia.default.write);var Dn=V(Go(),1);var P0=["string","number","bigint","symbol"],F0=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function md(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(P0.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(M0(t))return"Buffer";let r=R0(t);return r||"Object"}function M0(t){return t&&t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer.call(null,t)}function R0(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(F0.includes(e))return e}var x=class{constructor(e,r,n){this.major=e,this.majorEncoded=e<<5,this.name=r,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};x.uint=new x(0,"uint",!0);x.negint=new x(1,"negint",!0);x.bytes=new x(2,"bytes",!0);x.string=new x(3,"string",!0);x.array=new x(4,"array",!1);x.map=new x(5,"map",!1);x.tag=new x(6,"tag",!1);x.float=new x(7,"float",!0);x.false=new x(7,"false",!0);x.true=new x(7,"true",!0);x.null=new x(7,"null",!0);x.undefined=new x(7,"undefined",!0);x.break=new x(7,"break",!0);var B=class{constructor(e,r,n){this.type=e,this.value=r,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var _r=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",O0=new TextDecoder,z0=new TextEncoder;function Xo(t){return _r&&globalThis.Buffer.isBuffer(t)}function xd(t){return t instanceof Uint8Array?Xo(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var kd=_r?(t,e,r)=>r-e>64?globalThis.Buffer.from(t.subarray(e,r)).toString("utf8"):wd(t,e,r):(t,e,r)=>r-e>64?O0.decode(t.subarray(e,r)):wd(t,e,r),vd=_r?t=>t.length>64?globalThis.Buffer.from(t):gd(t):t=>t.length>64?z0.encode(t):gd(t),He=t=>Uint8Array.from(t),Br=_r?(t,e,r)=>Xo(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),Ed=_r?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),xd(globalThis.Buffer.concat(t,e))):(t,e)=>{let r=new Uint8Array(e),n=0;for(let o of t)n+o.length>r.length&&(o=o.subarray(0,r.length-n)),r.set(o,n),n+=o.length;return r},Sd=_r?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function Ad(t,e){if(Xo(t)&&Xo(e))return t.compare(e);for(let r=0;r<t.length;r++)if(t[r]!==e[r])return t[r]<e[r]?-1:1;return 0}function gd(t,e=1/0){let r,n=t.length,o=null,i=[];for(let s=0;s<n;++s){if(r=t.charCodeAt(s),r>55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),o=r;continue}r=(o-55296<<10|r-56320)+65536}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return i}function wd(t,e,r){let n=[];for(;e<r;){let o=t[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=r){let c,a,u,l;switch(s){case 1:o<128&&(i=o);break;case 2:c=t[e+1],(c&192)===128&&(l=(o&31)<<6|c&63,l>127&&(i=l));break;case 3:c=t[e+1],a=t[e+2],(c&192)===128&&(a&192)===128&&(l=(o&15)<<12|(c&63)<<6|a&63,l>2047&&(l<55296||l>57343)&&(i=l));break;case 4:c=t[e+1],a=t[e+2],u=t[e+3],(c&192)===128&&(a&192)===128&&(u&192)===128&&(l=(o&15)<<18|(c&63)<<12|(a&63)<<6|u&63,l>65535&&l<1114112&&(i=l))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return $0(n)}var bd=4096;function $0(t){let e=t.length;if(e<=bd)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=bd));return r}var H0=256,Yo=class{constructor(e=H0){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let r=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=r.length-(this.maxCursor-this.cursor)-1;r.set(e,o)}else{if(r){let o=r.length-(this.maxCursor-this.cursor)-1;o<r.length&&(this.chunks[this.chunks.length-1]=r.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(r=Sd(this.chunkSize),this.chunks.push(r),this.maxCursor+=r.length,this._initReuseChunk===null&&(this._initReuseChunk=r),r.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let r;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(r=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):r=Br(n,0,this.cursor)}else r=Ed(this.chunks,this.cursor);return e&&this.reset(),r}};var O="CBOR decode error:",Da="CBOR encode error:",Tn=[];Tn[23]=1;Tn[24]=2;Tn[25]=3;Tn[26]=5;Tn[27]=9;function rt(t,e,r){if(t.length-e<r)throw new Error(`${O} not enough data for type`)}var Z=[24,256,65536,4294967296,BigInt("18446744073709551616")];function ge(t,e,r){rt(t,e,1);let n=t[e];if(r.strict===!0&&n<Z[0])throw new Error(`${O} integer encoded in more bytes than necessary (strict decode)`);return n}function we(t,e,r){rt(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<Z[1])throw new Error(`${O} integer encoded in more bytes than necessary (strict decode)`);return n}function be(t,e,r){rt(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<Z[2])throw new Error(`${O} integer encoded in more bytes than necessary (strict decode)`);return n}function xe(t,e,r){rt(t,e,8);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3],o=t[e+4]*16777216+(t[e+5]<<16)+(t[e+6]<<8)+t[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(r.strict===!0&&i<Z[3])throw new Error(`${O} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(r.allowBigInt===!0)return i;throw new Error(`${O} integers outside of the safe integer range are not supported`)}function _d(t,e,r,n){return new B(x.uint,ge(t,e+1,n),2)}function Bd(t,e,r,n){return new B(x.uint,we(t,e+1,n),3)}function Cd(t,e,r,n){return new B(x.uint,be(t,e+1,n),5)}function Td(t,e,r,n){return new B(x.uint,xe(t,e+1,n),9)}function Ce(t,e){return re(t,0,e.value)}function re(t,e,r){if(r<Z[0]){let n=Number(r);t.push([e|n])}else if(r<Z[1]){let n=Number(r);t.push([e|24,n])}else if(r<Z[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<Z[3]){let n=Number(r);t.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(r);if(n<Z[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,t.push(o)}else throw new Error(`${O} encountered BigInt larger than allowable range`)}}Ce.encodedSize=function(e){return re.encodedSize(e.value)};re.encodedSize=function(e){return e<Z[0]?1:e<Z[1]?2:e<Z[2]?3:e<Z[3]?5:9};Ce.compareTokens=function(e,r){return e.value<r.value?-1:e.value>r.value?1:0};function Id(t,e,r,n){return new B(x.negint,-1-ge(t,e+1,n),2)}function Ld(t,e,r,n){return new B(x.negint,-1-we(t,e+1,n),3)}function Dd(t,e,r,n){return new B(x.negint,-1-be(t,e+1,n),5)}var Na=BigInt(-1),Nd=BigInt(1);function Ud(t,e,r,n){let o=xe(t,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new B(x.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${O} integers outside of the safe integer range are not supported`);return new B(x.negint,Na-BigInt(o),9)}function Zo(t,e){let r=e.value,n=typeof r=="bigint"?r*Na-Nd:r*-1-1;re(t,e.type.majorEncoded,n)}Zo.encodedSize=function(e){let r=e.value,n=typeof r=="bigint"?r*Na-Nd:r*-1-1;return n<Z[0]?1:n<Z[1]?2:n<Z[2]?3:n<Z[3]?5:9};Zo.compareTokens=function(e,r){return e.value<r.value?1:e.value>r.value?-1:0};function In(t,e,r,n){rt(t,e,r+n);let o=Br(t,e+r,e+r+n);return new B(x.bytes,o,r+n)}function Pd(t,e,r,n){return In(t,e,1,r)}function Fd(t,e,r,n){return In(t,e,2,ge(t,e+1,n))}function Md(t,e,r,n){return In(t,e,3,we(t,e+1,n))}function Rd(t,e,r,n){return In(t,e,5,be(t,e+1,n))}function Od(t,e,r,n){let o=xe(t,e+1,n);if(typeof o=="bigint")throw new Error(`${O} 64-bit integer bytes lengths not supported`);return In(t,e,9,o)}function ei(t){return t.encodedBytes===void 0&&(t.encodedBytes=t.type===x.string?vd(t.value):t.value),t.encodedBytes}function Cr(t,e){let r=ei(e);re(t,e.type.majorEncoded,r.length),t.push(r)}Cr.encodedSize=function(e){let r=ei(e);return re.encodedSize(r.length)+r.length};Cr.compareTokens=function(e,r){return V0(ei(e),ei(r))};function V0(t,e){return t.length<e.length?-1:t.length>e.length?1:Ad(t,e)}function Ln(t,e,r,n,o){let i=r+n;rt(t,e,i);let s=new B(x.string,kd(t,e+r,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Br(t,e+r,e+i)),s}function zd(t,e,r,n){return Ln(t,e,1,r,n)}function $d(t,e,r,n){return Ln(t,e,2,ge(t,e+1,n),n)}function Hd(t,e,r,n){return Ln(t,e,3,we(t,e+1,n),n)}function jd(t,e,r,n){return Ln(t,e,5,be(t,e+1,n),n)}function Vd(t,e,r,n){let o=xe(t,e+1,n);if(typeof o=="bigint")throw new Error(`${O} 64-bit integer string lengths not supported`);return Ln(t,e,9,o,n)}var qd=Cr;function Tr(t,e,r,n){return new B(x.array,n,r)}function Wd(t,e,r,n){return Tr(t,e,1,r)}function Kd(t,e,r,n){return Tr(t,e,2,ge(t,e+1,n))}function Gd(t,e,r,n){return Tr(t,e,3,we(t,e+1,n))}function Qd(t,e,r,n){return Tr(t,e,5,be(t,e+1,n))}function Jd(t,e,r,n){let o=xe(t,e+1,n);if(typeof o=="bigint")throw new Error(`${O} 64-bit integer array lengths not supported`);return Tr(t,e,9,o)}function Xd(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${O} indefinite length items not allowed`);return Tr(t,e,1,1/0)}function ti(t,e){re(t,x.array.majorEncoded,e.value)}ti.compareTokens=Ce.compareTokens;ti.encodedSize=function(e){return re.encodedSize(e.value)};function Ir(t,e,r,n){return new B(x.map,n,r)}function Yd(t,e,r,n){return Ir(t,e,1,r)}function Zd(t,e,r,n){return Ir(t,e,2,ge(t,e+1,n))}function eh(t,e,r,n){return Ir(t,e,3,we(t,e+1,n))}function th(t,e,r,n){return Ir(t,e,5,be(t,e+1,n))}function rh(t,e,r,n){let o=xe(t,e+1,n);if(typeof o=="bigint")throw new Error(`${O} 64-bit integer map lengths not supported`);return Ir(t,e,9,o)}function nh(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${O} indefinite length items not allowed`);return Ir(t,e,1,1/0)}function ri(t,e){re(t,x.map.majorEncoded,e.value)}ri.compareTokens=Ce.compareTokens;ri.encodedSize=function(e){return re.encodedSize(e.value)};function oh(t,e,r,n){return new B(x.tag,r,1)}function ih(t,e,r,n){return new B(x.tag,ge(t,e+1,n),2)}function sh(t,e,r,n){return new B(x.tag,we(t,e+1,n),3)}function ah(t,e,r,n){return new B(x.tag,be(t,e+1,n),5)}function ch(t,e,r,n){return new B(x.tag,xe(t,e+1,n),9)}function ni(t,e){re(t,x.tag.majorEncoded,e.value)}ni.compareTokens=Ce.compareTokens;ni.encodedSize=function(e){return re.encodedSize(e.value)};var J0=20,X0=21,Y0=22,Z0=23;function uh(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${O} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new B(x.null,null,1):new B(x.undefined,void 0,1)}function lh(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${O} indefinite length items not allowed`);return new B(x.break,void 0,1)}function Ua(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${O} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${O} Infinity values are not supported`)}return new B(x.float,t,e)}function fh(t,e,r,n){return Ua(Pa(t,e+1),3,n)}function dh(t,e,r,n){return Ua(Fa(t,e+1),5,n)}function hh(t,e,r,n){return Ua(gh(t,e+1),9,n)}function oi(t,e,r){let n=e.value;if(n===!1)t.push([x.float.majorEncoded|J0]);else if(n===!0)t.push([x.float.majorEncoded|X0]);else if(n===null)t.push([x.float.majorEncoded|Y0]);else if(n===void 0)t.push([x.float.majorEncoded|Z0]);else{let o,i=!1;(!r||r.float64!==!0)&&(yh(n),o=Pa(Ne,1),n===o||Number.isNaN(n)?(Ne[0]=249,t.push(Ne.slice(0,3)),i=!0):(mh(n),o=Fa(Ne,1),n===o&&(Ne[0]=250,t.push(Ne.slice(0,5)),i=!0))),i||(e1(n),o=gh(Ne,1),Ne[0]=251,t.push(Ne.slice(0,9)))}}oi.encodedSize=function(e,r){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!r||r.float64!==!0){yh(n);let o=Pa(Ne,1);if(n===o||Number.isNaN(n))return 3;if(mh(n),o=Fa(Ne,1),n===o)return 5}return 9};var ph=new ArrayBuffer(9),Te=new DataView(ph,1),Ne=new Uint8Array(ph,0);function yh(t){if(t===1/0)Te.setUint16(0,31744,!1);else if(t===-1/0)Te.setUint16(0,64512,!1);else if(Number.isNaN(t))Te.setUint16(0,32256,!1);else{Te.setFloat32(0,t);let e=Te.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)Te.setUint16(0,31744,!1);else if(r===0)Te.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let o=r-127;o<-24?Te.setUint16(0,0):o<-14?Te.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Te.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function Pa(t,e){if(t.length-e<2)throw new Error(`${O} not enough data for float16`);let r=(t[e]<<8)+t[e+1];if(r===31744)return 1/0;if(r===64512)return-1/0;if(r===32256)return NaN;let n=r>>10&31,o=r&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,r&32768?-i:i}function mh(t){Te.setFloat32(0,t,!1)}function Fa(t,e){if(t.length-e<4)throw new Error(`${O} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function e1(t){Te.setFloat64(0,t,!1)}function gh(t,e){if(t.length-e<8)throw new Error(`${O} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}oi.compareTokens=Ce.compareTokens;function z(t,e,r){throw new Error(`${O} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function ii(t){return()=>{throw new Error(`${O} ${t}`)}}var _=[];for(let t=0;t<=23;t++)_[t]=z;_[24]=_d;_[25]=Bd;_[26]=Cd;_[27]=Td;_[28]=z;_[29]=z;_[30]=z;_[31]=z;for(let t=32;t<=55;t++)_[t]=z;_[56]=Id;_[57]=Ld;_[58]=Dd;_[59]=Ud;_[60]=z;_[61]=z;_[62]=z;_[63]=z;for(let t=64;t<=87;t++)_[t]=Pd;_[88]=Fd;_[89]=Md;_[90]=Rd;_[91]=Od;_[92]=z;_[93]=z;_[94]=z;_[95]=ii("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)_[t]=zd;_[120]=$d;_[121]=Hd;_[122]=jd;_[123]=Vd;_[124]=z;_[125]=z;_[126]=z;_[127]=ii("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)_[t]=Wd;_[152]=Kd;_[153]=Gd;_[154]=Qd;_[155]=Jd;_[156]=z;_[157]=z;_[158]=z;_[159]=Xd;for(let t=160;t<=183;t++)_[t]=Yd;_[184]=Zd;_[185]=eh;_[186]=th;_[187]=rh;_[188]=z;_[189]=z;_[190]=z;_[191]=nh;for(let t=192;t<=215;t++)_[t]=oh;_[216]=ih;_[217]=sh;_[218]=ah;_[219]=ch;_[220]=z;_[221]=z;_[222]=z;_[223]=z;for(let t=224;t<=243;t++)_[t]=ii("simple values are not supported");_[244]=z;_[245]=z;_[246]=z;_[247]=uh;_[248]=ii("simple values are not supported");_[249]=fh;_[250]=dh;_[251]=hh;_[252]=z;_[253]=z;_[254]=z;_[255]=lh;var je=[];for(let t=0;t<24;t++)je[t]=new B(x.uint,t,1);for(let t=-1;t>=-24;t--)je[31-t]=new B(x.negint,t,1);je[64]=new B(x.bytes,new Uint8Array(0),1);je[96]=new B(x.string,"",1);je[128]=new B(x.array,0,1);je[160]=new B(x.map,0,1);je[244]=new B(x.false,!1,1);je[245]=new B(x.true,!0,1);je[246]=new B(x.null,null,1);function Ma(t){switch(t.type){case x.false:return He([244]);case x.true:return He([245]);case x.null:return He([246]);case x.bytes:return t.value.length?void 0:He([64]);case x.string:return t.value===""?He([96]):void 0;case x.array:return t.value===0?He([128]):void 0;case x.map:return t.value===0?He([160]):void 0;case x.uint:return t.value<24?He([Number(t.value)]):void 0;case x.negint:if(t.value>=-24)return He([31-Number(t.value)])}}function Ra(){let t=[];return t[x.uint.major]=Ce,t[x.negint.major]=Zo,t[x.bytes.major]=Cr,t[x.string.major]=qd,t[x.array.major]=ti,t[x.map.major]=ri,t[x.tag.major]=ni,t[x.float.major]=oi,t}var q_=Ra(),W_=new Yo,ai=class t{constructor(e,r){this.obj=e,this.parent=r}includes(e){let r=this;do if(r.obj===e)return!0;while(r=r.parent);return!1}static createCheck(e,r){if(e&&e.includes(r))throw new Error(`${Da} object contains circular references`);return new t(r,e)}},pt={null:new B(x.null,null),undefined:new B(x.undefined,void 0),true:new B(x.true,!0),false:new B(x.false,!1),emptyArray:new B(x.array,0),emptyMap:new B(x.map,0)},yt={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new B(x.float,t):t>=0?new B(x.uint,t):new B(x.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new B(x.uint,t):new B(x.negint,t)},Uint8Array(t,e,r,n){return new B(x.bytes,t)},string(t,e,r,n){return new B(x.string,t)},boolean(t,e,r,n){return t?pt.true:pt.false},null(t,e,r,n){return pt.null},undefined(t,e,r,n){return pt.undefined},ArrayBuffer(t,e,r,n){return new B(x.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new B(x.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[pt.emptyArray,new B(x.break)]:pt.emptyArray;n=ai.createCheck(n,t);let o=[],i=0;for(let s of t)o[i++]=si(s,r,n);return r.addBreakTokens?[new B(x.array,t.length),o,new B(x.break)]:[new B(x.array,t.length),o]},Object(t,e,r,n){let o=e!=="Object",i=o?t.keys():Object.keys(t),s=o?t.size:i.length;if(!s)return r.addBreakTokens===!0?[pt.emptyMap,new B(x.break)]:pt.emptyMap;n=ai.createCheck(n,t);let c=[],a=0;for(let u of i)c[a++]=[si(u,r,n),si(o?t.get(u):t[u],r,n)];return r1(c,r),r.addBreakTokens?[new B(x.map,s),c,new B(x.break)]:[new B(x.map,s),c]}};yt.Map=yt.Object;yt.Buffer=yt.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))yt[`${t}Array`]=yt.DataView;function si(t,e={},r){let n=md(t),o=e&&e.typeEncoders&&e.typeEncoders[n]||yt[n];if(typeof o=="function"){let s=o(t,n,e,r);if(s!=null)return s}let i=yt[n];if(!i)throw new Error(`${Da} unsupported type: ${n}`);return i(t,n,e,r)}function r1(t,e){e.mapSorter&&t.sort(e.mapSorter)}var X_=Symbol.for("DONE"),Y_=Symbol.for("BREAK");var n1=Ra(),o1={float64:!1,quickEncodeToken:Ma};function Oa(t,e=n1,r=o1){if(Array.isArray(t)){let n=0;for(let o of t)n+=Oa(o,e,r);return n}else{let n=e[t.type.major];if(n.encodedSize===void 0||typeof n.encodedSize!="function")throw new Error(`Encoder for ${t.type.name} does not have an encodedSize()`);return n.encodedSize(t,r)}}var $a=class{constructor(e,r){this.bytes=e,this.byteOffset=r,this.roots=[],this.headerSize=r}addRoot(e,r){return i1(this,e,r),this}write(e){return s1(this,e),this}close(e){return a1(this,e)}},i1=(t,e,r={})=>{let{resize:n=!1}=r,{bytes:o,headerSize:i,byteOffset:s,roots:c}=t;t.roots.push(e);let a=ci(t);if(a>i)if(a-i+s<o.byteLength)if(n)xh(t,a);else throw c.pop(),new RangeError(`Header of size ${i} has no capacity for new root ${e}.
2
2
  However there is a space in the buffer and you could call addRoot(root, { resize: root }) to resize header to make a space for this root.`);else throw c.pop(),new RangeError(`Buffer has no capacity for a new root ${e}`)},bh=({cid:t,bytes:e})=>{let r=t.bytes.byteLength+e.byteLength;return Dn.default.encodingLength(r)+r},s1=(t,{cid:e,bytes:r})=>{let n=e.bytes.byteLength+r.byteLength,o=Dn.default.encode(n);if(t.byteOffset+o.length+n>t.bytes.byteLength)throw new RangeError("Buffer has no capacity for this block");za(t,o),za(t,e.bytes),za(t,r)},a1=(t,e={})=>{let{resize:r=!1}=e,{roots:n,bytes:o,byteOffset:i,headerSize:s}=t,c=Ko({version:1,roots:n}),a=Dn.default.encode(c.length),u=a.length+c.byteLength;if(s-u===0)return wh(t,a,c),o.subarray(0,i);if(r)return xh(t,u),wh(t,a,c),o.subarray(0,t.byteOffset);throw new RangeError(`Header size was overestimated.
3
- You can use close({ resize: true }) to resize header`)},xh=(t,e)=>{let{bytes:r,headerSize:n}=t;r.set(r.subarray(n,t.byteOffset),e),t.byteOffset+=e-n,t.headerSize=e},za=(t,e)=>{t.bytes.set(e,t.byteOffset),t.byteOffset+=e.length},wh=({bytes:t},e,r)=>{t.set(e),t.set(r,e.length)},c1=[new B(x.map,2),new B(x.string,"version"),new B(x.uint,1),new B(x.string,"roots")],u1=new B(x.tag,42),l1=t=>{let e=[...c1];e.push(new B(x.array,t.length));for(let n of t)e.push(u1),e.push(new B(x.bytes,{length:n+1}));let r=Oa(e);return Dn.default.encodingLength(r)+r},ci=({roots:t})=>l1(t.map(e=>e.bytes.byteLength));var kh=(t,e={})=>{let{roots:r=[],byteOffset:n=0,byteLength:o=t.byteLength,headerSize:i=ci({roots:r})}=e,s=new Uint8Array(t,n,o),c=new $a(s,i);for(let a of r)c.addRoot(a);return c};var Mt=({name:t,code:e,encode:r})=>new Ha(t,e,r),Ha=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Ut(this.code,r):r.then(n=>Ut(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ui({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*d1(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r],i=j.asCID(n);i?yield[o.join("/"),i]:typeof n=="object"&&(yield*ja(n,o))}else{let r=j.asCID(e);r?yield[t.join("/"),r]:yield*ja(e,t)}}function*ja(t,e){if(t==null||t instanceof Uint8Array)return;let r=j.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,o]of Object.entries(t)){let i=[...e,n];yield*d1(i,o)}}function*h1(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r];yield o.join("/"),typeof n=="object"&&!j.asCID(n)&&(yield*Va(n,o))}else yield*Va(e,t)}function*Va(t,e){if(!(t==null||typeof t!="object"))for(let[r,n]of Object.entries(t)){let o=[...e,r];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!j.asCID(n)&&(yield*h1(o,n))}}function p1(t,e){let r=t;for(let[n,o]of e.entries()){if(r=r[o],r==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=j.asCID(r);if(i)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:r}}var Nn=class{constructor({cid:e,bytes:r,value:n}){if(!e||!r||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=r,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:ui(),bytes:ui(),value:ui(),asBlock:ui()})}links(){return ja(this.value,[])}tree(){return Va(this.value,[])}get(e="/"){return p1(this.value,e.split("/").filter(Boolean))}};async function Ve({value:t,codec:e,hasher:r}){if(typeof t>"u")throw new Error('Missing required argument "value"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.encode(t),o=await r.digest(n),i=j.create(1,e.code,o);return new Nn({value:t,bytes:n,cid:i})}async function mt({bytes:t,codec:e,hasher:r}){if(!t)throw new Error('Missing required argument "bytes"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.decode(t),o=await r.digest(t),i=j.create(1,e.code,o);return new Nn({value:n,bytes:t,cid:i})}function y1({bytes:t,cid:e,value:r,codec:n}){let o=r!==void 0?r:n&&n.decode(t);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Nn({cid:e,bytes:t,value:o})}async function li({bytes:t,cid:e,hasher:r,codec:n}){if(!t)throw new Error('Missing required argument "bytes"');if(!r)throw new Error('Missing required argument "hasher"');let o=n.decode(t),i=await r.digest(t);if(!Nt.equals(e.multihash.bytes,i.bytes))throw new Error("CID hash does not match bytes");return y1({bytes:t,cid:e,value:o,codec:n})}var qa=V(require("crypto"),1);var le=Mt({name:"sha2-256",code:18,encode:t=>ie(qa.default.createHash("sha256").update(t).digest())}),C8=Mt({name:"sha2-512",code:19,encode:t=>ie(qa.default.createHash("sha512").update(t).digest())});var gt={};G(gt,{code:()=>Un,decode:()=>w1,encode:()=>g1,name:()=>m1});var m1="raw",Un=85,g1=t=>ie(t),w1=t=>ie(t);async function Pn(t,e){let r=0,n=ci({roots:t});r+=n;for(let{cid:s,bytes:c}of e.entries())r+=bh({cid:s,bytes:c});let o=new Uint8Array(r),i=kh(o,{headerSize:n});for(let s of t)i.addRoot(s);for(let{cid:s,bytes:c}of e.entries())i.write({cid:s,bytes:c});return i.close(),await Ve({value:i.bytes,hasher:le,codec:gt})}async function Wa(t){return await Ve({value:{fp:t},hasher:le,codec:q})}async function Ka(t){let e=await t.getRoots(),r=await t.get(e[0]);if(!r)throw new Error("missing header block");let{value:n}=await mt({bytes:r.bytes,hasher:le,codec:q});if(n&&n.fp===void 0)throw new Error("missing fp");let{fp:o}=n;return o}var Rt={};G(Rt,{code:()=>E1,crypto:()=>S1,decode:()=>v1,decrypt:()=>hi,encode:()=>k1,encrypt:()=>pi,name:()=>A1});function fi(){try{return window.crypto&&window.crypto.subtle?window.crypto:new Crypto}catch{return null}}var Fn=fi();function di(t){let e=new Uint8Array(t);return t>0&&Fn.getRandomValues(e),e}var b1=t=>{t=+t;let e=new Uint8Array(4);return e[3]=t>>>24,e[2]=t>>>16,e[1]=t>>>8,e[0]=t&255,e},x1=t=>{let e=t.byteLength-4;return(t[e]|t[e+1]<<8|t[e+2]<<16)+t[e+3]*16777216},Eh=t=>{let e=t.map(i=>i instanceof ArrayBuffer?new Uint8Array(i):i),r=e.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r),o=0;for(let i of e)n.set(i,o),o+=i.length;return n},k1=({iv:t,bytes:e})=>Eh([t,e]),v1=t=>{let e=t.subarray(0,12);return t=t.slice(12),{iv:e,bytes:t}},E1=3145728+1337;async function Sh(t){return await Fn.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt","decrypt"])}var hi=async({key:t,value:e})=>{let{bytes:r,iv:n}=e,o=await Sh(t),i=await Fn.subtle.decrypt({name:"AES-GCM",iv:n,tagLength:128},o,r);r=new Uint8Array(i);let s=x1(r.subarray(0,4)),c=j.decode(r.subarray(4,4+s));return r=r.subarray(4+s),{cid:c,bytes:r}},pi=async({key:t,cid:e,bytes:r})=>{let n=b1(e.bytes.byteLength),o=di(12),i=Eh([n,e.bytes,r]);try{let s=await Sh(t),c=await Fn.subtle.encrypt({name:"AES-GCM",iv:o,tagLength:128},s,i);r=new Uint8Array(c)}catch(s){throw console.log("ee",s),s}return{value:{bytes:r,iv:o}}},S1=t=>({encrypt:e=>pi({key:t,...e}),decrypt:e=>hi({key:t,...e})}),A1="jchris@encrypted-block:aes-gcm";var Mn=t=>{let e=t.byteLength-4;return(t[e]|t[e+1]<<8|t[e+2]<<16)+t[e+3]*16777216};var Rn=t=>{let e=Math.floor(4294967295/t);return async r=>{let n=await r.identity();if(typeof n!="number")throw new Error("Identity must be a number");return n<=e}};var zt=(t,e)=>t===e?0:t>e?1:-1,Ah=(t,e)=>{for(let r=0;r<t.byteLength;r++){if(e.byteLength===r)return 1;let n=t[r],o=e[r];if(n!==o)return n>o?1:-1}return e.byteLength>t.byteLength?-1:0},Ot=class{constructor(){this._cids=new Set}add(e){if(!e.address)throw new Error("Cannot add node without address");if(e.address.then){let r=e.address.then(n=>this._cids.add(n.toString()));this._cids.add(r),r.then(()=>this._cids.delete(r))}else this._cids.add(e.address.toString())}async all(){return await Promise.all([...this._cids]),this._cids}};var $t=class{constructor({key:e,address:r},n={}){this.key=e,this.address=r,this.codec=n.codec,this.hasher=n.hasher}get isEntry(){return!0}},wt=class{constructor({entries:e,closed:r}){if(typeof r!="boolean")throw new Error('Missing required argument "closed"');this.entries=e,this.closed=r,this.startKey=e[0].key}find(e,r){let{entries:n}=this;for(let o=n.length-1;o>-1;o--){let i=n[o];if(r(e,i.key)>-1)return[o,i]}return null}findMany(e,r,n=!1,o=!1){let{entries:i}=this,s=new Map;n?e=[...e]:e=e.sort(r);for(let c=i.length-1;c>-1&&e.length;c--){let a=i[c],u=[];for(;e.length;){let l=e[e.length-1];l=l.key?l.key:l;let d=r(l,a.key);if(o)if(d===0)u.push(e.pop());else if(d>0)e.pop();else break;else if(d>-1)u.push(e.pop());else break}u.length&&s.set(c,[a,u])}return s}findRange(e,r,n){let{entries:o}=this,i,s=0;for(let c=o.length-1;c>-1;c--){let a=o[c];if(n(r,a.key)>0){i=c;break}}for(let c=0;c<o.length;c++){let a=o[c],u=n(e,a.key);if(u===0){s=c;break}else if(u<0)break;s=c}return{first:s,last:i,entries:o.slice(s,i+1)}}},_h=t=>typeof t=="string"?t:JSON.stringify(t);function _1(t,e){return t.sort(({key:r},{key:n})=>e.compare(r,n))}async function B1(t,e,r){let n=[];for(let o of e){let{key:i,del:s}=o;if(r(i,t)<0)s||n.push(o);else break}return n}async function C1(t,e,{chunker:r,compare:n}){return await bt.from({entries:t.map(o=>new e.LeafEntryClass(o,e)).sort((o,i)=>n(o.key,i.key)),chunker:r,NodeClass:e.LeafClass,distance:0,opts:e})}async function T1(t,e,r,n){return await Promise.all(e.map(async o=>{let i=await o.encode();return r.blocks.push({block:i,node:o}),t.cache.set(o),new n.BranchEntryClass({key:o.key,address:await o.address},n)}))}async function I1(t,e,r,n){let o=e.root;e.blocks.push({block:await o.encode(),node:o}),t.cache.set(o);let i=n.opts,s=o.distance,c=o.entryList.startKey,a=await B1(c,r,t.compare);if(a.length){let u=await C1(a,i,t),l=await T1(t,u,e,i),m=[new i.BranchEntryClass({key:o.entryList.startKey,address:await o.address},i),...l].sort(({key:p},{key:w})=>i.compare(p,w)),f=await bt.from({...n,entries:m,chunker:t.chunker,NodeClass:i.BranchClass,distance:s+1}),h=[...f];for(;f.length>1;){let p=await Promise.all(f.map(async w=>new i.BranchEntryClass({key:w.key,address:await w.address},i)));f=await bt.from({...n,entries:p.sort(({key:w},{key:g})=>i.compare(w,g)),chunker:t.chunker,NodeClass:i.BranchClass,distance:s+1}),h=[...h,...f]}await Promise.all(h.map(async p=>{let w=await p.encode();t.cache.set(p),e.blocks.push({block:w,node:p})})),e.root=f[0],e.nodes=[...e.nodes,...h]}}var bt=class t{constructor({entryList:e,chunker:r,distance:n,getNode:o,compare:i,cache:s}){this.entryList=e,this.chunker=r,this.distance=n,this.getNode=o,this.compare=i,this.cache=s}get closed(){return this.entryList.closed}get key(){return this.entryList.startKey}async getEntry(e,r=new Ot){return{result:await this._getEntry(e,r),cids:r}}async _getEntry(e,r){r.add(this);let n=this;for(;!n.isLeaf;){let s=n.entryList.find(e,this.compare);if(s===null)throw new Error("Not found");let[,c]=s;n=await this.getNode(await c.address),r.add(n)}let o=n.entryList.find(e,this.compare);if(o===null||o[1].key.toString()!==e.toString())throw new Error("Not found");let[,i]=o;return i}async getAllEntries(e=new Ot){return{result:await this._getAllEntries(e),cids:e}}_getAllEntries(e){if(e.add(this),this.isLeaf)return this.entryList.entries;{let{entries:r}=this.entryList,n=async o=>this.getNode(await o.address).then(i=>i._getAllEntries(e)).catch(async i=>{throw i});return Promise.all(r.map(n)).then(o=>o.flat())}}async*vis(e=new Set){let r=async i=>i.isLeaf?`Leaf [${i.entryList.entries.map(c=>`[${c.key},${JSON.stringify(c.value).replace(/"/g,"'")}]`).join(", ")}]`:`Branch [${i.entryList.entries.map(c=>`[${c.key}]`).join(", ")}]`,n=i=>i.toString().slice(0,4)+i.toString().slice(-4),o=async function*(i,s,c){let a=await i.address;if(!c.has(a)){c.add(a);let u=await r(i);yield` node [shape=ellipse fontname="Courier"]; ${n(a)} [label="${u}"];`,yield` ${n(s)} -> ${n(a)};`;for(let l of i.entryList.entries)if(l.address){let d=await l.address;try{let m=await i.getNode(d);yield*await o(m,a,c)}catch(m){yield` ${n(a)} -> ${n(d)};`,yield` node [shape=ellipse fontname="Courier"]; ${n(d)} [label="Error: ${m.message}"];`}}}};yield"digraph tree {",yield' node [shape=ellipse fontname="Courier"]; rootnode;';for await(let i of o(this,"rootnode",e))yield i;yield"}"}async getEntries(e,r=!1,n=new Ot){return{result:await this._getEntries(e,r,n),cids:n}}async _getEntries(e,r,n){n.add(this),r||(e=e.sort(this.compare));let o=this.entryList.findMany(e,this.compare,!0,this.isLeaf);if(this.isLeaf)return[...o.values()].map(([s])=>s);let i=[];for(let[s,c]of[...o.values()].reverse()){let a=this.getNode(await s.address);i.push(a.then(u=>u._getEntries(c.reverse(),!0,n)))}return i=await Promise.all(i),i.flat()}async getRangeEntries(e,r,n=new Ot){return{result:await this._getRangeEntries(e,r,n),cids:n}}_getRangeEntries(e,r,n){n.add(this);let{entries:o}=this.entryList.findRange(e,r,this.compare);if(this.isLeaf)return o.filter(a=>{let u=this.compare(e,a.key),l=this.compare(r,a.key);return u<=0&&l>=0});if(!o.length)return[];let i=async a=>this.getNode(await a.address).then(u=>u._getRangeEntries(e,r,n)),s=[i(o.shift())];if(!o.length)return s[0];let c=i(o.pop());for(;o.length;){let a=async u=>this.getNode(await u.address).then(async l=>l._getAllEntries(n));s.push(a(o.shift()))}return s.push(c),Promise.all(s).then(a=>a.flat())}async transaction(e,r={}){r={codec:this.codec,hasher:this.hasher,getNode:this.getNode,compare:this.compare,cache:this.cache,...r};let n={chunker:this.chunker,opts:r},o=this.entryList.findMany(e,r.compare,!0,this.isLeaf);return this.isLeaf?await this.transactionLeaf(e,r,n,o):await this.transactionBranch(e,r,n,o)}async transactionLeaf(e,r,n,o){let{LeafClass:i,LeafEntryClass:s}=r,{entries:c,previous:a}=this.processLeafEntries(e,o,s,r),u={...n,entries:c,NodeClass:i,distance:0},l=await t.from(u);return{nodes:l,previous:a,blocks:await Promise.all(l.map(async d=>{let m=await d.encode();return this.cache.set(d),{block:m,node:d}})),distance:0}}processLeafEntries(e,r,n,o){let i=[],s=[],c={},a=new Map;for(let{key:d,del:m,value:f}of e){let h=_h(d);m?typeof c[h]>"u"&&a.set(h,null):(c[h]={key:d,value:f},a.delete(h))}s=[...this.entryList.entries];for(let[d,[m]]of r){i.push(m);let f=_h(m.key);a.has(f)?a.set(f,d):(s[d]=new n(c[f],o),delete c[f])}let u=0;for(let[,d]of a)d!==null&&s.splice(d-u++,1);let l=Object.values(c).map(d=>new n(d,o));return s=s.concat(l).sort(({key:d},{key:m})=>o.compare(d,m)),{entries:s,previous:i}}async transactionBranch(e,r,n,o){let{BranchClass:i,BranchEntryClass:s}=r,c=0;for(let[h,[p,w]]of o){let g=this.getNode(await p.address).then(b=>b.transaction(w.reverse(),{...r,sorted:!0})).then(b=>({entry:p,keys:w,distance:c,...b}));o.set(h,g)}let a=[...this.entryList.entries],u={previous:[],blocks:[],nodes:[]};for(let[h,p]of o){let{nodes:w,previous:g,blocks:b,distance:k}=await p;c=k,a[h]=w,g.length&&(u.previous=u.previous.concat(g)),b.length&&(u.blocks=u.blocks.concat(b)),w.length&&(u.nodes=u.nodes.concat(w))}a=a.flat();let l=await this.handlePrepend(a,r,n,u,c);c++;let d=async h=>{if(h.isEntry)return h;let p=await h.encode();return u.blocks.push({block:p,node:h}),this.cache.set(h),new s(h,r)};a=await Promise.all(l.map(d));let m={...n,entries:a,NodeClass:i,distance:c},f=await t.from(m);return await Promise.all(f.map(async h=>{let p=await h.encode();u.blocks.push({block:p,node:h}),this.cache.set(h)})),u.nodes=f,{...u,distance:c}}async handlePrepend(e,r,n,o,i){let{BranchClass:s,LeafClass:c}=r,a=[],u=null;for(let l of e)if(u){let d=await this.mergeFirstLeftEntries(l,u,n,o,i);u=null;let m=d[0].address?s:c,f={...n,entries:d.sort(({key:p},{key:w})=>r.compare(p,w)),NodeClass:m,distance:i},h=await t.from(f);h[h.length-1].closed||(u=h.pop()),h.length&&(a=a.concat(h))}else!l.isEntry&&!l.closed?u=l:a.push(l);return u&&a.push(u),a}async getNodeFirstFromBlocks(e,r){for(let{block:n,node:o}of e)if(await n.cid===r)return o;return await this.getNode(r)}async mergeFirstLeftEntries(e,r,n,o,i){let s=n.opts,{LeafClass:c,BranchClass:a,BranchEntryClass:u}=s;if(e.isEntry){let f=await e.address;e=await this.getNodeFirstFromBlocks(o.blocks,f)}let l=e.entryList.entries;if(!l.length)throw new Error("unreachable no entries");let d=(f,h)=>f.concat(h),m=async(f,h,p)=>await Promise.all(f.map(async w=>(h.blocks.push({block:await w.encode(),node:w}),this.cache.set(w),new u({key:w.key,address:await w.address},p))));if(l[0].constructor.name===r.entryList.entries[0].constructor.name)return await d(r.entryList.entries,l);{let f=l.shift();if(!f)throw new Error("unreachable no left entry");if(!f.address)throw new Error("unreachable existing leaf, no leftEntry.address");let h=await this.mergeFirstLeftEntries(f,r,n,o,i-1),p=l.shift();if(!p)return h;if(!p.address)throw new Error("unreachable existing leaf, no esf.address");let w=await this.getNodeFirstFromBlocks(o.blocks,await p.address);if(w.entryList.entries[0].address){if(h[0].address)return h.concat(w.entryList.entries);{let g=await t.from({...n,entries:h.sort(({key:C},{key:N})=>s.compare(C,N)),NodeClass:c,distance:i}),b=await m(g,o,s),k=await t.from({...n,entries:[...w.entryList.entries,...b,...l].sort(({key:C},{key:N})=>s.compare(C,N)),NodeClass:a,distance:i});return await m(k,o,s)}}else{let g=await d(h,w.entryList.entries),b=await t.from({...n,entries:g.sort(({key:v},{key:C})=>s.compare(v,C)),NodeClass:c,distance:i}),k=await m(b,o,s);return await d(k,l)}}}async bulk(e,r={},n=!0){let{BranchClass:o}=r;r={codec:this.codec,hasher:this.hasher,getNode:this.getNode,compare:this.compare,cache:this.cache,...r},r.sorted||(e=_1(e,r),r.sorted=!0);let i={chunker:this.chunker,opts:r},s=await this.transaction(e,r);for(;s.nodes.length>1;){let c=s.nodes[0].distance+1,a=await Promise.all(s.nodes.map(async l=>{let d=await l.encode();return s.blocks.push({block:d,node:l}),this.cache.set(l),new r.BranchEntryClass(l,r)})),u=await t.from({...i,entries:a,NodeClass:o,distance:c});await Promise.all(u.map(async l=>{let d=await l.encode();this.cache.set(l),s.blocks.push({block:d,node:l})})),s.nodes=u}return s.root=s.nodes[0],n&&s.root&&await I1(this,s,e,i),s.blocks=s.blocks.map(({block:c})=>c),s}static async from({entries:e,chunker:r,NodeClass:n,distance:o,opts:i}){if(!e.every(a=>a.constructor.name===e[0].constructor.name))throw new Error("all entries must be of the same type");let s=[],c=[];for(let a of e)c.push(a),await r(a,o)&&(s.push(new wt({entries:c,closed:!0})),c=[]);return c.length&&s.push(new wt({entries:c,closed:!1})),s.map(a=>new n({entryList:a,chunker:r,distance:o,...i}))}},yi=class extends bt{constructor({codec:e,hasher:r,block:n,...o}){super(o),this.codec=e,this.hasher=r,n?(this.block=n,this.address=n.cid):(this.block=this.encode(),this.address=this.block.then(i=>i.cid))}async get(e){let{result:r,cids:n}=await this.getEntry(e);return{result:r.key,cids:n}}async encode(){if(this.block)return this.block;let e=await this.encodeNode(),r={codec:this.codec,hasher:this.hasher,value:e};return this.block=await Ve(r),this.block}},Lr=class extends yi{async encodeNode(){let{entries:e}=this.entryList,r=async o=>{if(!o.address)throw new Error("entry.address required");return[o.key,await o.address]},n=await Promise.all(e.map(r));return{branch:[this.distance,n],closed:this.closed}}get isBranch(){return!0}},Dr=class extends yi{async encodeNode(){return{leaf:await Promise.all(this.entryList.entries.map(async r=>await r.encodeNode())),closed:this.closed}}get isLeaf(){return!0}},mi=async function*(t){let{LeafClass:e,LeafEntryClass:r,BranchClass:n,BranchEntryClass:o,list:i,chunker:s,compare:c,...a}=t;i=i.map(d=>new r(d,a)),a.compare=c;let u=await bt.from({entries:i,chunker:s,NodeClass:e,distance:0,opts:a});yield*u;let l=1;for(;u.length>1;){let d=async f=>new o({key:f.key,address:await f.address},a),m=await Promise.all(u.map(d));u=await bt.from({entries:m,chunker:s,NodeClass:n,distance:l,opts:a}),yield*u,l++}};var Ga=({bytes:t},{bytes:e})=>Ah(t,e),gi=class extends $t{constructor(e){super({address:e,key:e}),this.cid=e}encodeNode(){return this.cid}identity(){let e=this.cid.multihash.bytes;return Mn(e)}},wi=class extends $t{async identity(){let{multihash:{bytes:e}}=await this.address;return Mn(e)}},bi=class extends Lr{},xi=class extends Dr{},Bh=(t,e,r,n,o)=>{let i=c=>{let{value:a}=c,u={chunker:r,cache:e,block:c,getNode:s,codec:n,hasher:o,compare:Ga},l,d;if(a.leaf)l=a.leaf.map(h=>new gi(h)),d=xi;else if(a.branch){let[h,p]=a.branch;u.distance=h,l=p.map(([w,g])=>new wi({key:w,address:g})),d=bi}else throw new Error("Unknown block data, does not match schema");let m=new wt({entries:l,closed:a.closed}),f=new d({entryList:m,...u});return e.set(f),f},s=c=>e.has(c)?e.get(c):t(c).then(a=>i(a));return s},Ch=({get:t,cache:e,chunker:r,list:n,codec:o,hasher:i,sorted:s})=>{s||(n=n.sort(Ga));let c=Bh(t,e,r,o,i);return mi({list:n,codec:o,hasher:i,chunker:r,getNode:c,sorted:s,compare:Ga,cache:e,LeafClass:xi,LeafEntryClass:gi,BranchClass:bi,BranchEntryClass:wi})},Th=({cid:t,get:e,cache:r,chunker:n,codec:o,hasher:i,...s})=>Bh(e,r,n,o,i,s)(t);var Ih=async function*({get:t,cids:e,hasher:r,key:n,cache:o,chunker:i,root:s}){let c=new Set,a;for(let f of e){let h=await t(f);if(!h)throw new Error("missing cid: "+f.toString());let p=await pi({...h,key:n}),w=await Ve({...p,codec:Rt,hasher:r});yield w,c.add(w.cid.toString()),h.cid.equals(s)&&(a=w.cid)}if(!a)throw new Error("cids does not include root");let u=[...c].map(f=>j.parse(f)),l;for await(let f of Ch({list:u,get:t,cache:o,chunker:i,hasher:r,codec:q})){let h=await f.block;yield h,l=h}if(!l)throw new Error("missing last block");let d=[a,l.cid];yield await Ve({value:d,codec:q,hasher:r})},Lh=async function*({root:t,get:e,key:r,cache:n,chunker:o,hasher:i}){let s=async w=>e(w).then(async g=>g?await mt({...g,codec:q,hasher:i}):void 0),c=async w=>e(w).then(async g=>g?await mt({...g,codec:Rt,hasher:i}):void 0),a=await s(t);if(!a)throw new Error("missing root");if(!a.bytes)throw new Error("missing bytes");let{value:[u,l]}=a,d=await e(u);if(!d)throw new Error("missing root block");let m=await Th({cid:l,get:s,cache:n,chunker:o,codec:Rt,hasher:i}),{result:f}=await m.getAllEntries(),h=async w=>{if(!w)throw new Error("missing block");w.value||(w=await mt({...w,codec:Rt,hasher:i}));let{bytes:g,cid:b}=await hi({...w,key:r}).catch(v=>{throw v});return await li({cid:b,bytes:g,hasher:i,codec:Rt})},p=[];for(let{cid:w}of f)d.cid.equals(w)||p.push(c(w).then(h));yield*p,yield h(d)};var Nr={has:()=>!1,get:()=>{throw new Error("Cannot ask for entries from nocache")},set:()=>{}};var Dh=Rn(30);function Nh(t){let e=t.length,r=new Uint8Array(e/2);for(let n=0;n<e;n+=2)r[n/2]=parseInt(t.substring(n,n+2),16);return r}async function Uh(t,e,r){let n=Nh(t),o=n.buffer.slice(0,n.byteLength),i=new Ae,s=[];for(let{cid:u}of r.entries())s.push(u);let c=null;for await(let u of Ih({cids:s,get:r.get.bind(r),key:o,hasher:le,chunker:Dh,cache:Nr,root:e}))await i.put(u.cid,u.bytes),c=u;if(!c)throw new Error("no blocks encrypted");return await Pn([c.cid],i)}async function Ph(t,e){let n=(await e.getRoots())[0];return await L1(n,e.get.bind(e),t)}async function L1(t,e,r){let n=Nh(r),o=n.buffer.slice(0,n.byteLength),i=new Ae,s=null;for await(let c of Lh({root:t,get:e,key:o,hasher:le,chunker:Dh,cache:Nr}))await i.put(c.cid,c.bytes),s=c;if(!s)throw new Error("no blocks decrypted");return{blocks:i,root:s.cid}}var Qa=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let r=this.inRecursive[this.inRecursive.length-1];r&&(r.type===y.array&&(r.elements++,r.elements!==1&&e.push([44])),r.type===y.map&&(r.elements++,r.elements!==1&&(r.elements%2===1?e.push([44]):e.push([58]))))}[y.uint.major](e,r){this.prefix(e);let n=String(r.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[y.negint.major](e,r){this[y.uint.major](e,r)}[y.bytes.major](e,r){throw new Error(`${Ze} unsupported type: Uint8Array`)}[y.string.major](e,r){this.prefix(e);let n=Po(JSON.stringify(r.value));e.push(n.length>32?hn(n):n)}[y.array.major](e,r){this.prefix(e),this.inRecursive.push({type:y.array,elements:0}),e.push([91])}[y.map.major](e,r){this.prefix(e),this.inRecursive.push({type:y.map,elements:0}),e.push([123])}[y.tag.major](e,r){}[y.float.major](e,r){if(r.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===y.array)e.push([93]);else if(s.type===y.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(r.value===void 0)throw new Error(`${Ze} unsupported type: undefined`);if(this.prefix(e),r.type.name==="true"){e.push([116,114,117,101]);return}else if(r.type.name==="false"){e.push([102,97,108,115,101]);return}else if(r.type.name==="null"){e.push([110,117,108,108]);return}let n=String(r.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function D1(t,e){if(Array.isArray(t[0])||Array.isArray(e[0]))throw new Error(`${Ze} complex map keys are not supported`);let r=t[0],n=e[0];if(r.type!==y.string||n.type!==y.string)throw new Error(`${Ze} non-string map keys are not supported`);if(r<n)return-1;if(r>n)return 1;throw new Error(`${Ze} unexpected duplicate map keys, this is not supported`)}var N1={addBreakTokens:!0,mapSorter:D1};function Ja(t,e){return e=Object.assign({},N1,e),ua(t,new Qa,e)}var Ur=class{constructor(e,r={}){this.pos=0,this.data=e,this.options=r,this.modeStack=["value"],this.lastToken=""}done(){return this.pos>=this.data.length}ch(){return this.data[this.pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this.pos]}expect(e){if(this.data.length-this.pos<e.length)throw new Error(`${T} unexpected end of input at position ${this.pos}`);for(let r=0;r<e.length;r++)if(this.data[this.pos++]!==e[r])throw new Error(`${T} unexpected token at position ${this.pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this.pos,r=!1,n=!1,o=c=>{for(;!this.done();){let a=this.ch();if(c.includes(a))this.pos++;else break}};if(this.ch()===45&&(r=!0,this.pos++),this.ch()===48)if(this.pos++,this.ch()===46)this.pos++,n=!0;else return new E(y.uint,0,this.pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),r&&this.pos===e+1)throw new Error(`${T} unexpected token at position ${this.pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${T} unexpected token at position ${this.pos}`);n=!0,this.pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this.pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this.pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this.pos)),s=parseFloat(i);return n?new E(y.float,s,this.pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new E(s>=0?y.uint:y.negint,s,this.pos-e):new E(s>=0?y.uint:y.negint,BigInt(i),this.pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${T} unexpected character at position ${this.pos}; this shouldn't happen`);this.pos++;for(let i=this.pos,s=0;i<this.data.length&&s<65536;i++,s++){let c=this.data[i];if(c===92||c<32||c>=128)break;if(c===34){let a=String.fromCharCode.apply(null,this.data.subarray(this.pos,i));return this.pos=i+1,new E(y.string,a,s)}}let e=this.pos,r=[],n=()=>{if(this.pos+4>=this.data.length)throw new Error(`${T} unexpected end of unicode escape sequence at position ${this.pos}`);let i=0;for(let s=0;s<4;s++){let c=this.ch();if(c>=48&&c<=57)c-=48;else if(c>=97&&c<=102)c=c-97+10;else if(c>=65&&c<=70)c=c-65+10;else throw new Error(`${T} unexpected unicode escape character at position ${this.pos}`);i=i*16+c,this.pos++}return i},o=()=>{let i=this.ch(),s=null,c=i>239?4:i>223?3:i>191?2:1;if(this.pos+c>this.data.length)throw new Error(`${T} unexpected unicode sequence at position ${this.pos}`);let a,u,l,d;switch(c){case 1:i<128&&(s=i);break;case 2:a=this.data[this.pos+1],(a&192)===128&&(d=(i&31)<<6|a&63,d>127&&(s=d));break;case 3:a=this.data[this.pos+1],u=this.data[this.pos+2],(a&192)===128&&(u&192)===128&&(d=(i&15)<<12|(a&63)<<6|u&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:a=this.data[this.pos+1],u=this.data[this.pos+2],l=this.data[this.pos+3],(a&192)===128&&(u&192)===128&&(l&192)===128&&(d=(i&15)<<18|(a&63)<<12|(u&63)<<6|l&63,d>65535&&d<1114112&&(s=d))}s===null?(s=65533,c=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|s&1023),r.push(s),this.pos+=c};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this.pos++,this.done())throw new Error(`${T} unexpected string termination at position ${this.pos}`);switch(s=this.ch(),this.pos++,s){case 34:case 39:case 92:case 47:r.push(s);break;case 98:r.push(8);break;case 116:r.push(9);break;case 110:r.push(10);break;case 102:r.push(12);break;case 114:r.push(13);break;case 117:r.push(n());break;default:throw new Error(`${T} unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new E(y.string,na(r),this.pos-e);default:if(i<32)throw new Error(`${T} invalid control character at position ${this.pos}`);i<128?(r.push(i),this.pos++):o()}}throw new Error(`${T} unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new E(y.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new E(y.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new E(y.null,null,4);case 102:return this.expect([102,97,108,115,101]),new E(y.false,!1,5);case 116:return this.expect([116,114,117,101]),new E(y.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${T} unexpected character at position ${this.pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this.pos++,this.skipWhitespace(),new E(y.break,void 0,1);if(this.ch()!==44)throw new Error(`${T} unexpected character at position ${this.pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this.pos++,this.skipWhitespace(),new E(y.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this.pos++,this.skipWhitespace(),new E(y.break,void 0,1);if(this.ch()!==44)throw new Error(`${T} unexpected character at position ${this.pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this.pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this.pos++,this.skipWhitespace(),new E(y.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${T} unexpected character at position ${this.pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${T} unexpected parse state at position ${this.pos}; this shouldn't happen`)}}};function Xa(t,e){return e=Object.assign({tokenizer:new Ur(t,e)},e),xn(t,e)}var Ya=se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),m6=se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),g6=se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),w6=se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function P1(t){if(t.asCID!==t&&t["/"]!==t.bytes)return null;let e=j.asCID(t);if(!e)return null;let r=e.toString();return[new E(y.map,1/0,1),new E(y.string,"/",1),new E(y.string,r,r.length),new E(y.break,void 0,1)]}function ki(t){let e=Ya.encode(t).slice(1);return[new E(y.map,1/0,1),new E(y.string,"/",1),new E(y.map,1/0,1),new E(y.string,"bytes",5),new E(y.string,e,e.length),new E(y.break,void 0,1),new E(y.break,void 0,1)]}function Ue(t){return ki(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function F1(t){return ki(new Uint8Array(t))}function M1(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function R1(t){if(Number.isNaN(t))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(t===1/0||t===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var O1={typeEncoders:{Object:P1,Buffer:ki,Uint8Array:ki,Int8Array:Ue,Uint16Array:Ue,Int16Array:Ue,Uint32Array:Ue,Int32Array:Ue,Float32Array:Ue,Float64Array:Ue,Uint8ClampedArray:Ue,BigInt64Array:Ue,BigUint64Array:Ue,DataView:Ue,ArrayBuffer:F1,undefined:M1,number:R1}},Za=class extends Ur{constructor(e,r){super(e,r),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===y.map){let r=this._next();if(r.type===y.string&&r.value==="/"){let n=this._next();if(n.type===y.string){if(this._next().type!==y.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new E(y.tag,42,0)}if(n.type===y.map){let o=this._next();if(o.type===y.string&&o.value==="bytes"){let i=this._next();if(i.type===y.string){for(let c=0;c<2;c++)if(this._next().type!==y.break)throw new Error("Invalid encoded Bytes form");let s=Ya.decode(`m${i.value}`);return new E(y.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(r)}return e}},ec={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};ec.tags[42]=j.parse;var z1=t=>Ja(t,O1),$1=t=>{let e=Object.assign(ec,{tokenizer:new Za(t,ec)});return Xa(t,e)},vi=t=>H1.decode(z1(t));var H1=new TextDecoder,Ei=t=>$1(j1.encode(t)),j1=new TextEncoder;var V1=(t,e)=>e.some(r=>t instanceof r),Fh,Mh;function q1(){return Fh||(Fh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function W1(){return Mh||(Mh=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Rh=new WeakMap,rc=new WeakMap,Oh=new WeakMap,tc=new WeakMap,oc=new WeakMap;function K1(t){let e=new Promise((r,n)=>{let o=()=>{t.removeEventListener("success",i),t.removeEventListener("error",s)},i=()=>{r(qe(t.result)),o()},s=()=>{n(t.error),o()};t.addEventListener("success",i),t.addEventListener("error",s)});return e.then(r=>{r instanceof IDBCursor&&Rh.set(r,t)}).catch(()=>{}),oc.set(e,t),e}function G1(t){if(rc.has(t))return;let e=new Promise((r,n)=>{let o=()=>{t.removeEventListener("complete",i),t.removeEventListener("error",s),t.removeEventListener("abort",s)},i=()=>{r(),o()},s=()=>{n(t.error||new DOMException("AbortError","AbortError")),o()};t.addEventListener("complete",i),t.addEventListener("error",s),t.addEventListener("abort",s)});rc.set(t,e)}var nc={get(t,e,r){if(t instanceof IDBTransaction){if(e==="done")return rc.get(t);if(e==="objectStoreNames")return t.objectStoreNames||Oh.get(t);if(e==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return qe(t[e])},set(t,e,r){return t[e]=r,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function zh(t){nc=t(nc)}function Q1(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...r){let n=t.call(Si(this),e,...r);return Oh.set(n,e.sort?e.sort():[e]),qe(n)}:W1().includes(t)?function(...e){return t.apply(Si(this),e),qe(Rh.get(this))}:function(...e){return qe(t.apply(Si(this),e))}}function J1(t){return typeof t=="function"?Q1(t):(t instanceof IDBTransaction&&G1(t),V1(t,q1())?new Proxy(t,nc):t)}function qe(t){if(t instanceof IDBRequest)return K1(t);if(tc.has(t))return tc.get(t);let e=J1(t);return e!==t&&(tc.set(t,e),oc.set(e,t)),e}var Si=t=>oc.get(t);function Hh(t,e,{blocked:r,upgrade:n,blocking:o,terminated:i}={}){let s=indexedDB.open(t,e),c=qe(s);return n&&s.addEventListener("upgradeneeded",a=>{n(qe(s.result),a.oldVersion,a.newVersion,qe(s.transaction),a)}),r&&s.addEventListener("blocked",a=>r(a.oldVersion,a.newVersion,a)),c.then(a=>{i&&a.addEventListener("close",()=>i()),o&&a.addEventListener("versionchange",u=>o(u.oldVersion,u.newVersion,u))}).catch(()=>{}),c}var X1=["get","getKey","getAll","getAllKeys","count"],Y1=["put","add","delete","clear"],ic=new Map;function $h(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(ic.get(e))return ic.get(e);let r=e.replace(/FromIndex$/,""),n=e!==r,o=Y1.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||X1.includes(r)))return;let i=async function(s,...c){let a=this.transaction(s,o?"readwrite":"readonly"),u=a.store;return n&&(u=u.index(c.shift())),(await Promise.all([u[r](...c),o&&a.done]))[0]};return ic.set(e,i),i}zh(t=>({...t,get:(e,r,n)=>$h(e,r)||t.get(e,r,n),has:(e,r)=>!!$h(e,r)||t.has(e,r)}));var sc="0.13.3-dev";var jh=sc.match(/^([^.]*\.[^.]*)/);if(!jh)throw new Error("invalid version: "+sc);var $n=jh[0],ac=class{STORAGE_VERSION=$n;name;constructor(e){this.name=e}},On=class extends ac{tag="header-base";makeHeader({car:e,key:r}){return vi({car:e,key:r})}parseHeader(e){return Ei(e)}},zn=class{tag="car-base";STORAGE_VERSION=$n;loader;constructor(e){this.loader=e}};var Ai=class{tag="rwal-base";STORAGE_VERSION=$n;loader;ready;walState={operations:[],noLoaderOps:[],fileOperations:[]};processing=void 0;constructor(e){this.loader=e,this.ready=(async()=>{let r=await this.load().catch(n=>(console.error("error loading wal",n),null));this.walState.operations=r?.operations||[],this.walState.fileOperations=r?.fileOperations||[]})()}async enqueue(e,r){await this.ready,r.noLoader?this.walState.noLoaderOps.push(e):this.walState.operations.push(e),await this.save(this.walState),r.noLoader||this._process()}async enqueueFile(e,r=!1){await this.ready,this.walState.fileOperations.push({cid:e,public:r})}async _process(){if(await this.ready,!this.loader.remoteCarStore)return;if(this.processing)return this.processing;let e=(async()=>{await this._int_process()})();this.processing=e;try{await e}finally{this.processing=void 0}(this.walState.operations.length||this.walState.fileOperations.length||this.walState.noLoaderOps.length)&&setTimeout(()=>void this._process(),0)}async _int_process(){if(!this.loader.remoteCarStore)return;let e=(async()=>{let r=[...this.walState.operations],n=[...this.walState.fileOperations],o=[],i=[...this.walState.noLoaderOps],s=dn(5);if(r.length+n.length+i.length!==0){for(let c of i){let a=s(async()=>{let u=await this.loader.carStore.load(c.car).catch(()=>null);if(!u)throw new Error(`missing car ${c.car.toString()}`);await this.loader.remoteCarStore.save(u),this.walState.noLoaderOps=this.walState.noLoaderOps.filter(l=>l!==c)});o.push(a)}for(let c of r){let a=s(async()=>{let u=await this.loader.carStore.load(c.car).catch(()=>null);if(!u)throw new Error(`missing car ${c.car.toString()}`);await this.loader.remoteCarStore.save(u),this.walState.operations=this.walState.operations.filter(l=>l!==c)});o.push(a)}if(n.length){let c=this.loader;for(let{cid:a,public:u}of n){let l=s(async()=>{let d=await c.fileStore.load(a);await c.remoteFileStore?.save(d,{public:u}),this.walState.fileOperations=this.walState.fileOperations.filter(m=>m.cid!==a)});o.push(l)}}try{let a=(await Promise.allSettled(o)).filter(u=>u.status==="rejected");if(a.length)throw console.error("error uploading",a),a[0].reason;if(r.length){let u=r[r.length-1];await this.loader.remoteMetaStore?.save(u).catch(l=>{throw console.error("error saving remote meta",l),this.walState.operations.push(u),l})}}finally{await this.save(this.walState)}}})();this.loader.remoteMetaLoading=e,await e}};var Pr=class extends zn{tag="car-browser-idb";idb=null;async _withDB(e){if(!this.idb){let r=`fp.${this.STORAGE_VERSION}.${this.loader.keyId}.${this.loader.name}`;this.idb=await Hh(r,1,{upgrade(n){n.createObjectStore("cars")}})}return await e(this.idb)}async load(e){return await this._withDB(async r=>{let o=await r.transaction(["cars"],"readonly").objectStore("cars").get(e.toString());if(!o)throw new Error(`missing idb block ${e.toString()}`);return{cid:e,bytes:o}})}async save(e){return await this._withDB(async r=>{let n=r.transaction(["cars"],"readwrite");return await n.objectStore("cars").put(e.bytes,e.cid.toString()),await n.done})}async remove(e){return await this._withDB(async r=>{let n=r.transaction(["cars"],"readwrite");return await n.objectStore("cars").delete(e.toString()),await n.done})}},_i=class extends Ai{tag="wal-browser-ls";headerKey(e){return`fp.${this.STORAGE_VERSION}.wal.${this.loader.name}.${e}`}async load(e="main"){try{let r=localStorage.getItem(this.headerKey(e));return r?Ei(r):null}catch{return null}}async save(e,r="main"){try{let n=vi(e);localStorage.setItem(this.headerKey(r),n)}catch{}}},Bi=class extends On{tag="header-browser-ls";headerKey(e){return`fp.${this.STORAGE_VERSION}.meta.${this.name}.${e}`}async load(e="main"){try{let r=localStorage.getItem(this.headerKey(e));return r?[this.parseHeader(r)]:null}catch{return null}}async save(e,r="main"){try{let n=this.headerKey(r),o=this.makeHeader(e);return localStorage.setItem(n,o),null}catch{return null}}};function cc(t,e){return t.some(r=>r.equals(e))}function Vh(t,e=[]){let r=new Map;for(let n of t)cc(e,n)||r.set(n.toString(),n);return[...r.values()]}function qh(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Fr=class{name;opts={};remoteMetaLoading;remoteMetaStore;remoteCarStore;remoteWAL;metaStore;carStore;carLog=[];carReaders=new Map;ready;key;keyId;getBlockCache=new Map;static defaultHeader;constructor(e,r){this.name=e,this.opts=r||this.opts,this.metaStore=new Bi(this.name),this.carStore=new Pr(this),this.remoteWAL=new _i(this),this.ready=Promise.resolve().then(async()=>{if(!this.metaStore||!this.carStore||!this.remoteWAL)throw new Error("stores not initialized");let n=this.opts.meta?[this.opts.meta]:await this.metaStore.load("main");n&&await this.handleDbMetasFromStore(n)})}async snapToCar(e){await this.ready,typeof e=="string"&&(e=j.parse(e));let r=await this.loadCarHeaderFromMeta({car:e,key:this.key||null});this.carLog=[e,...r.cars],await this.getMoreReaders(r.cars),await this._applyCarHeader(r,!0)}async handleDbMetasFromStore(e){for(let r of e)await this.mergeDbMetaIntoClock(r)}async mergeDbMetaIntoClock(e){if(e.key&&await this.setKey(e.key),cc(this.carLog,e.car))return;let r=await this.loadCarHeaderFromMeta(e);await this.getMoreReaders(r.cars),this.carLog=[...Vh([e.car,...this.carLog,...r.cars],r.compact)],await this._applyCarHeader(r)}async ingestKeyFromMeta(e){let{key:r}=e;r&&await this.setKey(r)}async loadCarHeaderFromMeta({car:e}){let r=await this.loadCar(e);return await Ka(r)}async _getKey(){return this.key?this.key:(this.opts.public||(fi()?await this.setKey(qh(di(32))):console.warn("missing crypto module, using public mode")),this.key)}committing;async commit(e,r,n={noLoader:!1,compact:!1}){this.committing&&await this.committing,this.committing=this._commitInternal(e,r,n);let o=await this.committing;return this.committing=void 0,o}async _commitInternal(e,r,n={noLoader:!1,compact:!1}){await this.ready;let o=this.makeCarHeader(r,this.carLog,!!n.compact),i=[];if(o.files)i=o.files;else{let l=await Wa(o);await e.put(l.cid,l.bytes),i=[l.cid]}let s=n.public?null:await this._getKey(),{cid:c,bytes:a}=s?await Uh(s,i[0],e):await Pn(i,e);if(uc(r))return await this.fileStore.save({cid:c,bytes:a}),await this.remoteWAL.enqueueFile(c,n.public),c;await this.carStore.save({cid:c,bytes:a});let u={car:c,key:s||null};if(await this.remoteWAL.enqueue(u,n),await this.metaStore.save(u),n.compact){let l=o;this.carLog=[...Vh([c,...this.carLog],l.compact)],(async()=>{this.remoteMetaLoading&&await this.remoteMetaLoading;for(let d of l.compact)await this.carStore.remove(d)})()}else this.carLog.unshift(c);return c}async getBlock(e){await this.ready;let r=e.toString();if(this.getBlockCache.has(r))return this.getBlockCache.get(r);let n=await Promise.any(this.carLog.map(async o=>{let i=await this.loadCar(o);if(!i)throw new Error(`missing car reader ${o.toString()}`);let s=await i.get(e);if(s)return s;throw new Error(`block not in reader: ${e.toString()}`)})).catch(()=>{});return n&&this.getBlockCache.set(r,n),n}async loadCar(e){if(!this.carStore)throw new Error("car store not initialized");return await this.storesLoadCar(e,this.carStore,this.remoteCarStore)}async storesLoadCar(e,r,n,o){let i=e.toString();return this.carReaders.has(i)||this.carReaders.set(i,(async()=>{let s=null;try{s=await r.load(e)}catch{if(n){let l=await n.load(e);l&&(await r.save(l),s=l)}}if(!s)throw new Error(`missing car file ${i}`);let c=await Ar.fromBytes(s.bytes),a=o?Promise.resolve(c):this.ensureDecryptedReader(c);return this.carReaders.set(i,a),a})().catch(s=>{throw this.carReaders.delete(i),s})),this.carReaders.get(i)}async ensureDecryptedReader(e){let r=await this._getKey();if(!r)return e;let{blocks:n,root:o}=await Ph(r,e);return{getRoots:()=>[o],get:n.get.bind(n)}}async setKey(e){if(this.key&&this.key!==e)throw new Error("key mismatch");this.key=e;let r=fi();if(!r)throw new Error("missing crypto module");let n=r.subtle,i=new TextEncoder().encode(e),s=await n.digest("SHA-256",i),c=Array.from(new Uint8Array(s));this.keyId=c.map(a=>a.toString(16).padStart(2,"0")).join("")}async getMoreReaders(e){let r=dn(5),n=e.filter(o=>!this.carReaders.has(o.toString()));await Promise.all(n.map(o=>r(()=>this.loadCar(o))))}};var Mr=V(Xh(),1);var Ci=class extends $t{async identity(){let e=await this.codec.encode(await this.encodeNode()),r=await this.hasher.encode(e);return Mn(r)}},Ht=class extends Ci{constructor(e,r){super(e,r),this.value=e.value}encodeNode(){return[this.key,this.value]}},jt=class extends Ci{constructor(e,r){if(!e.address)throw new Error("Cannot create MapBranchEntry without address");super(e,r)}async encodeNode(){return[this.key,await this.address]}},Yh=async(t,e)=>{let{result:r,cids:n}=await t.getEntry(e);return{result:r.value,cids:n}},Zh=async(t,e)=>{let{result:r,cids:n}=await t.getEntries(e);return{result:r.map(o=>o.value),cids:n}},Vt=class extends Dr{get(e){return Yh(this,e)}getMany(e){return Zh(this,e)}bulk(e,r={},n=!0){return super.bulk(e,{...ep,...r},n)}},qt=class extends Lr{get(e){return Yh(this,e)}getMany(e){return Zh(this,e)}bulk(e,r={},n=!0){return super.bulk(e,{...ep,...r},n)}},ep={LeafClass:Vt,LeafEntryClass:Ht,BranchClass:qt,BranchEntryClass:jt},tp=(t,e,r,n,o,i,s)=>{let c=s.LeafClass||Vt,a=s.LeafEntryClass||Ht,u=s.BranchClass||qt,l=s.BranchEntryClass||jt,d=async f=>e.has(f)?e.get(f):t(f).then(h=>m(h)),m=sx({chunker:r,cache:e,getNode:d,codec:n,hasher:o,compare:i,LeafEntryClass:a,LeafClass:c,BranchEntryClass:l,BranchClass:u});return d},rp=({get:t,cache:e,chunker:r,list:n,codec:o,hasher:i,sorted:s,compare:c,...a})=>{s||(n=n.sort(({key:d},{key:m})=>c(d,m)));let u=tp(t,e,r,o,i,c,a),l={list:n,codec:o,hasher:i,chunker:r,getNode:u,sorted:s,compare:c,cache:e,LeafClass:a.LeafClass||Vt,LeafEntryClass:a.LeafEntryClass||Ht,BranchClass:a.BranchClass||qt,BranchEntryClass:a.BranchEntryClass||jt};return mi(l)},np=({cid:t,get:e,cache:r,chunker:n,codec:o,hasher:i,compare:s,...c})=>tp(e,r,n,o,i,s,c)(t);function sx({chunker:t,cache:e,getNode:r,codec:n,hasher:o,compare:i,LeafEntryClass:s,LeafClass:c,BranchEntryClass:a,BranchClass:u}){let l={codec:n,hasher:o};return d=>{let{value:m}=d,f={chunker:t,cache:e,block:d,getNode:r,codec:n,hasher:o,compare:i},h,p;if(m.leaf)h=m.leaf.map(([b,k])=>new s({key:b,value:k},l)),p=c;else if(m.branch){let[b,k]=m.branch;f.distance=b,h=k.map(([v,C])=>new a({key:v,address:C},l)),p=u}else throw new Error("Unknown block data, does not match schema");let w=new wt({entries:h,closed:m.closed}),g=new p({entryList:w,...f});return e.set(g),g}}var ax=(t,e)=>{let[r,n]=t,[o,i]=e,s=zt(r,o);return s!==0?s:cx(n,i)},cx=(t,e)=>{if(Number.isNaN(t))return-1;if(Number.isNaN(e))throw new Error("ref may not be Infinity or NaN");return Number.isFinite(t)?zt(t,e):1},op=async(t,e)=>{let r=[e,NaN],n=[e,1/0],{result:o,cids:i}=await t.getRangeEntries(r,n);return{result:o.map(s=>{let[c,a]=s.key;return{id:a,key:c,row:s.value}}),cids:i}},ip=async(t,e,r)=>{e=[e,NaN],r=[r,1/0];let{result:n,cids:o}=await t.getRangeEntries(e,r);return{result:n.map(s=>{let[c,a]=s.key;return{id:a,key:c,row:s.value}}),cids:o}},fc=class extends Vt{get(e){return op(this,e)}range(e,r){return ip(this,e,r)}bulk(e,r={},n=!0){return super.bulk(e,{...hc,...r},n)}},dc=class extends qt{get(e){return op(this,e)}range(e,r){return ip(this,e,r)}bulk(e,r={},n=!0){return super.bulk(e,{...hc,...r},n)}},ux=fc,lx=dc,hc={LeafClass:ux,BranchClass:lx,LeafEntryClass:Ht,BranchEntryClass:jt},sp={...hc,compare:ax},ap=t=>(t={...sp,...t},rp(t)),pc=t=>(t={...sp,...t},np(t));var Wt=class{cid=null;root=null},dx=(t,e)=>{if(Number.isNaN(t))return-1;if(Number.isNaN(e))throw new Error("ref may not be Infinity or NaN");return t===1/0?1:zt(t,e)},hx=(t,e)=>{let[r,n]=t,[o,i]=e,s=zt(r,o);return s!==0?s:dx(n,i)},mc={cache:Nr,chunker:Rn(30),codec:q,hasher:le,compare:hx},gc={cache:Nr,chunker:Rn(30),codec:q,hasher:le,compare:zt};function cp(t,e){let r=[];return t.forEach(({key:n,value:o,del:i})=>{if(i||!o)return;let s=!1,c=e({_id:n,...o},(a,u)=>{s=!0,!(typeof a>"u")&&r.push({key:[Mr.default.encode(a),n],value:u||null})});!s&&c&&r.push({key:[Mr.default.encode(c),n],value:null})}),r}function yc(t){return async e=>{let r=await t.get(e);if(!r)throw new Error(`Missing block ${e.toString()}`);let{cid:n,bytes:o}=r;return li({cid:n,bytes:o,hasher:le,codec:q})}}async function wc(t,e,r,n){if(!r.length)return e;if(!e.root)if(e.cid)e.root=await pc({cid:e.cid,get:yc(t),...n});else{let s=null,c=null;for await(let a of await ap({get:yc(t),list:r,...n})){let u=await a.block;await t.put(u.cid,u.bytes),s=u,c=a}if(!c||!s)throw new Error("failed to create index");return{root:c,cid:s.cid}}let{root:o,blocks:i}=await e.root.bulk(r);if(o){for await(let s of i)await t.put(s.cid,s.bytes);return{root:o,cid:(await o.block).cid}}else return{root:null,cid:null}}async function bc(t,e,r){return await pc({cid:e,get:yc(t),...r})}async function Kt(t,e,r){return r.descending&&(e.result=e.result.reverse()),r.limit&&(e.result=e.result.slice(0,r.limit)),r.includeDocs&&(e.result=await Promise.all(e.result.map(async n=>{let o=await t.get(n.id),i=o?{_id:n.id,...o.doc}:null;return{...n,doc:i}}))),{rows:e.result.map(n=>(n.key=Mr.default.decode(n.key),n.row&&!n.value&&(n.value=n.row,delete n.row),n))}}function xc(t){return t.map(e=>Mr.default.encode(e))}function kc(t){return Mr.default.encode(t)}function Rr({_crdt:t},e,r,n){if(r&&n)throw new Error("cannot provide both mapFn and meta");if(r&&r.constructor.name!=="Function")throw new Error("mapFn must be a function");if(t.indexers.has(e))t.indexers.get(e).applyMapFn(e,r,n);else{let o=new Ti(t,e,r,n);t.indexers.set(e,o)}return t.indexers.get(e)}var Ti=class{blocks;crdt;name=null;mapFn=null;mapFnString="";byKey=new Wt;byId=new Wt;indexHead=void 0;includeDocsDefault=!1;initError=null;ready;constructor(e,r,n,o){if(this.blocks=e.indexBlocks,this.crdt=e,this.applyMapFn(r,n,o),!(this.mapFnString||this.initError))throw new Error("missing mapFnString");this.ready=this.blocks.ready.then(()=>{})}applyMapFn(e,r,n){if(r&&n)throw new Error("cannot provide both mapFn and meta");if(this.name&&this.name!==e)throw new Error("cannot change name");this.name=e;try{if(n){if(this.indexHead&&this.indexHead.map(i=>i.toString()).join()!==n.head.map(i=>i.toString()).join())throw new Error("cannot apply meta to existing index");this.mapFnString?this.mapFnString!==n.map?console.log("cannot apply different mapFn meta: old mapFnString",this.mapFnString,"new mapFnString",n.map):(this.byId.cid=n.byId,this.byKey.cid=n.byKey,this.indexHead=n.head):(this.mapFnString=n.map,this.byId.cid=n.byId,this.byKey.cid=n.byKey,this.indexHead=n.head)}else if(this.mapFn){if(r&&this.mapFn.toString()!==r.toString())throw new Error("cannot apply different mapFn app2")}else{if(r||(r=px(e)),this.mapFnString){if(this.mapFnString!==r.toString())throw new Error("cannot apply different mapFn app")}else this.mapFnString=r.toString();this.mapFn=r}let o=/=>\s*(.*)/.test(this.mapFnString);this.includeDocsDefault=o}catch(o){this.initError=o}}async query(e={}){if(await this._updateIndex(),await this._hydrateIndex(),!this.byKey.root)return await Kt(this.crdt,{result:[]},e);if(this.includeDocsDefault&&e.includeDocs===void 0&&(e.includeDocs=!0),e.range){let{result:o,...i}=await this.byKey.root.range(...xc(e.range));return await Kt(this.crdt,{result:o,...i},e)}if(e.key){let o=kc(e.key);return await Kt(this.crdt,await this.byKey.root.get(o),e)}if(Array.isArray(e.keys))return{rows:(await Promise.all(e.keys.map(async i=>{let s=kc(i);return(await Kt(this.crdt,await this.byKey.root.get(s),e)).rows}))).flat()};if(e.prefix){Array.isArray(e.prefix)||(e.prefix=[e.prefix]);let o=[...e.prefix,NaN],i=[...e.prefix,1/0],s=xc([o,i]);return await Kt(this.crdt,await this.byKey.root.range(...s),e)}let{result:r,...n}=await this.byKey.root.getAllEntries();return await Kt(this.crdt,{result:r.map(({key:[o,i],value:s})=>({key:o,id:i,value:s})),...n},e)}_resetIndex(){this.byId=new Wt,this.byKey=new Wt,this.indexHead=void 0}async _hydrateIndex(){this.byId.root&&this.byKey.root||!this.byId.cid||!this.byKey.cid||(this.byId.root=await bc(this.blocks,this.byId.cid,gc),this.byKey.root=await bc(this.blocks,this.byKey.cid,mc))}async _updateIndex(){if(await this.ready,this.initError)throw this.initError;if(!this.mapFn)throw new Error("No map function defined");let e,r;if(!this.indexHead||this.indexHead.length===0?{result:e,head:r}=await this.crdt.allDocs():{result:e,head:r}=await this.crdt.changes(this.indexHead),e.length===0)return this.indexHead=r,{byId:this.byId,byKey:this.byKey};let n=[],o=[];if(this.byId.root){let a=e.map(({key:l})=>l),{result:u}=await this.byId.root.getMany(a);n=u.map(l=>({key:l,del:!0})),o=u.map(l=>({key:l[1],del:!0}))}let i=cp(e,this.mapFn),s=i.map(({key:a})=>({key:a[1],value:a})),c=new Map;for(let[a,u]of this.crdt.indexers)u.indexHead&&c.set(a,{byId:u.byId.cid,byKey:u.byKey.cid,head:u.indexHead,map:u.mapFnString,name:u.name});return await this.blocks.transaction(async a=>(this.byId=await wc(a,this.byId,o.concat(s),gc),this.byKey=await wc(a,this.byKey,n.concat(i),mc),this.indexHead=r,{byId:this.byId.cid,byKey:this.byKey.cid,head:r,map:this.mapFnString,name:this.name}),c)}};function px(t){return e=>{if(e[t])return e[t]}}var Ii=class t extends Fr{crdt;static defaultHeader={cars:[],compact:[],indexes:new Map};defaultHeader=t.defaultHeader;constructor(e,r,n){super(e,n),this.crdt=r}async _applyCarHeader(e){for(let[r,n]of Object.entries(e.indexes))Rr({_crdt:this.crdt},r,void 0,n)}makeCarHeader({indexes:e},r,n=!1){return n?{indexes:e,cars:[],compact:r}:{indexes:e,cars:r,compact:[]}}},Li=class t extends Fr{static defaultHeader={cars:[],compact:[],head:[]};defaultHeader=t.defaultHeader;clock;remoteFileStore;fileStore;constructor(e,r,n){super(e,n),this.fileStore=new Pr(this),this.clock=r}async loadFileCar(e,r=!1){return await this.storesLoadCar(e,this.fileStore,this.remoteFileStore,r)}async _applyCarHeader(e,r=!1){r?await this.clock.applyHead(null,e.head,this.clock.head):await this.clock.applyHead(null,e.head,[])}makeCarHeader(e,r,n=!1){if(uc(e)){let o=[];for(let[,i]of Object.entries(e.files))o.push(i.cid);return{files:o}}else{let{head:o}=e;return n?{head:o,cars:[],compact:r}:{head:o,cars:r,compact:[]}}}};function uc(t){return t&&t.files!==void 0}var xt=class extends Ae{parent;constructor(e){super(),this.parent=e}async get(e){return this.parent.get(e)}async superGet(e){return super.get(e)}},Di=class{ready;name=null;loader=null;opts={};transactions=new Set;constructor(e,r,n){if(this.opts=n||this.opts,e){if(this.name=e,!r)throw new Error("missing loader");this.loader=r,this.ready=this.loader.ready}else this.ready=Promise.resolve()}async put(){throw new Error("use a transaction to put")}async get(e){if(!e)throw new Error("required cid");for(let r of this.transactions){let n=await r.superGet(e);if(n)return n}if(this.loader)return await this.loader.getBlock(e)}async commitCompaction(e,r){return this.transactions.clear(),this.transactions.add(e),await this.loader?.commit(e,{head:r},{compact:!0})}async*entries(){let e=new Set;for(let r of this.transactions)for await(let n of r.entries())e.has(n.cid.toString())||(e.add(n.cid.toString()),yield n)}async executeTransaction(e,r){let n=new xt(this);this.transactions.add(n);let o=await e(n),{car:i,done:s}=await r(n,o);return i?{...s,car:i}:s}},Ni=class extends Di{constructor(e,r,n){e?super(e,new Ii(e,r,n),n):super(null)}async transaction(e,r){return this.executeTransaction(e,async(n,o)=>(r.set(o.name,o),{car:await this.loader?.commit(n,{indexes:r}),done:o}))}},Ui=class extends Di{constructor(e,r,n){e?super(e,new Li(e,r,n),n):super(null)}async transaction(e,r,n={noLoader:!1}){return this.executeTransaction(e,async(o,i)=>({car:await this.loader?.commit(o,i,n),done:i}))}},Pi=class{blocks;loader=null;cids=new Set;constructor(e){this.blocks=e,this.loader=e.loader}async get(e){return this.cids.add(e),await this.blocks.get(e)}};var Ec=({name:t,code:e,encode:r})=>new vc(t,e,r),vc=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Tt(this.code,r):r.then(n=>Tt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Fi({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*yx(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r],i=H.asCID(n);i?yield[o.join("/"),i]:typeof n=="object"&&(yield*Sc(n,o))}else{let r=H.asCID(e);r?yield[t.join("/"),r]:yield*Sc(e,t)}}function*Sc(t,e){if(t==null||t instanceof Uint8Array)return;let r=H.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,o]of Object.entries(t)){let i=[...e,n];yield*yx(i,o)}}function*mx(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r];yield o.join("/"),typeof n=="object"&&!H.asCID(n)&&(yield*Ac(n,o))}else yield*Ac(e,t)}function*Ac(t,e){if(!(t==null||typeof t!="object"))for(let[r,n]of Object.entries(t)){let o=[...e,r];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!H.asCID(n)&&(yield*mx(o,n))}}function gx(t,e){let r=t;for(let[n,o]of e.entries()){if(r=r[o],r==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=H.asCID(r);if(i)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:r}}var Pe=class{constructor({cid:e,bytes:r,value:n}){if(!e||!r||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=r,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:Fi(),bytes:Fi(),value:Fi(),asBlock:Fi()})}links(){return Sc(this.value,[])}tree(){return Ac(this.value,[])}get(e="/"){return gx(this.value,e.split("/").filter(Boolean))}};async function Mi({value:t,codec:e,hasher:r}){if(typeof t>"u")throw new Error('Missing required argument "value"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.encode(t),o=await r.digest(n),i=H.create(1,e.code,o);return new Pe({value:t,bytes:n,cid:i})}async function Ri({bytes:t,codec:e,hasher:r}){if(!t)throw new Error('Missing required argument "bytes"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.decode(t),o=await r.digest(t),i=H.create(1,e.code,o);return new Pe({value:n,bytes:t,cid:i})}var Bc={};G(Bc,{sha256:()=>nt,sha512:()=>wx});var _c=V(require("crypto"),1);var nt=Ec({name:"sha2-256",code:18,encode:t=>Se(_c.default.createHash("sha256").update(t).digest())}),wx=Ec({name:"sha2-512",code:19,encode:t=>Se(_c.default.createHash("sha512").update(t).digest())});async function jn(t,e,r){let n=new We(t),o=new Map(e.map(s=>[s.toString(),s]));if(o.has(r.toString()))return e;let i=!1;for(let s of e)await lp(n,r,s)&&(o.delete(s.toString()),o.set(r.toString(),r),i=!0);if(i)return[...o.values()];for(let s of e)if(await lp(n,s,r))return e;return e.concat(r)}var Hn=class extends Pe{constructor({cid:e,value:r,bytes:n,prefix:o}){super({cid:e,value:r,bytes:n}),this.prefix=o}static create(e,r){return bx({data:e,parents:r??[]})}},We=class{constructor(e){this._blocks=e}async get(e){let r=await this._blocks.get(e);if(!r)throw new Error(`missing block: ${e}`);return xx(r.bytes)}};async function bx(t){let{cid:e,bytes:r}=await Mi({value:t,codec:q,hasher:nt});return new Pe({cid:e,value:t,bytes:r})}async function xx(t){let{cid:e,value:r}=await Ri({bytes:t,codec:q,hasher:nt});return new Pe({cid:e,value:r,bytes:t})}async function lp(t,e,r){if(e.toString()===r.toString())return!0;let[{value:n},{value:o}]=await Promise.all([t.get(e),t.get(r)]),i=[...n.parents],s=new Set;for(;i.length;){let c=i.shift();if(!c)break;if(c.toString()===r.toString())return!0;if(o.parents.some(u=>c.toString()===u.toString())||s.has(c.toString()))continue;s.add(c.toString());let{value:a}=await t.get(c);i.push(...a.parents)}return!1}async function*Cc(t,e,r={}){let n=r.renderNodeLabel??(a=>kx(a.cid)),o=new We(t);yield"digraph clock {",yield' node [shape=point fontname="Courier"]; head;';let i=await Promise.all(e.map(a=>o.get(a))),s=[],c=new Set;for(let a of i){c.add(a.cid.toString()),yield` node [shape=oval fontname="Courier"]; ${a.cid} [label="${n(a)}"];`,yield` head -> ${a.cid};`;for(let u of a.value.parents)yield` ${a.cid} -> ${u};`;s.push(...a.value.parents)}for(;s.length;){let a=s.shift();if(!a)break;if(c.has(a.toString()))continue;c.add(a.toString());let u=await o.get(a);yield` node [shape=oval]; ${a} [label="${n(u)}" fontname="Courier"];`;for(let l of u.value.parents)yield` ${a} -> ${l};`;s.push(...u.value.parents)}yield"}"}var kx=t=>`${String(t).slice(0,4)}..${String(t).slice(-4)}`;var Gt=class extends Pe{constructor({cid:e,value:r,bytes:n,prefix:o}){super({cid:e,value:r,bytes:n}),this.prefix=o}static create(){return Ke([])}};async function Ke(t,e){let{cid:r,bytes:n}=await Mi({value:t,codec:q,hasher:nt});return new Gt({cid:r,value:t,bytes:n,prefix:e??""})}async function fp(t,e){let{cid:r,value:n}=await Ri({bytes:t,codec:q,hasher:nt});if(!Array.isArray(n))throw new Error(`invalid shard: ${r}`);return new Gt({cid:r,value:n,bytes:t,prefix:e??""})}var Qt=class{constructor(e){this._blocks=e}async get(e,r=""){let n=await this._blocks.get(e);if(!n)throw new Error(`missing block: ${e}`);return fp(n.bytes,r)}};function Tc(t,e){if(!t.length)return[e];let r=[];for(let[n,[o,i]]of t.entries()){if(e[0]===o){if(Array.isArray(e[1]))Array.isArray(i)&&i[1]!=null&&e[1][1]==null?r.push([o,[e[1][0],i[1]]]):r.push(e);else{let s=Array.isArray(i)?[o,[i[0],e[1]]]:e;r.push(s)}for(let s=n+1;s<t.length;s++)r.push(t[s]);return r}if(n===0&&e[0]<o){r.push(e);for(let s=n;s<t.length;s++)r.push(t[s]);return r}if(n>0&&e[0]>t[n-1][0]&&e[0]<o){r.push(e);for(let s=n;s<t.length;s++)r.push(t[s]);return r}r.push([o,i])}return r.push(e),r}function dp(t,e){let r=t.findIndex(([i])=>e===i);if(r===-1)throw new Error(`key not found in shard: ${e}`);let n=r,o;for(;;){if(o=t[n][0].slice(0,-1),o.length)for(;;){let i=t.filter(s=>s[0].startsWith(o));if(i.length>1)return{prefix:o,matches:i};if(o=o.slice(0,-1),!o.length)break}if(n++,n>=t.length&&(n=0),n===r)return}}var Oi=64,Ex=512*1024;async function Vn(t,e,r,n,o={}){let i=new Qt(t),s=await i.get(e),c=await zi(i,s,r),a=c[c.length-1],u=r.slice(a.prefix.length),l=[u,n],d=[];if(u.length>Oi){let h=Array.from(Array(Math.ceil(u.length/Oi)),(w,g)=>{let b=g*Oi;return{prefix:a.prefix+u.slice(0,b),skey:u.slice(b,b+Oi)}}),p=await Ke([[h[h.length-1].skey,n]],h[h.length-1].prefix);d.push(p);for(let w=h.length-2;w>0;w--)p=await Ke([[h[w].skey,[p.cid]]],h[w].prefix),d.push(p);l=[h[0].skey,[p.cid]]}let m=Tc(a.value,l),f=await Ke(m,a.prefix);if(f.bytes.length>(o.maxShardSize??Ex)){let h=dp(m,l[0]);if(!h)throw new Error("shard limit reached");let{prefix:p,matches:w}=h,g=await Ke(w.filter(([v])=>v!==p).map(([v,C])=>[v.slice(p.length),C]),a.prefix+p);d.push(g);let b,k=w.find(([v])=>v===p);if(k){if(Array.isArray(k[1]))throw new Error(`expected "${p}" to be a shard value but found a shard link`);b=[g.cid,k[1]]}else b=[g.cid];m=m.filter(v=>w.every(C=>v[0]!==C[0])),m=Tc(m,[p,b]),f=await Ke(m,a.prefix)}d.push(f);for(let h=c.length-2;h>=0;h--){let p=c[h],w=f.prefix.slice(p.prefix.length),g=p.value.map(b=>{let[k,v]=b;if(k!==w)return b;if(!Array.isArray(v))throw new Error(`"${w}" is not a shard link in: ${p.cid}`);return v[1]==null?[k,[f.cid]]:[k,[f.cid,v[1]]]});f=await Ke(g,p.prefix),d.push(f)}return{root:d[d.length-1].cid,additions:d,removals:c}}async function hp(t,e,r){let n=new Qt(t),o=await n.get(e),i=await zi(n,o,r),s=i[i.length-1],c=r.slice(s.prefix.length),a=s.value.find(([u])=>u===c);if(a)return Array.isArray(a[1])?a[1][1]:a[1]}async function Ic(t,e,r){let n=new Qt(t),o=await n.get(e),i=await zi(n,o,r),s=i[i.length-1],c=r.slice(s.prefix.length),a=s.value.findIndex(([h])=>h===c);if(a===-1)return{root:e,additions:[],removals:[]};let u=s.value[a];if(Array.isArray(u[1])&&u[1][1]==null)return{root:e,additions:[],removals:[]};let l=[],d=[...i],m=[...s.value];if(Array.isArray(u[1]))m[a]=[u[0],[u[1][0]]];else for(m.splice(a,1);!m.length;){let h=i[i.length-1],p=i[i.length-2];if(!p)break;i.pop(),m=p.value.filter(w=>Array.isArray(w[1])?w[1][0].toString()!==h.cid.toString():!0)}let f=await Ke(m,i[i.length-1].prefix);l.push(f);for(let h=i.length-2;h>=0;h--){let p=i[h],w=f.prefix.slice(p.prefix.length),g=p.value.map(b=>{let[k,v]=b;if(k!==w)return b;if(!Array.isArray(v))throw new Error(`"${w}" is not a shard link in: ${p.cid}`);return v[1]==null?[k,[f.cid]]:[k,[f.cid,v[1]]]});f=await Ke(g,p.prefix),l.push(f)}return{root:l[l.length-1].cid,additions:l,removals:d}}async function*pp(t,e,r={}){let{prefix:n}=r,o=new Qt(t),i=await o.get(e);yield*async function*s(c){for(let a of c.value){let u=c.prefix+a[0];if(Array.isArray(a[1])){if(a[1][1]&&(!n||n&&u.startsWith(n))&&(yield[u,a[1][1]]),n&&(n.length<=u.length&&!u.startsWith(n)||n.length>u.length&&!n.startsWith(u)))continue;yield*s(await o.get(a[1][0],u))}else{if(n&&!u.startsWith(n))continue;yield[u,a[1]]}}}(i)}async function zi(t,e,r){for(let[n,o]of e.value){if(r===n)return[e];if(r.startsWith(n)&&Array.isArray(o)){let i=await zi(t,await t.get(o[0],e.prefix+n),r.slice(n.length));return[e,...i]}}return[e]}async function yp(t,e,r,n,o){let i=new Ae;if(t=new Lt(i,t),!e.length){let g=await Gt.create();i.putSync(g.cid,g.bytes);let b=await Vn(t,g.cid,r,n,o),k={type:"put",root:b.root,key:r,value:n},v=await Hn.create(k,e);return e=await jn(t,e,v.cid),{root:b.root,additions:[g,...b.additions],removals:b.removals,head:e,event:v}}let s=new We(t),c=await Dc(s,e);if(!c)throw new Error("failed to find common ancestor event");let a=await s.get(c),{root:u}=a.value.data,l=await gp(s,e,c),d=new Map,m=new Map;for(let{value:g}of l){if(!["put","del"].includes(g.data.type))throw new Error(`unknown event type: ${g.data.type}`);let b=g.data.type==="put"?await Vn(t,u,g.data.key,g.data.value):await Ic(t,u,g.data.key);u=b.root;for(let k of b.additions)i.putSync(k.cid,k.bytes),d.set(k.cid.toString(),k);for(let k of b.removals)m.set(k.cid.toString(),k)}let f=await Vn(t,u,r,n,o);for(let g of f.additions)i.putSync(g.cid,g.bytes),d.set(g.cid.toString(),g);for(let g of f.removals)m.set(g.cid.toString(),g);let h={type:"put",root:f.root,key:r,value:n},p=await Hn.create(h,e);i.putSync(p.cid,p.bytes),e=await jn(t,e,p.cid);let w=f.root.toString();for(let g of m.keys())d.has(g)&&g!==w&&(d.delete(g),m.delete(g));return{root:f.root,additions:[...d.values()],removals:[...m.values()],head:e,event:p}}async function Or(t,e){if(!e.length)throw new Error("cannot determine root of headless clock");let r=new Ae;t=new Lt(r,t);let n=new We(t);if(e.length===1){let d=await n.get(e[0]),{root:m}=d.value.data;return{root:m,additions:[],removals:[]}}let o=await Dc(n,e);if(!o)throw new Error("failed to find common ancestor event");let i=await n.get(o),{root:s}=i.value.data,c=await gp(n,e,o),a=new Map,u=new Map;for(let{value:d}of c){if(!["put","del"].includes(d.data.type))throw new Error(`unknown event type: ${d.data.type}`);let m=d.data.type==="put"?await Vn(t,s,d.data.key,d.data.value):await Ic(t,s,d.data.key);s=m.root;for(let f of m.additions)r.putSync(f.cid,f.bytes),a.set(f.cid.toString(),f);for(let f of m.removals)u.set(f.cid.toString(),f)}let l=s.toString();for(let d of u.keys())a.has(d)&&d!==l&&(a.delete(d),u.delete(d));return{root:s,additions:[...a.values()],removals:[...u.values()]}}async function mp(t,e,r){if(!e.length)return;let n=await Or(t,e);return n.additions.length&&(t=new Lt(new Ae(n.additions),t)),hp(t,n.root,r)}async function*Lc(t,e,r){if(!e.length)return;let n=await Or(t,e);n.additions.length&&(t=new Lt(new Ae(n.additions),t)),yield*pp(t,n.root,r)}async function Dc(t,e){if(!e.length)return;let r=e.map(n=>[n]);for(;;){let n=!1;for(let o of r){let i=await Ax(t,o[o.length-1]);if(!i)continue;n=!0,o.push(i);let s=_x(r);if(s)return s}if(!n)return}}async function Ax(t,e){let{value:r}=await t.get(e);return r.parents.length?r.parents.length===1?r.parents[0]:Dc(t,r.parents):e}function _x(t){t=t.map(e=>[...e]);for(let e of t)for(let r of e){let n=!0;for(let o of t)if(e!==o&&(n=o.some(i=>String(i)===String(r)),!n))break;if(n)return r}}async function gp(t,e,r){if(e.length===1&&String(e[0])===String(r))return[];let n=new Map,o=await Promise.all(e.map(s=>wp(t,s,r)));for(let s of o)for(let{event:c,depth:a}of s){let u=n.get(c.cid.toString());u?u.weight+=a:n.set(c.cid.toString(),{event:c,weight:a})}let i=new Map;for(let{event:s,weight:c}of n.values()){let a=i.get(c);a?a.push(s):i.set(c,[s])}return Array.from(i).sort((s,c)=>c[0]-s[0]).flatMap(([,s])=>s.sort((c,a)=>String(c.cid)<String(a.cid)?-1:1))}async function wp(t,e,r,n=0){let o=await t.get(e),i=[{event:o,depth:n}],{parents:s}=o.value;if(s.length===1&&String(s[0])===String(r))return i;let c=await Promise.all(s.map(a=>wp(t,a,r,n+1)));return i.concat(...c)}var Wr={};G(Wr,{DEFAULT_DIRECTORY_MODE:()=>By,DEFAULT_FILE_MODE:()=>_y,NodeType:()=>P,code:()=>Vr,createAdvancedFile:()=>Qx,createComplexFile:()=>Xx,createDirectoryShard:()=>Ly,createEmptyFile:()=>Kx,createFileChunk:()=>Gx,createFileShard:()=>Jx,createFlatDirectory:()=>Yi,createRaw:()=>Cy,createShardedDirectory:()=>Iy,createSimpleFile:()=>Ty,createSymlink:()=>Ny,cumulativeContentByteLength:()=>Xe,cumulativeDagByteLength:()=>qr,decode:()=>Fy,decodeMetadata:()=>Zt,encode:()=>Py,encodeAdvancedFile:()=>eu,encodeComplexFile:()=>tu,encodeDirectory:()=>ts,encodeDirectoryMetadata:()=>iu,encodeFile:()=>Dy,encodeFileChunk:()=>Zc,encodeFileShard:()=>Yx,encodeHAMTShard:()=>ru,encodeLink:()=>Zi,encodeMetadata:()=>Jn,encodeMode:()=>Ry,encodeRaw:()=>Yc,encodeSimpleFile:()=>es,encodeSymlink:()=>Uy,filesize:()=>rk,matchFile:()=>tk,name:()=>Xc});var Bx=new TextDecoder;function Nc(t,e){let r=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=t.length)throw new Error("protobuf: unexpected end of data");let o=t[e++];if(r+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[r,e]}function $i(t,e){let r;[r,e]=Nc(t,e);let n=e+r;if(r<0||n<0)throw new Error("protobuf: invalid length");if(n>t.length)throw new Error("protobuf: unexpected end of data");return[t.subarray(e,n),n]}function bp(t,e){let r;return[r,e]=Nc(t,e),[r&7,r>>3,e]}function Cx(t){let e={},r=t.length,n=0;for(;n<r;){let o,i;if([o,i,n]=bp(t,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=$i(t,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=$i(t,n),e.Name=Bx.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=Nc(t,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>r)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function xp(t){let e=t.length,r=0,n,o=!1,i;for(;r<e;){let c,a;if([c,a,r]=bp(t,r),c!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${c}`);if(a===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,r]=$i(t,r),n&&(o=!0)}else if(a===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let u;[u,r]=$i(t,r),n.push(Cx(u))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${a}`)}if(r>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var vp=new TextEncoder,kp=2**32,Tx=2**31;function Ix(t,e){let r=e.length;if(typeof t.Tsize=="number"){if(t.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(t.Tsize))throw new Error("Tsize too large for encoding");r=qn(e,r,t.Tsize)-1,e[r]=24}if(typeof t.Name=="string"){let n=vp.encode(t.Name);r-=n.length,e.set(n,r),r=qn(e,r,n.length)-1,e[r]=18}return t.Hash&&(r-=t.Hash.length,e.set(t.Hash,r),r=qn(e,r,t.Hash.length)-1,e[r]=10),e.length-r}function Ep(t){let e=Dx(t),r=new Uint8Array(e),n=e;if(t.Data&&(n-=t.Data.length,r.set(t.Data,n),n=qn(r,n,t.Data.length)-1,r[n]=10),t.Links)for(let o=t.Links.length-1;o>=0;o--){let i=Ix(t.Links[o],r.subarray(0,n));n-=i,n=qn(r,n,i)-1,r[n]=18}return r}function Lx(t){let e=0;if(t.Hash){let r=t.Hash.length;e+=1+r+zr(r)}if(typeof t.Name=="string"){let r=vp.encode(t.Name).length;e+=1+r+zr(r)}return typeof t.Tsize=="number"&&(e+=1+zr(t.Tsize)),e}function Dx(t){let e=0;if(t.Data){let r=t.Data.length;e+=1+r+zr(r)}if(t.Links)for(let r of t.Links){let n=Lx(r);e+=1+n+zr(n)}return e}function qn(t,e,r){e-=zr(r);let n=e;for(;r>=Tx;)t[e++]=r&127|128,r/=128;for(;r>=128;)t[e++]=r&127|128,r>>>=7;return t[e]=r,n}function zr(t){return t%2===0&&t++,Math.floor((Nx(t)+6)/7)}function Nx(t){let e=0;return t>=kp&&(t=Math.floor(t/kp),e=32),t>=65536&&(t>>>=16,e+=16),t>=256&&(t>>>=8,e+=8),e+Ux[t]}var Ux=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var Px=["Data","Links"],Fx=["Hash","Name","Tsize"],Uc=new TextEncoder;function Ap(t,e){if(t===e)return 0;let r=t.Name?Uc.encode(t.Name):[],n=e.Name?Uc.encode(e.Name):[],o=r.length,i=n.length;for(let s=0,c=Math.min(o,i);s<c;++s)if(r[s]!==n[s]){o=r[s],i=n[s];break}return o<i?-1:i<o?1:0}function Sp(t,e){return!Object.keys(t).some(r=>!e.includes(r))}function Mx(t){if(typeof t.asCID=="object"){let r=H.asCID(t);if(!r)throw new TypeError("Invalid DAG-PB form");return{Hash:r}}if(typeof t!="object"||Array.isArray(t))throw new TypeError("Invalid DAG-PB form");let e={};if(t.Hash){let r=H.asCID(t.Hash);try{r||(typeof t.Hash=="string"?r=H.parse(t.Hash):t.Hash instanceof Uint8Array&&(r=H.decode(t.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}r&&(e.Hash=r)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof t.Name=="string"&&(e.Name=t.Name),typeof t.Tsize=="number"&&(e.Tsize=t.Tsize),e}function Pc(t){if((t instanceof Uint8Array||typeof t=="string")&&(t={Data:t}),typeof t!="object"||Array.isArray(t))throw new TypeError("Invalid DAG-PB form");let e={};if(t.Data!==void 0)if(typeof t.Data=="string")e.Data=Uc.encode(t.Data);else if(t.Data instanceof Uint8Array)e.Data=t.Data;else throw new TypeError("Invalid DAG-PB form");if(t.Links!==void 0)if(Array.isArray(t.Links))e.Links=t.Links.map(Mx),e.Links.sort(Ap);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function _p(t){if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form");if(!Sp(t,Px))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(t.Data!==void 0&&!(t.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(t.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<t.Links.length;e++){let r=t.Links[e];if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!Sp(r,Fx))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(r.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(r.Hash==null||!r.Hash["/"]||r.Hash["/"]!==r.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(r.Name!==void 0&&typeof r.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(r.Tsize!==void 0){if(typeof r.Tsize!="number"||r.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(r.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&Ap(r,t.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}var Jt=112;function Bp(t){_p(t);let e={};return t.Links&&(e.Links=t.Links.map(r=>{let n={};return r.Hash&&(n.Hash=r.Hash.bytes),r.Name!==void 0&&(n.Name=r.Name),r.Tsize!==void 0&&(n.Tsize=r.Tsize),n})),t.Data&&(e.Data=t.Data),Ep(e)}function Ge(t){let e=xp(t),r={};return e.Data&&(r.Data=e.Data),e.Links&&(r.Links=e.Links.map(n=>{let o={};try{o.Hash=H.decode(n.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return n.Name!==void 0&&(o.Name=n.Name),n.Tsize!==void 0&&(o.Tsize=n.Tsize),o})),r}var it=V(vy(),1),Hr=it.default.Reader,Qc=it.default.Writer,D=it.default.util,ne=it.default.roots.unixfs||(it.default.roots.unixfs={}),jr=ne.Data=(()=>{function t(e){if(this.blocksizes=[],e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.Type=0,t.prototype.Data=D.newBuffer([]),t.prototype.filesize=D.Long?D.Long.fromBits(0,0,!0):0,t.prototype.blocksizes=D.emptyArray,t.prototype.hashType=D.Long?D.Long.fromBits(0,0,!0):0,t.prototype.fanout=D.Long?D.Long.fromBits(0,0,!0):0,t.prototype.mode=0,t.prototype.mtime=null,t.encode=function(r,n){if(n||(n=Qc.create()),n.uint32(8).int32(r.Type),r.Data!=null&&Object.hasOwnProperty.call(r,"Data")&&n.uint32(18).bytes(r.Data),r.filesize!=null&&Object.hasOwnProperty.call(r,"filesize")&&n.uint32(24).uint64(r.filesize),r.blocksizes!=null&&r.blocksizes.length)for(var o=0;o<r.blocksizes.length;++o)n.uint32(32).uint64(r.blocksizes[o]);return r.hashType!=null&&Object.hasOwnProperty.call(r,"hashType")&&n.uint32(40).uint64(r.hashType),r.fanout!=null&&Object.hasOwnProperty.call(r,"fanout")&&n.uint32(48).uint64(r.fanout),r.mode!=null&&Object.hasOwnProperty.call(r,"mode")&&n.uint32(56).uint32(r.mode),r.mtime!=null&&Object.hasOwnProperty.call(r,"mtime")&&ne.UnixTime.encode(r.mtime,n.uint32(66).fork()).ldelim(),n},t.decode=function(r,n){r instanceof Hr||(r=Hr.create(r));for(var o=n===void 0?r.len:r.pos+n,i=new ne.Data;r.pos<o;){var s=r.uint32();switch(s>>>3){case 1:i.Type=r.int32();break;case 2:i.Data=r.bytes();break;case 3:i.filesize=r.uint64();break;case 4:if(i.blocksizes&&i.blocksizes.length||(i.blocksizes=[]),(s&7)===2)for(var c=r.uint32()+r.pos;r.pos<c;)i.blocksizes.push(r.uint64());else i.blocksizes.push(r.uint64());break;case 5:i.hashType=r.uint64();break;case 6:i.fanout=r.uint64();break;case 7:i.mode=r.uint32();break;case 8:i.mtime=ne.UnixTime.decode(r,r.uint32());break;default:r.skipType(s&7);break}}if(!i.hasOwnProperty("Type"))throw D.ProtocolError("missing required 'Type'",{instance:i});return i},t.fromObject=function(r){if(r instanceof ne.Data)return r;var n=new ne.Data;switch(r.Type){case"Raw":case 0:n.Type=0;break;case"Directory":case 1:n.Type=1;break;case"File":case 2:n.Type=2;break;case"Metadata":case 3:n.Type=3;break;case"Symlink":case 4:n.Type=4;break;case"HAMTShard":case 5:n.Type=5;break}if(r.Data!=null&&(typeof r.Data=="string"?D.base64.decode(r.Data,n.Data=D.newBuffer(D.base64.length(r.Data)),0):r.Data.length&&(n.Data=r.Data)),r.filesize!=null&&(D.Long?(n.filesize=D.Long.fromValue(r.filesize)).unsigned=!0:typeof r.filesize=="string"?n.filesize=parseInt(r.filesize,10):typeof r.filesize=="number"?n.filesize=r.filesize:typeof r.filesize=="object"&&(n.filesize=new D.LongBits(r.filesize.low>>>0,r.filesize.high>>>0).toNumber(!0))),r.blocksizes){if(!Array.isArray(r.blocksizes))throw TypeError(".Data.blocksizes: array expected");n.blocksizes=[];for(var o=0;o<r.blocksizes.length;++o)D.Long?(n.blocksizes[o]=D.Long.fromValue(r.blocksizes[o])).unsigned=!0:typeof r.blocksizes[o]=="string"?n.blocksizes[o]=parseInt(r.blocksizes[o],10):typeof r.blocksizes[o]=="number"?n.blocksizes[o]=r.blocksizes[o]:typeof r.blocksizes[o]=="object"&&(n.blocksizes[o]=new D.LongBits(r.blocksizes[o].low>>>0,r.blocksizes[o].high>>>0).toNumber(!0))}if(r.hashType!=null&&(D.Long?(n.hashType=D.Long.fromValue(r.hashType)).unsigned=!0:typeof r.hashType=="string"?n.hashType=parseInt(r.hashType,10):typeof r.hashType=="number"?n.hashType=r.hashType:typeof r.hashType=="object"&&(n.hashType=new D.LongBits(r.hashType.low>>>0,r.hashType.high>>>0).toNumber(!0))),r.fanout!=null&&(D.Long?(n.fanout=D.Long.fromValue(r.fanout)).unsigned=!0:typeof r.fanout=="string"?n.fanout=parseInt(r.fanout,10):typeof r.fanout=="number"?n.fanout=r.fanout:typeof r.fanout=="object"&&(n.fanout=new D.LongBits(r.fanout.low>>>0,r.fanout.high>>>0).toNumber(!0))),r.mode!=null&&(n.mode=r.mode>>>0),r.mtime!=null){if(typeof r.mtime!="object")throw TypeError(".Data.mtime: object expected");n.mtime=ne.UnixTime.fromObject(r.mtime)}return n},t.toObject=function(r,n){n||(n={});var o={};if((n.arrays||n.defaults)&&(o.blocksizes=[]),n.defaults){if(o.Type=n.enums===String?"Raw":0,n.bytes===String?o.Data="":(o.Data=[],n.bytes!==Array&&(o.Data=D.newBuffer(o.Data))),D.Long){var i=new D.Long(0,0,!0);o.filesize=n.longs===String?i.toString():n.longs===Number?i.toNumber():i}else o.filesize=n.longs===String?"0":0;if(D.Long){var i=new D.Long(0,0,!0);o.hashType=n.longs===String?i.toString():n.longs===Number?i.toNumber():i}else o.hashType=n.longs===String?"0":0;if(D.Long){var i=new D.Long(0,0,!0);o.fanout=n.longs===String?i.toString():n.longs===Number?i.toNumber():i}else o.fanout=n.longs===String?"0":0;o.mode=0,o.mtime=null}if(r.Type!=null&&r.hasOwnProperty("Type")&&(o.Type=n.enums===String?ne.Data.DataType[r.Type]:r.Type),r.Data!=null&&r.hasOwnProperty("Data")&&(o.Data=n.bytes===String?D.base64.encode(r.Data,0,r.Data.length):n.bytes===Array?Array.prototype.slice.call(r.Data):r.Data),r.filesize!=null&&r.hasOwnProperty("filesize")&&(typeof r.filesize=="number"?o.filesize=n.longs===String?String(r.filesize):r.filesize:o.filesize=n.longs===String?D.Long.prototype.toString.call(r.filesize):n.longs===Number?new D.LongBits(r.filesize.low>>>0,r.filesize.high>>>0).toNumber(!0):r.filesize),r.blocksizes&&r.blocksizes.length){o.blocksizes=[];for(var s=0;s<r.blocksizes.length;++s)typeof r.blocksizes[s]=="number"?o.blocksizes[s]=n.longs===String?String(r.blocksizes[s]):r.blocksizes[s]:o.blocksizes[s]=n.longs===String?D.Long.prototype.toString.call(r.blocksizes[s]):n.longs===Number?new D.LongBits(r.blocksizes[s].low>>>0,r.blocksizes[s].high>>>0).toNumber(!0):r.blocksizes[s]}return r.hashType!=null&&r.hasOwnProperty("hashType")&&(typeof r.hashType=="number"?o.hashType=n.longs===String?String(r.hashType):r.hashType:o.hashType=n.longs===String?D.Long.prototype.toString.call(r.hashType):n.longs===Number?new D.LongBits(r.hashType.low>>>0,r.hashType.high>>>0).toNumber(!0):r.hashType),r.fanout!=null&&r.hasOwnProperty("fanout")&&(typeof r.fanout=="number"?o.fanout=n.longs===String?String(r.fanout):r.fanout:o.fanout=n.longs===String?D.Long.prototype.toString.call(r.fanout):n.longs===Number?new D.LongBits(r.fanout.low>>>0,r.fanout.high>>>0).toNumber(!0):r.fanout),r.mode!=null&&r.hasOwnProperty("mode")&&(o.mode=r.mode),r.mtime!=null&&r.hasOwnProperty("mtime")&&(o.mtime=ne.UnixTime.toObject(r.mtime,n)),o},t.prototype.toJSON=function(){return this.constructor.toObject(this,it.default.util.toJSONOptions)},t.DataType=function(){let e={},r=Object.create(e);return r[e[0]="Raw"]=0,r[e[1]="Directory"]=1,r[e[2]="File"]=2,r[e[3]="Metadata"]=3,r[e[4]="Symlink"]=4,r[e[5]="HAMTShard"]=5,r}(),t})(),h3=ne.UnixTime=(()=>{function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.Seconds=D.Long?D.Long.fromBits(0,0,!1):0,t.prototype.FractionalNanoseconds=0,t.encode=function(r,n){return n||(n=Qc.create()),n.uint32(8).int64(r.Seconds),r.FractionalNanoseconds!=null&&Object.hasOwnProperty.call(r,"FractionalNanoseconds")&&n.uint32(21).fixed32(r.FractionalNanoseconds),n},t.decode=function(r,n){r instanceof Hr||(r=Hr.create(r));for(var o=n===void 0?r.len:r.pos+n,i=new ne.UnixTime;r.pos<o;){var s=r.uint32();switch(s>>>3){case 1:i.Seconds=r.int64();break;case 2:i.FractionalNanoseconds=r.fixed32();break;default:r.skipType(s&7);break}}if(!i.hasOwnProperty("Seconds"))throw D.ProtocolError("missing required 'Seconds'",{instance:i});return i},t.fromObject=function(r){if(r instanceof ne.UnixTime)return r;var n=new ne.UnixTime;return r.Seconds!=null&&(D.Long?(n.Seconds=D.Long.fromValue(r.Seconds)).unsigned=!1:typeof r.Seconds=="string"?n.Seconds=parseInt(r.Seconds,10):typeof r.Seconds=="number"?n.Seconds=r.Seconds:typeof r.Seconds=="object"&&(n.Seconds=new D.LongBits(r.Seconds.low>>>0,r.Seconds.high>>>0).toNumber())),r.FractionalNanoseconds!=null&&(n.FractionalNanoseconds=r.FractionalNanoseconds>>>0),n},t.toObject=function(r,n){n||(n={});var o={};if(n.defaults){if(D.Long){var i=new D.Long(0,0,!1);o.Seconds=n.longs===String?i.toString():n.longs===Number?i.toNumber():i}else o.Seconds=n.longs===String?"0":0;o.FractionalNanoseconds=0}return r.Seconds!=null&&r.hasOwnProperty("Seconds")&&(typeof r.Seconds=="number"?o.Seconds=n.longs===String?String(r.Seconds):r.Seconds:o.Seconds=n.longs===String?D.Long.prototype.toString.call(r.Seconds):n.longs===Number?new D.LongBits(r.Seconds.low>>>0,r.Seconds.high>>>0).toNumber():r.Seconds),r.FractionalNanoseconds!=null&&r.hasOwnProperty("FractionalNanoseconds")&&(o.FractionalNanoseconds=r.FractionalNanoseconds),o},t.prototype.toJSON=function(){return this.constructor.toObject(this,it.default.util.toJSONOptions)},t})(),p3=ne.Metadata=(()=>{function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.MimeType="",t.encode=function(r,n){return n||(n=Qc.create()),r.MimeType!=null&&Object.hasOwnProperty.call(r,"MimeType")&&n.uint32(10).string(r.MimeType),n},t.decode=function(r,n){r instanceof Hr||(r=Hr.create(r));for(var o=n===void 0?r.len:r.pos+n,i=new ne.Metadata;r.pos<o;){var s=r.uint32();switch(s>>>3){case 1:i.MimeType=r.string();break;default:r.skipType(s&7);break}}return i},t.fromObject=function(r){if(r instanceof ne.Metadata)return r;var n=new ne.Metadata;return r.MimeType!=null&&(n.MimeType=String(r.MimeType)),n},t.toObject=function(r,n){n||(n={});var o={};return n.defaults&&(o.MimeType=""),r.MimeType!=null&&r.hasOwnProperty("MimeType")&&(o.MimeType=r.MimeType),o},t.prototype.toJSON=function(){return this.constructor.toObject(this,it.default.util.toJSONOptions)},t})();var P=jr.DataType;var Ay=Object.freeze([]),Jc=new Uint8Array(0),ke=Object.freeze({}),_y=parseInt("0644",8),By=parseInt("0755",8),Vr=Jt,Xc="UnixFS",Et=(t,e)=>(Object(globalThis).debug&&console.log({data:t,links:e}),Bp(Pc({Data:jr.encode(t).finish(),Links:e}))),Cy=t=>({type:P.Raw,content:t}),Kx=t=>Ty(Jc,t),Ty=(t,e)=>({type:P.File,layout:"simple",content:t,metadata:Zt(e)}),Gx=t=>({type:P.File,layout:"simple",content:t}),Qx=(t,e)=>({type:P.File,layout:"advanced",parts:t,metadata:Zt(e)}),Jx=t=>({type:P.File,layout:"advanced",parts:t}),Xx=(t,e,r)=>({type:P.File,layout:"complex",content:t,parts:e,metadata:Zt(r)}),Yi=(t,e)=>({type:P.Directory,metadata:Zt(e),entries:t}),Iy=(t,e,r,n,o=ke)=>({type:P.HAMTShard,bitfield:e,fanout:nu(r),hashType:ou(n),entries:t,metadata:Zt(o)}),Ly=(t,e,r,n)=>({type:P.HAMTShard,bitfield:e,fanout:nu(r),hashType:ou(n),entries:t}),Yc=t=>Et({Type:P.Raw,Data:t.byteLength>0?t:void 0,filesize:t.byteLength,blocksizes:Ay},[]),Dy=(t,e=!1)=>{let r=e?ke:Object(t).metadata;switch(t.layout){case"simple":return es(t.content,r);case"advanced":return eu(t.parts,r);case"complex":return tu(t.content,t.parts,r);default:throw new TypeError(`File with unknown layout "${Object(t).layout}" was passed`)}},Zc=t=>es(t,ke),Yx=t=>Et({Type:P.File,blocksizes:t.map(Qn),filesize:Xe(t)},t.map(Zi)),eu=(t,e=ke)=>Et({Type:P.File,blocksizes:t.map(Qn),filesize:Xe(t),...Jn(e)},t.map(Zi)),Zi=t=>({Name:"",Tsize:t.dagByteLength,Hash:t.cid}),es=(t,e=ke)=>Et({Type:P.File,Data:t.byteLength>0?t:void 0,filesize:t.byteLength,blocksizes:[],...Jn(e)},[]),tu=(t,e,r=ke)=>Et({Type:P.File,Data:t,filesize:t.byteLength+Xe(e),blocksizes:e.map(Qn)},e.map(Zi)),ts=t=>Et({Type:t.type,...iu(t.metadata||ke)},t.entries.map(My)),ru=({bitfield:t,fanout:e,hashType:r,entries:n,metadata:o=ke})=>Et({Type:P.HAMTShard,Data:t.byteLength>0?t:void 0,fanout:nu(e),hashType:ou(r),...iu(o)},n.map(My)),nu=t=>{if(Math.log2(t)%1===0)return t;throw new TypeError(`Expected hamt size to be a power of two instead got ${t}`)},ou=t=>{if(Number.isInteger(t))return t;throw new TypeError(`Expected an integer value instead got ${t}`)};var Ny=(t,e=ke)=>({type:P.Symlink,content:t,metadata:Zt(e)}),Uy=(t,e=!1)=>{let r=e?ke:Object(t).metadata;return Et({Type:P.Symlink,Data:t.content,...Jn(r||ke)},[])},Py=(t,e=!0)=>{switch(t.type){case P.Raw:return Yc(t.content);case P.File:return Dy(t);case P.Directory:return ts(t);case P.HAMTShard:return ru(t);case P.Symlink:return Uy(t);default:throw new Error(`Unknown node type ${Object(t).type}`)}},Fy=t=>{let e=Ge(t),r=jr.decode(e.Data),{Type:n,Data:o,mtime:i,mode:s,blocksizes:c,...a}=jr.toObject(r,{defaults:!1,arrays:!0,longs:Number,objects:!1}),u={...s&&{mode:s},...Zx(i)},l=e.Links;switch(r.Type){case P.Raw:return Cy(o);case P.File:return l.length===0?new Qi(o,u):o.byteLength===0?new Ji(Ey(a.blocksizes,l),u):new Xi(o,Ey(a.blocksizes,l),u);case P.Directory:return Yi(Sy(l),u);case P.HAMTShard:return Iy(Sy(l),o||Jc,a.fanout,a.hashType,u);case P.Symlink:return Ny(o,u);default:throw new TypeError(`Unsupported node type ${r.Type}`)}},Zx=t=>t==null?void 0:{mtime:{secs:t.Seconds,nsecs:t.FractionalNanoseconds||0}};var Ey=(t,e)=>{let r=[],n=t.length,o=0;for(;o<n;)r.push({cid:e[o].Hash,dagByteLength:e[o].Tsize||0,contentByteLength:t[o]});return r},Sy=t=>t.map(e=>({cid:e.Hash,name:e.Name||"",dagByteLength:e.Tsize||0})),Xe=t=>t.reduce((e,r)=>e+r.contentByteLength,0),qr=(t,e)=>e.reduce((r,n)=>r+n.dagByteLength,t.byteLength),Qn=t=>t.contentByteLength,My=({name:t,dagByteLength:e,cid:r})=>({Name:t,Tsize:e,Hash:r}),iu=t=>Jn(t,By),Jn=({mode:t,mtime:e},r=_y)=>({mode:t!=null?Ry(t,r):void 0,mtime:e!=null?ek(e):void 0}),Zt=t=>t==null?ke:{...t.mode==null?void 0:{mode:Oy(t.mode)},...t.mtime==null?void 0:{mtime:t.mtime}},ek=t=>t==null?void 0:t.nsecs!==0?{Seconds:t.secs,FractionalNanoseconds:t.nsecs}:{Seconds:t.secs},Ry=(t,e)=>{let r=t==null?void 0:Oy(t);return r===e||r==null?void 0:r},Oy=t=>t&4095|t&4294963200,tk=({content:t=Jc,parts:e=Ay,metadata:r=ke,...n})=>e.length===0?new Qi(t,r):t.byteLength===0?new Ji(e,r):new Xi(t,e,r),Qi=class{constructor(e,r){this.content=e,this.metadata=r,this.layout="simple",this.type=P.File}get filesize(){return this.content.byteLength}encode(){return es(this.content,this.metadata)}},Ji=class{constructor(e,r){this.parts=e,this.metadata=r}get layout(){return"advanced"}get type(){return P.File}get fileSize(){return Xe(this.parts)}get blockSizes(){return this.parts.map(Qn)}encode(){return eu(this.parts,this.metadata)}},Xi=class{constructor(e,r,n){this.content=e,this.parts=r,this.metadata=n}get layout(){return"complex"}get type(){return P.File}get fileSize(){return this.content.byteLength+Xe(this.parts)}get blockSizes(){return this.parts.map(Qn)}encode(){return tu(this.content,this.parts,this.metadata)}},rk=t=>{switch(t.type){case P.Raw:case P.Symlink:return t.content.byteLength;case P.File:switch(t.layout){case"simple":return t.content.byteLength;case"advanced":return Xe(t.parts);case"complex":return t.content.byteLength+Xe(t.parts)}default:return 0}};var nk=function*(t){let e=yield*t;yield*ns(e)};function*lu(){return yield ss}var Gr=function*(){yield as};var rs=function*(t){let e=yield*lu();if(ik(t)){let r=!1,n;if(t.then(o=>{r=!1,n=o,St(e)},o=>{r=!0,n=o,St(e)}),yield*Gr(),r)throw n;return n}else return uk(ok(e)),yield*Gr(),t};function*ok(t){St(t)}var ik=t=>t!=null&&typeof t.then=="function",ns=function*(t){yield t},os=function*(t){let e=[];for(let r of Object.entries(t)){let[n,o]=r;o!==Zn&&e.push(yield*Jr(ak(o,n)))}yield*du(e)},is=t=>t.length>0?sk(t.map(nk)):Zn;function*sk(t){let e=[];for(let r of t)e.push(yield*Jr(r));yield*du(e)}var ak=(t,e)=>t===Zn?Zn:t instanceof Xn?new Xn([...t.tags,e],t.source):new Xn([e],t),Xn=class{constructor(e,r){this.tags=e,this.source=r,this.controller}[Symbol.iterator](){return this.controller||(this.controller=this.source[Symbol.iterator]()),this}box(e){if(e.done)return e;switch(e.value){case as:case ss:return e;default:{let r=e,{value:n}=r;for(let o of this.tags)n=ck(o,n);return r.value=n,r}}}next(e){return this.box(this.controller.next(e))}throw(e){return this.box(this.controller.throw(e))}return(e){return this.box(this.controller.return(e))}get[Symbol.toStringTag](){return"TaggedEffect"}},eo=()=>Zn;var ck=(t,e)=>({type:t,[t]:e});var ss=Symbol("current"),as=Symbol("suspend");var st=class t{static of(e){return e.group||Kr}static enqueue(e,r){e.group=r,r.stack.active.push(e)}constructor(e,r=[],n=new Set,o=new Qr(r,n)){this.driver=e,this.parent=t.of(e),this.stack=o,this.id=++jy}},su=class{constructor(){this.status=Yn,this.stack=new Qr,this.id=0}},Qr=class{constructor(e=[],r=new Set){this.active=e,this.idle=r}static size({active:e,idle:r}){return e.length+r.size}},uk=t=>St(t[Symbol.iterator]()),St=t=>{let e=st.of(t);for(e.stack.active.push(t),e.stack.idle.delete(t);e.parent;){let{idle:r,active:n}=e.parent.stack;if(r.has(e.driver))r.delete(e.driver),n.push(e.driver);else break;e=e.parent}if(Kr.status===Yn)for(Kr.status=Vy;;)try{for(let r of fu(Kr));Kr.status=Yn;break}catch{Kr.stack.active.shift()}},lk=t=>St(t),fu=function*(t){let{active:e}=t.stack,r=e[0];for(t.stack.idle.delete(r);r;){let n=qy;e:for(;!n.done&&r===e[0];){let o=n.value;switch(o){case as:t.stack.idle.add(r);break e;case ss:n=r.next(r);break;default:n=r.next(yield o);break}}e.shift(),r=e[0],t.stack.idle.delete(r)}};var Jr=(t,e)=>new uu(t,e),fk=(t,e)=>$y(t,{ok:!0,value:e});var au=(t,e)=>$y(t,{ok:!1,error:e});function*$y(t,e){try{let r=t,n=e.ok?r.return(e.value):r.throw(e.error);if(!n.done)if(n.value===as){let{idle:o}=st.of(r).stack;o.add(r)}else St(r)}catch{}}function*du(t){if(t.length===0)return;let e=yield*lu(),r=new st(e),n=null;for(let o of t){let{result:i}=o;if(i){!i.ok&&!n&&(n=i);continue}dk(o,r)}try{if(n)throw n.error;for(;yield*fu(r),Qr.size(r.stack)>0;)yield*Gr()}catch(o){for(let i of r.stack.active)yield*au(i,o);for(let i of r.stack.idle)yield*au(i,o),St(i);throw o}}var dk=(t,e)=>{let r=st.of(t);if(r!==e){let{active:n,idle:o}=r.stack,i=e.stack;if(t.group=e,o.has(t))o.delete(t),i.idle.add(t);else{let s=n.indexOf(t);s>=0&&(n.splice(s,1),i.active.push(t))}}};function*hu(t){t.status===Yn&&(yield*t),t.result||(yield*du([t]));let e=t.result;if(e.ok)return e.value;throw e.error}var cu=class{constructor(e){this.handler=e,this.result}get promise(){let{result:e}=this,r=e==null?new Promise((n,o)=>{this.handler.onsuccess=n,this.handler.onfailure=o}):e.ok?Promise.resolve(e.value):Promise.reject(e.error);return Object.defineProperty(this,"promise",{value:r}),r}then(e,r){return this.activate().promise.then(e,r)}catch(e){return this.activate().promise.catch(e)}finally(e){return this.activate().promise.finally(e)}activate(){return this}},uu=class extends cu{constructor(e,r=hk,n={},o=qy){super(n),this.id=++jy,this.name=r.name||"",this.task=e,this.state=o,this.status=Yn,this.result,this.handler=n,this.controller}*resume(){lk(this)}join(){return hu(this)}abort(e){return au(this,e)}exit(e){return fk(this,e)}get[Symbol.toStringTag](){return"Fork"}*[Symbol.iterator](){return this.activate()}activate(){return this.controller=this.task[Symbol.iterator](),this.status=Vy,St(this),this}panic(e){this.result={ok:!1,error:e},this.status=zy;let{handler:r}=this;throw r.onfailure&&r.onfailure(e),e}step(e){if(this.state=e,e.done){this.result={ok:!0,value:e.value},this.status=zy;let{handler:r}=this;r.onsuccess&&r.onsuccess(e.value)}return e}next(e){try{return this.step(this.controller.next(e))}catch(r){return this.panic(r)}}return(e){try{return this.step(this.controller.return(e))}catch(r){return this.panic(r)}}throw(e){try{return this.step(this.controller.throw(e))}catch(r){return this.panic(r)}}},Hy=function*(t,e){let r=yield*lu(),n=new st(r);for(st.enqueue(t[Symbol.iterator](),n);;){for(let o of fu(n))st.enqueue(e(o)[Symbol.iterator](),n);if(Qr.size(n.stack)>0)yield*Gr();else break}},jy=0,Yn="idle",Vy="active",zy="finished",qy={done:!1,value:ss},hk={},Zn=function*(){}(),Kr=new su;function pu(){}Object.defineProperties(pu,{prototype:{value:new Proxy(Object.prototype,{get(t,e,r){return typeof e=="symbol"?Reflect.get(t,e,r):r.get(e)}})}});var yu=()=>new to;var Ky=(t,e=0,r=t.byteLength)=>{let n=[],o=e<0?t.byteLength-e:e,i=r<0?t.byteLength-r:r;if(o===0&&i>=t.byteLength)return t;if(o>i||o>t.byteLength||i<=0)return yu();let s=0,c=0;for(let a of t.segments){let u=c+a.byteLength;if(s===0){if(i<=u){let l=a.subarray(o-c,i-c);n.push(l),s=l.byteLength;break}else if(o<u){let l=o===c?a:a.subarray(o-c);n.push(l),s=l.byteLength}}else if(i<=u){let l=i===u?a:a.subarray(0,i-c);n.push(l),s+=l.byteLength;break}else n.push(a),s+=a.byteLength;c=u}return new to(n,t.byteOffset+o,s)},pk=(t,e)=>e.byteLength>0?(t.segments.push(e),new to(t.segments,t.byteOffset,t.byteLength+e.byteLength)):t,yk=(t,e)=>{if(e<t.byteLength){let r=0;for(let n of t.segments){if(e<r+n.byteLength)return n[e-r];r+=n.byteLength}}},mk=(t,e,r)=>{let n=r;for(let o of t.segments)e.set(o,n),n+=o.byteLength;return e};function*gk(t){for(let e of t.segments)yield*e}var to=class extends pu{constructor(e=[],r=0,n=0){super(),this.segments=e,this.byteLength=n,this.length=n,this.byteOffset=r}[Symbol.iterator](){return gk(this)}slice(e,r){return Ky(this,e,r)}subarray(e,r){return Ky(this,e,r)}push(e){return pk(this,e)}get(e){return yk(this,e)}copyTo(e,r){return mk(this,e,r)}};var ro=t=>{throw new Error(t)},Gy=(t,e,...r)=>ro(String.raw(t,JSON.stringify(e),...r)),Qy=new Uint8Array(0),Jy=[];var Xy=t=>({config:t,buffer:yu()}),Yy=(t,e)=>e.byteLength>0?em(t.config,t.buffer.push(e),!1):{...t,chunks:Jy},Zy=t=>em(t.config,t.buffer,!0),em=(t,e,r)=>{let n=t.chunker,o=[],i=0;for(let s of n.cut(n.context,e,r))if(s>0){let c=e.subarray(i,i+s);o.push(c),i+=s}return{config:t,chunks:o,buffer:e.subarray(i)}};var tm=()=>({mutable:!0,needs:{},nodes:{},links:{},linked:wu});var bu=(t,e)=>{let r=Xr(e,{});for(let n of t){let{ready:o,has:i,wants:s}=nm(n.children,r.links);s.length===0?r=Xr(r,{links:gu(void 0,i),linked:[{id:n.id,links:o}]}):r=Xr(r,{needs:gu(n.id,s),nodes:{[n.id]:{children:n.children,count:s.length}}})}return r},rm=(t,e,r)=>{let n=r.needs[t],o=r.nodes[n];if(o!=null)if(o.count===1){let{ready:i,has:s}=nm(o.children,{...r.links,[t]:e});return Xr(r,{needs:{[t]:void 0},links:gu(void 0,s),nodes:{[n]:void 0},linked:[{id:n,links:i}]})}else return Xr(r,{needs:{[t]:void 0},links:{[t]:e},nodes:{[n]:{...o,count:o.count-1}}});else return Xr(r,{links:{[t]:e}})},Xr=(t,{needs:e,nodes:r,links:n,linked:o})=>{let i=t.mutable?t:{...t},s=t.mutable?kk:void 0;return e&&(i.needs=mu(t.needs,e,s)),r&&(i.nodes=mu(t.nodes,r,s)),n&&(i.links=mu(t.links,n,s)),i.linked=o?xk(t.linked||wu,o,wu):t.linked||[],i},gu=(t,e)=>{let r={};for(let n of e)r[n]=t;return r},mu=(t,e,r=t)=>{let n=t===r?{...t}:t;for(let o of Object.entries(e)){let[i,s]=o;s==null?delete n[i]:n[i]=s}return n};var xk=(t,e,r=t)=>{if(t===r)return[...t,...e];for(let n of e)t.push(n);return t},nm=(t,e)=>{let r=[],n=[],o=[];for(let i of t){let s=e[i];s?(r.push(i),o.push(s)):n.push(i)}return{has:r,wants:n,ready:o}},wu=Object.freeze([]),kk=Object.freeze({});var om=(t,e)=>{switch(t.type){case"write":return Ek(e,t.bytes);case"link":return Sk(e,t.link);case"block":return{state:e,effect:eo()};case"close":return Ak(e);case"end":return{state:e,effect:eo()};default:return Gy`File Writer got unknown message ${t}`}},im=(t,e,r)=>({status:"open",metadata:e,config:r,writer:t,chunker:Xy({chunker:r.chunker}),layout:r.fileLayout.open(),nodeQueue:tm()}),Ek=(t,e)=>{if(t.status==="open"){let{chunks:r,...n}=Yy(t.chunker,e),{nodes:o,leaves:i,layout:s}=t.config.fileLayout.write(t.layout,r),{linked:c,...a}=bu(o,t.nodeQueue),u=[...sm(i,t.config),...xu(c,t.config)];return{state:{...t,chunker:n,layout:s,nodeQueue:a},effect:os({link:is(u)})}}else return ro("Unable to perform write on closed file")},Sk=(t,{id:e,link:r,block:n})=>{let{linked:o,...i}=rm(e,r,t.nodeQueue),s=xu(o,t.config),c=t.status==="closed"&&e===t.rootID?{...t,status:"linked",link:r,nodeQueue:i}:{...t,nodeQueue:i},a=t.status==="closed"&&e===t.rootID&&t.end?t.end.resume():eo();return{state:c,effect:os({link:is(s),block:Ck(t.writer,n),end:a})}},Ak=t=>{if(t.status==="open"){let{chunks:e}=Zy(t.chunker),{layout:r,...n}=t.config.fileLayout.write(t.layout,e),{root:o,...i}=t.config.fileLayout.close(r,t.metadata),[s,c]=Ik(o)?[[...n.nodes,...i.nodes],[...n.leaves,...i.leaves,o]]:[[...n.nodes,...i.nodes,o],[...n.leaves,...i.leaves]],{linked:a,...u}=bu(s,t.nodeQueue),l=[...sm(c,t.config),...xu(a,t.config)],d=Jr(Gr());return{state:{...t,chunker:null,layout:null,rootID:o.id,status:"closed",end:d,nodeQueue:u},effect:os({link:is(l),end:hu(d)})}}else return{state:t,effect:eo()}},sm=(t,e)=>t.map(r=>_k(e,r,e.fileChunkEncoder)),_k=function*({hasher:t,linker:e},{id:r,content:n},o){let i=o.encode(n?Tk(n):Qy),s=yield*rs(t.digest(i)),c=e.createLink(o.code,s),a={cid:c,bytes:i},u={cid:c,contentByteLength:n?n.byteLength:0,dagByteLength:i.byteLength};return{id:r,block:a,link:u}},xu=(t,e)=>t.map(r=>Bk(e,r)),Bk=function*(t,{id:e,links:r},n){let o=t.fileEncoder.encode({type:P.File,layout:"advanced",parts:r,metadata:n}),i=yield*rs(Promise.resolve(t.hasher.digest(o))),s=t.linker.createLink(t.fileEncoder.code,i),c={bytes:o,cid:s},a={cid:s,contentByteLength:Xe(r),dagByteLength:qr(o,r)};return{id:e,block:c,link:a}},Ck=function*(t,e){(t.desiredSize||0)<=0&&(yield*rs(t.ready)),t.write(e)},Tk=t=>t instanceof Uint8Array?t:t.copyTo(new Uint8Array(t.byteLength),0),Ik=t=>t.children==null;var vu={};G(vu,{context:()=>Dk,cut:()=>cm,name:()=>am,type:()=>Nk,withMaxChunkSize:()=>ku});var am="fixed",Dk={maxChunkSize:262144},Nk="Stateless",ku=t=>({type:"Stateless",context:{maxChunkSize:t},name:am,cut:cm}),cm=({maxChunkSize:t},{byteLength:e},r)=>{let n=e/t|0,o=new Array(n).fill(t),i=r?e-n*t:0;return i>0&&o.push(i),o};var no=class{constructor(e,r,n){this.id=e,this.children=r,this.metadata=n}},cs=t=>({open:()=>Pk({width:t}),write:Fk,close:Mk}),Uk={width:174},Pk=({width:t}=Uk)=>({width:t,head:null,leafIndex:[],nodeIndex:[],lastID:0}),Fk=(t,e)=>{if(e.length===0)return{layout:t,nodes:de,leaves:de};{let{lastID:r}=t,[n,o]=t.head?[null,(e.unshift(t.head),e)]:e.length===1&&t.leafIndex.length===0?[e[0],de]:[null,e];if(o.length===0)return{layout:{...t,head:n},nodes:de,leaves:de};{let i=[...t.leafIndex],s=[];for(let c of o){let a={id:++r,content:c};s.push(a),i.push(a.id)}return i.length>=t.width?lm({...t,leafIndex:i,head:n,lastID:r},s):{layout:{...t,head:n,leafIndex:i,lastID:r},leaves:s,nodes:de}}}},lm=(t,e=de,r=[],n=!1)=>{let{lastID:o}=t,i=t.nodeIndex.map(u=>[...u]),s=[...t.leafIndex],{width:c}=t;for(;s.length>=c||s.length>0&&n;){um(i,1);let u=new no(++o,s.splice(0,c));i[0].push(u.id),r.push(u)}let a=0;for(;a<i.length;){let u=i[a];for(a++;u.length>=c||u.length>0&&n&&a<i.length;){let l=new no(++o,u.splice(0,c));um(i,a+1),i[a].push(l.id),r.push(l)}}return{layout:{...t,lastID:o,leafIndex:s,nodeIndex:i},leaves:e,nodes:r}},Mk=(t,e)=>{let r=t;if(t.head)return{root:{id:1,content:t.head,metadata:e},leaves:de,nodes:de};if(t.leafIndex.length===0)return{root:{id:1,metadata:e},leaves:de,nodes:de};{let{nodes:n,layout:o}=lm(r,de,[],!0),{nodeIndex:i}=o,s=i.length-1,c=i[s];if(c.length===1){let a=n[n.length-1];return n.length=n.length-1,{root:a,nodes:n,leaves:de}}else return{root:new no(o.lastID+1,c,e),nodes:n,leaves:de}}},um=(t,e)=>{for(;t.length<e;)t.push([]);return t},de=[];var At=()=>({chunker:vu,fileChunkEncoder:Eu,smallFileEncoder:Eu,fileEncoder:Wr,fileLayout:cs(174),hasher:nt,linker:{createLink:H.createV1}}),_t=t=>({...At(),...t}),Eu={code:Vr,name:Xc,encode:Zc};var oo=({writer:t,metadata:e={},settings:r=At()})=>new Su(im(t,e,_t(r))),fm=async(t,e)=>(await hm(t,ns({type:"write",bytes:e})),t),dm=async(t,{releaseLock:e=!1,closeWriter:r=!1}={})=>{await hm(t,ns({type:"close"}));let{state:n}=t;if(n.status==="linked")return r?await t.state.writer.close():e&&t.state.writer.releaseLock(),n.link;ro(`Expected writer to be in 'linked' state after close, but it is in "${n.status}" instead`)},hm=(t,e)=>Jr(Hy(e,r=>{let{state:n,effect:o}=om(r,t.state);return t.state=n,o})),Su=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.config}write(e){return fm(this,e)}close(e){return dm(this,e)}};var Ok=At,_u=({writer:t,settings:e=Ok(),metadata:r={}})=>new us({writer:t,metadata:r,settings:e,entries:new Map,closed:!1}),ls=(t,e,r,{overwrite:n=!1}={})=>{let o=Bu(t.state);if(e.includes("/"))throw new Error(`Directory entry name "${e}" contains forbidden "/" character`);if(!n&&o.entries.has(e))throw new Error(`Directory already contains entry with name "${e}"`);return o.entries.set(e,r),t},fs=(t,e)=>(Bu(t.state).entries.delete(e),t),Bu=t=>{if(t.closed)throw new Error("Can not change written directory, but you can .fork() and make changes to it");return t},pm=async(t,{closeWriter:e=!1,releaseLock:r=!1}={})=>{let{writer:n,settings:o,metadata:i}=Bu(t.state);t.state.closed=!0;let s=[...ym(t)],c=Yi(s,i),a=ts(c),u=await o.hasher.digest(a),l=o.linker.createLink(Vr,u);return(n.desiredSize||0)<=0&&await n.ready,n.write({cid:l,bytes:a}),e?await n.close():r&&n.releaseLock(),{cid:l,dagByteLength:qr(a,s)}},ym=function*({state:t}){for(let[e,{dagByteLength:r,cid:n}]of t.entries)yield{name:e,dagByteLength:r,cid:n}},mm=({state:t},{writer:e=t.writer,metadata:r=t.metadata,settings:n=t.settings}={})=>new us({writer:e,metadata:r,settings:n,entries:new Map(t.entries.entries()),closed:!1}),us=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.settings}links(){return ym(this)}set(e,r,n){return ls(this,e,r,n)}remove(e){return fs(this,e)}fork(e){return mm(this,e)}close(e){return pm(this,e)}entries(){return this.state.entries.entries()}has(e){return this.state.entries.has(e)}get size(){return this.state.entries.size}};var ps={};G(ps,{API:()=>ds,and:()=>Kk,bitCount:()=>hs,empty:()=>gm,from:()=>$k,fromBytes:()=>Jk,get:()=>Wk,or:()=>Gk,popcount:()=>Cu,set:()=>wm,size:()=>Hk,toBytes:()=>Qk,unset:()=>qk});var ds={};var gm=(t=32)=>{if(t!==32)throw new Error(`Uint32 BitField does not support size: ${t}`);return 0},$k=(t,e)=>{let r=gm(e);for(let n of t)r=wm(r,n);return r},Hk=t=>32,jk=(t,e)=>t>>>e&31,Vk=(t,e)=>1<<jk(t,e),Cu=(t,e=31)=>hs(t&Vk(e,0)-1),wm=(t,e)=>t|1<<e,qk=(t,e)=>t&(255^1<<e),Wk=(t,e)=>(t>>e&1)!==0,hs=t=>{let e=t-(t>>1&1431655765),r=(e&858993459)+(e>>2&858993459);return(r+(r>>4)&252645135)*16843009>>24},Kk=(t,e)=>t&e,Gk=(t,e)=>t|e,Qk=t=>Uint8Array.of(t>>24&255,t>>16&255,t>>8&255,t&255),Jk=t=>{if(t.length!==4)throw new Error(`Expected 4 bytes instead got ${t.length}`);return(t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3]};var km=V(Tu(),1),Xk=new TextEncoder,Yk=km.default.x64.hash126,vm=({bitWidth:t=5,hash:e=Yk})=>{if(t>4*8)throw new RangeError(`Can not use bitWidth ${t} which exceeds the hashSize 4`);if(4*8>32)throw new RangeError("Can not use hashSize 4 as it can not be encoded in Uint32");let n=4294967295>>>32-t;return{at:(s,c)=>s>>>c*t&n,from:s=>e(Xk.encode(s)),size:Math.ceil(4*8/t)}};var Yr=class{constructor(e,r,n,o,i){this.edit=e,this.config=i,this.datamap=r,this.nodemap=n,this.children=o}get nodeArity(){return this.config.BitField.popcount(this.nodemap)}get dataArity(){return this.config.BitField.popcount(this.datamap)}empty(){return so(this.config)}lookup(e,r,n,o){return Sm(this,e,r,n,o)}associate(e,r,n,o,i,s){return Du(this,e,r,n,o,i,s)}dissociate(e,r,n,o,i){return Am(this,e,r,n,o,i)}fork(e=null){return ao(this,e)}entries(){return _m(this)}keys(){return Bm(this)}values(){return Cm(this)}},ms=class{constructor(e,r,n,o){this.edit=e,this.count=r,this.children=n,this.config=o}get nodeArity(){return 0}get dataArity(){return this.count}lookup(e,r,n,o){return Zk(this,n,o)}associate(e,r,n,o,i,s){return e2(this,e,n,o,i,s)}dissociate(e,r,n,o,i){return t2(this,e,n,o,i)}fork(e=null){return r2(this,e)}entries(){return _m(this)}keys(){return Bm(this)}values(){return Cm(this)}},Zk=(t,e,r)=>{let{children:n,count:o}=t,i=Iu(n,o,e);return n[i]===e?n[i+1]:r},e2=(t,e,r,n,o,i)=>{let{children:s,count:c}=t,a=Iu(s,c,n);if(s[a]!==n){let u=t.fork(e);return i.value=!0,u.count+=1,u.children.splice(a,r,o),u}else if(s[a+1]!==o){let u=t.fork(e);return u.children[a+1]=o,u}else return t},t2=(t,e,r,n,o)=>{let{children:i,count:s,config:c}=t,a=Iu(i,s,n);if(i[a]!==n)return t;if(o.value=!0,s===2){let u=a===0?2:0;return Du(so(c),e,0,r,i[u],i[u+1],o)}else{let u=t.fork(e);return u.children.splice(a,2),u.count-=1,u}},r2=(t,e=null)=>Dm(t.edit,e)?t:new ms(e,t.count,t.children.slice(),t.config),Iu=(t,e,r)=>{let n=0;for(;n<e&&t[n]>r;)n+=2;return n};var so=(t,e=null)=>new Yr(e,t.BitField.empty(Math.pow(2,t.bitWidth)),t.BitField.empty(Math.pow(2,t.bitWidth)),[],t),ws=(t,e,r)=>Sm(t,0,t.config.Path.from(e),e,r),Sm=(t,e,r,n,o)=>{let{datamap:i,nodemap:s,config:c}=t,{Path:a,BitField:u}=c,l=a.at(r,e);if(u.get(i,l)){let d=u.popcount(i,l);return bs(t,d)===n?gs(t,d):o}else return u.get(s,l)?xs(t,l).lookup(e+1,r,n,o):o},Lu=(t,e,r,n,o)=>Du(t,e,0,t.config.Path.from(r),r,n,o),Du=(t,e,r,n,o,i,s)=>{let{datamap:c,nodemap:a,config:u}=t,{Path:l,BitField:d}=u,m=l.at(n,r);if(d.get(c,m)){let f=d.popcount(c,m),h=bs(t,f);if(o===h)return gs(t,f)===i?t:n2(t,e,f,i);{let p=Im(u,e,r+1,l.from(h),h,gs(t,f),n,o,i);return s.value=!0,i2(t,e,m,p)}}else if(d.get(a,m)){let f=xs(t,m),h=f.associate(e,r+1,n,o,i,s);return f===h?t:Tm(t,e,m,h)}else{let f=d.popcount(c,m);s.value=!0;let h=t.fork(e);return h.datamap=d.set(c,m),h.children.splice(co(f),0,o,i),h}},Nu=(t,e,r,n)=>Am(t,e,0,t.config.Path.from(r),r,n);var Am=(t,e,r,n,o,i)=>{let{datamap:s,nodemap:c,config:a}=t,{BitField:u,Path:l}=a,d=l.at(n,r);if(u.get(s,d)){let m=u.popcount(s,d);if(o===bs(t,m)){i.value=!0;let f=ao(t,e);return f.datamap=u.unset(t.datamap,d),f.children.splice(co(m),2),f}else return t}else if(u.get(c,d)){let m=xs(t,d),f=m.dissociate(e,r+1,n,o,i);return s2(f)?a2(t)?f:o2(t,e,d,f):m===f?t:Tm(t,e,d,f)}else return t},_m=function*({children:t}){let e=0,r=t.length;for(;e<r;){let n=t[e];if(typeof n=="string"){e+=1;let o=t[e];yield[n,o],e+=1}else break}for(;e<r;)yield*t[e].entries(),e+=1},ao=(t,e)=>Dm(t.edit,e)?t:new Yr(e,t.datamap,t.nodemap,t.children.slice(),t.config),Bm=function*({children:t}){let e=0,r=t.length;for(;e<r;){let n=t[e];if(typeof n=="string")yield n,e+=2;else break}for(;e<r;)yield*t[e].keys(),e+=1},Cm=function*({children:t}){let e=0,r=t.length;for(;e<r&&typeof t[e]=="string";)e+=1,yield t[e],e+=1;for(;e<r;)yield*t[e].values(),e+=1},n2=(t,e,r,n)=>{let o=t.fork(e);return o.children[Lm(r)]=n,o},o2=(t,e,r,n)=>{let{datamap:o,nodemap:i,config:s}=t,{BitField:c}=s,a=ao(t,e);return a.children.splice(ks(t,r),1),a.children.splice(co(c.popcount(o,r)),0,n.children[0],n.children[1]),a.datamap=c.set(o,r),a.nodemap=c.unset(i,r),a},Tm=(t,e,r,n)=>{let o=ao(t,e);return o.children[ks(t,r)]=n,o},i2=(t,e,r,n)=>{let{nodemap:o,datamap:i,config:s}=t,{BitField:c}=s,a=c.popcount(i,r),u=co(a),l=ks(t,r),d=ao(t,e);return d.datamap=c.unset(i,r),d.children.splice(u,2),d.nodemap=c.set(o,r),d.children.splice(l-1,0,n),d},Im=(t,e,r,n,o,i,s,c,a)=>{let{BitField:u,Path:l}=t;if(l.size<r)return new ms(e,2,[o,i,c,a],t);{let d=l.at(n,r),m=l.at(s,r);return d===m?new Yr(e,u.empty(Math.pow(2,t.bitWidth)),u.from([d],Math.pow(2,t.bitWidth)),[Im(t,e,r+1,n,o,i,s,c,a)],t):new Yr(e,u.from([d,m],Math.pow(2,t.bitWidth)),u.empty(Math.pow(2,t.bitWidth)),d<m?[o,i,c,a]:[c,a,o,i],t)}},bs=({children:t},e)=>t[co(e)],co=t=>t*2,gs=({children:t},e)=>t[Lm(e)],Lm=t=>t*2+1,xs=(t,e)=>t.children[ks(t,e)],ks=({children:t,nodemap:e,config:r},n)=>t.length-1-r.BitField.popcount(e,n),Dm=(t,e)=>t!=null&&t===e,s2=t=>t.nodeArity===0&&t.dataArity===1,a2=({config:{BitField:t},datamap:e,nodemap:r})=>t.popcount(e)===0&&t.popcount(r)===1;var vs=V(Tu(),1);function c2(t){let e=new Array(4);for(let r=0;r<4;r++)e[r]=t&255,t=t>>8;return new Uint8Array(e)}var V3=Mt({name:"murmur3-32",code:35,encode:t=>c2(vs.default.x86.hash32(t))}),Um=Mt({name:"murmur3-128",code:34,encode:t=>Nt.fromHex(vs.default.x64.hash128(t))}),uo=Mt({name:"murmur3-x64-64",code:34,encode:t=>Nt.fromHex(vs.default.x64.hash128(t)).subarray(0,8)});var u2=new TextEncoder,l2=t=>uo.encode(t),Pm=({bitWidth:t=8,hash:e=l2}={})=>{let r=e(new Uint8Array).byteLength;return{from:i=>e(u2.encode(i)),at:(i,s)=>{let c=s*t;if(c>r)throw new RangeError("Out of bounds");return Uu(i,c,t)},size:Math.ceil(r*8/t)}},Uu=(t,e,r)=>{let n=e/8|0,o=e%8,i=r,s=0;for(;i>0&&n<t.byteLength;){let c=t[n],a=8-o,u=a<i?a:i,l=8-o-u,m=(255>>o&c)>>l;s=(s<<u)+m,i-=u,n++,o=0}return s};var Pu={};G(Pu,{API:()=>ds,and:()=>k2,empty:()=>Fm,from:()=>d2,fromBytes:()=>w2,get:()=>m2,or:()=>x2,popcount:()=>b2,set:()=>p2,size:()=>h2,toBytes:()=>g2,unset:()=>y2});var Fm=(t=256)=>{if(t%8!==0)throw new Error("Must be multiple of 8");return new Uint8Array(t/8)},d2=(t,e)=>{let r=Fm(e);for(let n of t){let{byte:o,byteOffset:i,bitOffset:s}=lo(r,n);r[i]=o|1<<s}return r},h2=t=>t.byteLength*8,lo=(t,e)=>{let r=t.byteLength-1-(e/8|0),n=e%8;return{byte:t[r],byteOffset:r,bitOffset:n}},Mm=(t,e,r)=>{if(t[e]!==r){let n=t.slice(0);return n[e]=r,n}return t},p2=(t,e)=>{let{byte:r,byteOffset:n,bitOffset:o}=lo(t,e);return Mm(t,n,r|1<<o)},y2=(t,e)=>{let{byte:r,byteOffset:n,bitOffset:o}=lo(t,e);return Mm(t,n,r&(255^1<<o))},m2=(t,e)=>{var{byte:r,bitOffset:n}=lo(t,e);return(r>>n&1)!==0},g2=t=>t,w2=t=>t,b2=(t,e=t.byteLength*8)=>{let{byteOffset:r,bitOffset:n,byte:o}=lo(t,e),i=Cu(o,n),s=t.byteLength-1;for(;s>r;){let c=t[s];i+=hs(c),s--}return i},x2=(t,e)=>{let r=t.slice(),n=0;for(;n<t.length;)r[n]|=e[n],n++;return r},k2=(t,e)=>{let r=t.slice(),n=0;for(;n<t.length;)r[n]&=e[n],n++;return r};var Rm=new RangeError("Not Found");var v2=({bitWidth:t=5,BitField:e=t===5?ps:Pu,Path:r=t===5?vm({bitWidth:t}):Pm({bitWidth:t})}={})=>({bitWidth:t,BitField:e,Path:r});var Mu=(t,e)=>ws(t.root,e,Rm)!==Rm,Om=(t,e,r=void 0)=>ws(t.root,e,r),zm=t=>{let e={},r=v2(t);return new Es(e,0,so(r,e),r)},Fu=class t{constructor(e=0,r,n){this.count=e,this.root=r,this.config=n}get size(){return this.count}clone(){return new t(this.count,this.root,this.config)}empty(){return new t(0,so(this.config,null),this.config)}has(e){return Mu(this,e)}get(e){return ws(this.root,e,void 0)}set(e,r){let n={value:!1},o=Lu(this.root,null,e,r,n);return o===this.root?this:new t(n.value?this.count+1:this.count,o,this.config)}delete(e){let r=Nu(this.root,null,e,{value:!1});return r===this.root?this:new t(this.count-1,r,this.config)}get bitField(){return this.config.BitField.or(this.root.datamap,this.root.nodemap)}[Symbol.iterator](){return this.entries()}entries(){return this.root.entries()}keys(){return this.root.keys()}values(){return this.root.values()}createBuilder(){return new Es({},this.count,this.root,this.config)}},Es=class{constructor(e,r,n,o){this.edit=e,this.count=r,this.root=n,this.config=o}get size(){if(this.edit)return this.count;throw new Error(".size was accessed on the finalized builder")}set(e,r){if(this.edit){let n={value:!1},o=Lu(this.root,this.edit,e,r,n);return this.root!==o&&(this.root=o),n.value&&(this.count+=1),this}else throw new Error(".set was called on the finalized builder")}delete(e){if(this.edit){if(this.count===0)return this;let r={value:!1},n=Nu(this.root,this.edit,e,r);return n!==this.root&&(this.root=n),r.value&&(this.count-=1),this}else throw new Error(".delete was called on the finalized builder")}build(){if(this.edit)return this.edit=null,new Fu(this.count,this.root,this.config);throw new Error(".build was called on the finalized builder")}};var E2=new TextEncoder,S2=t=>uo.encode(t),Hm=({bitWidth:t=8,hash:e=S2})=>{let r=e(new Uint8Array).byteLength,n={bitWidth:t,hash:e,hashSize:r};return{at:(s,c)=>A2(s,c,n),from:s=>E2.encode(s),size:1/0}},A2=(t,e=0,{bitWidth:r=8,hash:n,hashSize:o})=>{let i=o*8,s=0,c=r,a=r*e;for(;c>0;){let u=a/i>>0,l=n(u===0?t:_2(t,u)),d=i<=a?a%i:a,m=i-d,f=m<c?m:c;s=(s<<f)+Uu(l,d,f),c-=f,a+=f}return s},_2=(t,e)=>{let r=new Uint8Array(t.byteLength+1).fill(e,t.byteLength);return r.set(t),r};var jm=8,C2={bitWidth:jm,Path:Hm({bitWidth:jm})};var Ru=(t=C2)=>zm(t);var Vm=class extends Map{constructor(e=Ru()){super(),this.builder=e}clear(){this.builder=Ru()}delete(e){let{root:r}=this.builder;return this.builder.delete(e),this.builder.root!==r}forEach(e,r=this){for(let[n,o]of this.builder.root.entries())e.call(r,o,n,this)}get(e){return Om(this.builder,e)}has(e){return Mu(this.builder,e)}set(e,r){return this.builder.set(e,r),this}get size(){return this.builder.size}[Symbol.iterator](){return this.builder.root.entries()}entries(){return this.builder.root.entries()}keys(){return this.builder.root.keys()}values(){return this.builder.root.values()}};var qm=({writable:t,settings:e=At()})=>new Ou({writer:t.getWriter(),settings:e}),I2=async(t,{releaseLock:e=!0,closeWriter:r=!0}={})=>(r?await t.writer.close():e&&t.writer.releaseLock(),t),Ou=class{constructor({writer:e,settings:r}){this.writer=e,this.settings=_t(r)}createFileWriter({settings:e=this.settings,metadata:r}={}){return oo({writer:this.writer,settings:e,metadata:r})}createDirectoryWriter({settings:e=this.settings,metadata:r}={}){return _u({writer:this.writer,settings:e,metadata:r})}close(e){return I2(this,e)}},L2=1048576,D2=L2*100,Wm=(t=D2)=>({highWaterMark:t,size:e=>e.bytes.length});var $s=V(Ye(),1);function P2(t){return t[Symbol.asyncIterator]!=null}function F2(t){if(P2(t))return(async()=>{let r;for await(let n of t)r=n;return r})();let e;for(let r of t)e=r;return e}var Qm=F2;var Xg=V(Ye(),1);var Jm=0,M2="identity",Xm=ie,R2=t=>Ut(Jm,Xm(t)),Ym={code:Jm,name:M2,encode:Xm,digest:R2};var Zm=V(Ye(),1);var O2=async(t,e,r,n,o,i,s,c)=>{let a=await s.get(t,c),u=xr(a),l=u,d=r;for(;n.length>0;){let m=n[0];if(m in l){n.shift(),d=`${d}/${m}`;let f=j.asCID(l[m]);if(f!=null)return{entry:{type:"object",name:e,path:r,cid:t,node:a,depth:i,size:BigInt(a.length),content:async function*(){yield u}},next:{cid:f,name:m,path:d,toResolve:n}};l=l[m]}else throw(0,Zm.default)(new Error(`No property named ${m} found in cbor node ${t}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:r,cid:t,node:a,depth:i,size:BigInt(a.length),content:async function*(){yield u}}}},eg=O2;var tg=V(Ye(),1);var ae=class extends Event{constructor(e,r){super(e),this.detail=r}};function z2(t,e,r,n){let o=BigInt(t.length),i=BigInt(e+o);return r>=i||n<e?new Uint8Array(0):(n>=e&&n<i&&(t=t.subarray(0,Number(n-e))),r>=e&&r<i&&(t=t.subarray(Number(r-e))),t)}var er=z2;var fo=V(Ye(),1),$2=(t,e=0,r=t)=>{let n=BigInt(t),o=BigInt(e??0),i=BigInt(r);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw(0,fo.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(o>n)throw(0,fo.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(i<0n)throw(0,fo.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,fo.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:o,end:i}},Zr=$2;var H2=t=>{async function*e(r={}){let{start:n,end:o}=Zr(t.length,r.offset,r.length),i=er(t,0n,n,o);r.onProgress?.(new ae("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(t.byteLength)})),yield i}return e},j2=async(t,e,r,n,o,i,s,c)=>{if(n.length>0)throw(0,tg.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let a=Wo(t.multihash.bytes);return{entry:{type:"identity",name:e,path:r,cid:t,content:H2(a.digest),depth:i,size:BigInt(a.digest.length),node:a.digest}}},rg=j2;var ng=V(Ye(),1);var V2=t=>{async function*e(r={}){let{start:n,end:o}=Zr(t.length,r.offset,r.length),i=er(t,0n,n,o);r.onProgress?.(new ae("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(t.byteLength)})),yield i}return e},q2=async(t,e,r,n,o,i,s,c)=>{if(n.length>0)throw(0,ng.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let a=await s.get(t,c);return{entry:{type:"raw",name:e,path:r,cid:t,content:V2(a),depth:i,size:BigInt(a.length),node:a}}},og=q2;var Ao=V(Ye(),1);var qu=V(Ye(),1);var zu=V(Gi(),1),ig=V(Kc(),1),sg=V(ot(),1),$u=V(Wi(),1),ag=V(Vc(),1);function W2(){sg.default._configure(),zu.default._configure(ig.default),$u.default._configure(ag.default)}W2();var cg=["uint64","int64","sint64","fixed64","sfixed64"];function K2(t){for(let e of cg){if(t[e]==null)continue;let r=t[e];t[e]=function(){return BigInt(r.call(this).toString())}}return t}function Hu(t){return K2(new zu.default(t))}function G2(t){for(let e of cg){if(t[e]==null)continue;let r=t[e];t[e]=function(n){return r.call(this,n.toString())}}return t}function ju(){return G2($u.default.create())}function ho(t,e){let r=Hu(t instanceof Uint8Array?t:t.subarray());return e.decode(r)}function po(t,e){let r=ju();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var en;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(en||(en={}));function Ss(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function Vu(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}let r=function(i,s){let c=e(i);s.int32(c)},n=function(i){let s=i.int32();return e(s)};return Ss("enum",en.VARINT,r,n)}function yo(t,e){return Ss("message",en.LENGTH_DELIMITED,t,e)}var Re;(function(t){let e;(function(o){o.Raw="Raw",o.Directory="Directory",o.File="File",o.Metadata="Metadata",o.Symlink="Symlink",o.HAMTShard="HAMTShard"})(e=t.DataType||(t.DataType={}));let r;(function(o){o[o.Raw=0]="Raw",o[o.Directory=1]="Directory",o[o.File=2]="File",o[o.Metadata=3]="Metadata",o[o.Symlink=4]="Symlink",o[o.HAMTShard=5]="HAMTShard"})(r||(r={})),function(o){o.codec=()=>Vu(r)}(e=t.DataType||(t.DataType={}));let n;t.codec=()=>(n==null&&(n=yo((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),t.DataType.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),o.filesize!=null&&(i.uint32(24),i.uint64(o.filesize)),o.blocksizes!=null)for(let c of o.blocksizes)i.uint32(32),i.uint64(c);o.hashType!=null&&(i.uint32(40),i.uint64(o.hashType)),o.fanout!=null&&(i.uint32(48),i.uint64(o.fanout)),o.mode!=null&&(i.uint32(56),i.uint32(o.mode)),o.mtime!=null&&(i.uint32(66),As.codec().encode(o.mtime,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let s={blocksizes:[]},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let a=o.uint32();switch(a>>>3){case 1:s.Type=t.DataType.codec().decode(o);break;case 2:s.Data=o.bytes();break;case 3:s.filesize=o.uint64();break;case 4:s.blocksizes.push(o.uint64());break;case 5:s.hashType=o.uint64();break;case 6:s.fanout=o.uint64();break;case 7:s.mode=o.uint32();break;case 8:s.mtime=As.codec().decode(o,o.uint32());break;default:o.skipType(a&7);break}}return s})),n),t.encode=o=>po(o,t.codec()),t.decode=o=>ho(o,t.codec())})(Re||(Re={}));var As;(function(t){let e;t.codec=()=>(e==null&&(e=yo((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Seconds!=null&&(n.uint32(8),n.int64(r.Seconds)),r.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(r.FractionalNanoseconds)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let o={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let s=r.uint32();switch(s>>>3){case 1:o.Seconds=r.int64();break;case 2:o.FractionalNanoseconds=r.fixed32();break;default:r.skipType(s&7);break}}return o})),e),t.encode=r=>po(r,t.codec()),t.decode=r=>ho(r,t.codec())})(As||(As={}));var ug;(function(t){let e;t.codec=()=>(e==null&&(e=yo((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.MimeType!=null&&(n.uint32(10),n.string(r.MimeType)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let o={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let s=r.uint32();switch(s>>>3){case 1:o.MimeType=r.string();break;default:r.skipType(s&7);break}}return o})),e),t.encode=r=>po(r,t.codec()),t.decode=r=>ho(r,t.codec())})(ug||(ug={}));var lg={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},Q2=["directory","hamt-sharded-directory"],fg=parseInt("0644",8),dg=parseInt("0755",8),tn=class t{static unmarshal(e){let r=Re.decode(e),n=new t({type:lg[r.Type!=null?r.Type.toString():"File"],data:r.Data,blockSizes:r.blocksizes,mode:r.mode,mtime:r.mtime!=null?{secs:r.mtime.Seconds??0n,nsecs:r.mtime.FractionalNanoseconds}:void 0});return n._originalMode=r.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:r,data:n,blockSizes:o,hashType:i,fanout:s,mtime:c,mode:a}=e;if(r!=null&&!Object.values(lg).includes(r))throw(0,qu.default)(new Error("Type: "+r+" is not valid"),"ERR_INVALID_TYPE");this.type=r??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=a,this.mtime=c}set mode(e){e==null?this._mode=this.isDirectory()?dg:fg:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return Q2.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(r=>{e+=r}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=Re.DataType.Raw;break;case"directory":e=Re.DataType.Directory;break;case"file":e=Re.DataType.File;break;case"metadata":e=Re.DataType.Metadata;break;case"symlink":e=Re.DataType.Symlink;break;case"hamt-sharded-directory":e=Re.DataType.HAMTShard;break;default:throw(0,qu.default)(new Error(`Type: ${e} is not valid`),"ERR_INVALID_TYPE")}let r=this.data;(this.data==null||this.data.length===0)&&(r=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===fg&&!this.isDirectory()&&(n=void 0),n===dg&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Re.encode({Type:e,Data:r,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var Eg=V(yg(),1);var Wu={};G(Wu,{identity:()=>Z2});var Z2=lr({prefix:"\0",name:"identity",encode:t=>_l(t),decode:t=>Al(t)});var Ku={};G(Ku,{base2:()=>ev});var ev=K({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Gu={};G(Gu,{base8:()=>tv});var tv=K({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qu={};G(Qu,{base10:()=>rv});var rv=ut({prefix:"9",name:"base10",alphabet:"0123456789"});var Ju={};G(Ju,{base16:()=>nv,base16upper:()=>ov});var nv=K({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ov=K({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Xu={};G(Xu,{base36:()=>iv,base36upper:()=>sv});var iv=ut({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),sv=ut({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Yu={};G(Yu,{base64:()=>av,base64pad:()=>cv,base64url:()=>uv,base64urlpad:()=>lv});var av=K({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cv=K({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),uv=K({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lv=K({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Zu={};G(Zu,{base256emoji:()=>yv});var mg=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),fv=mg.reduce((t,e,r)=>(t[r]=e,t),[]),dv=mg.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function hv(t){return t.reduce((e,r)=>(e+=fv[r],e),"")}function pv(t){let e=[];for(let r of t){let n=dv[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var yv=lr({prefix:"\u{1F680}",name:"base256emoji",encode:hv,decode:pv});var el={};G(el,{identity:()=>wv});var gg=0,mv="identity",wg=Se,gv=t=>Tt(gg,wg(t)),wv={code:gg,name:mv,encode:wg,digest:gv};var bT=new TextEncoder,xT=new TextDecoder;var tl={...Wu,...Ku,...Gu,...Qu,...Ju,...Zs,...Xu,...Ys,...Yu,...Zu},vT={...Bc,...el};function rn(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function _s(t=0){return globalThis.Buffer?.allocUnsafe!=null?rn(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function xg(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var bg=xg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),rl=xg("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=_s(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),kv={utf8:bg,"utf-8":bg,hex:tl.base16,latin1:rl,ascii:rl,binary:rl,...tl},kg=kv;function vg(t,e="utf8"){let r=kg[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?rn(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var tr=class t{constructor(e,r,n=0){this._options=e,this._popCount=0,this._parent=r,this._posAtParent=n,this._children=new Eg.default,this.key=null}async put(e,r){let n=await this._findNewBucketAndPos(e);await n.bucket._putAt(n,e,r)}async get(e){let r=await this._findChild(e);if(r!=null)return r.value}async del(e){let r=await this._findPlace(e),n=r.bucket._at(r.pos);n!=null&&n.key===e&&r.bucket._delAt(r.pos)}leafCount(){return this._children.compactArray().reduce((r,n)=>n instanceof t?r+n.leafCount():r+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let r of e)r instanceof t?yield*r.eachLeafSeries():yield r}serialize(e,r){let n=[];return r(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof t?o.push(i.serialize(e,r)):o.push(e(i,s))),o),n))}async asyncTransform(e,r){return await Sg(this,e,r)}toJSON(){return this.serialize(Ev,Sv)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let r=await this._findPlace(e),n=r.bucket._at(r.pos);if(!(n instanceof t)&&n!=null&&n.key===e)return n}async _findPlace(e){let r=this._options.hash(typeof e=="string"?vg(e):e),n=await r.take(this._options.bits),o=this._children.get(n);return o instanceof t?await o._findPlace(r):{bucket:this,pos:n,hash:r,existingChild:o}}async _findNewBucketAndPos(e){let r=await this._findPlace(e);if(r.existingChild!=null&&r.existingChild.key!==e){let n=new t(this._options,r.bucket,r.pos);r.bucket._putObjectAt(r.pos,n);let o=await n._findPlace(r.existingChild.hash);return o.bucket._putAt(o,r.existingChild.key,r.existingChild.value),await n._findNewBucketAndPos(r.hash)}return r}_putAt(e,r,n){this._putObjectAt(e.pos,{key:r,value:n,hash:e.hash})}_putObjectAt(e,r){this._children.get(e)==null&&this._popCount++,this._children.set(e,r)}_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(vv);if(e!=null&&!(e instanceof t)){let r=e.hash;r.untake(this._options.bits);let n={pos:this._posAtParent,hash:r,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 vv(t){return!!t}function Ev(t,e){return t.key}function Sv(t){return t}async function Sg(t,e,r){let n=[];for(let o of t._children.compactArray())if(o instanceof tr)await Sg(o,e,r);else{let i=await e(o);n.push({bitField:t._children.bitField(),children:i})}return await r(n)}var Av=[255,254,252,248,240,224,192,128],_v=[1,3,7,15,31,63,127,255],Bs=class{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 r=e,n=0;for(;r>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,r),c=Bv(o,i-s,s);n=(n<<s)+c,r-=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 Bv(t,e,r){let n=Cv(e,r);return(t&n)>>>e}function Cv(t,e){return Av[t]&_v[Math.min(e+t-1,7)]}function Ag(t,e){e==null&&(e=t.reduce((o,i)=>o+i.length,0));let r=_s(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return rn(r)}function _g(t){function e(r){return r instanceof Cs?r:new Cs(r,t)}return e}var Cs=class{constructor(e,r){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=r,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let r=e;for(;this._availableBits<r;)await this._produceMoreBits();let n=0;for(;r>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),r),s=o.take(i);n=(n<<i)+s,r-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let r=e;for(;r>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),r);n.untake(o),r-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?Ag([this._value,Uint8Array.from([this._depth])]):this._value,r=await this._hashFn(e),n=new Bs(r);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Bg(t){if(t==null||t.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:t.bits??8,hash:_g(t.hashFn)};return new tr(e)}var Tv=async function(t){return(await Um.encode(t)).slice(0,8).reverse()},Iv=async(t,e,r)=>{await Promise.all(t.map(async n=>{if(n.Name==null)throw new Error("Unexpected Link without a Name");if(n.Name.length===2){let o=parseInt(n.Name,16);e._putObjectAt(o,new tr({hash:r._options.hash,bits:r._options.bits},e,o));return}await r.put(n.Name.substring(2),!0)}))},Cg=t=>t.toString(16).toUpperCase().padStart(2,"0").substring(0,2),Lv=t=>{let e=t.bucket,r=[];for(;e._parent!=null;)r.push(e),e=e._parent;return r.push(e),r.reverse()},Tg=async(t,e,r,n,o)=>{if(n==null){let l=Bg({hashFn:Tv});n={rootBucket:l,hamtDepth:1,lastBucket:l}}await Iv(t.Links,n.lastBucket,n.rootBucket);let i=await n.rootBucket._findNewBucketAndPos(e),s=Cg(i.pos),c=Lv(i);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],s=Cg(n.lastBucket._posAtParent));let a=t.Links.find(l=>{if(l.Name==null)return!1;let d=l.Name.substring(0,2),m=l.Name.substring(2);return!(d!==s||m!==""&&m!==e)});if(a==null)return;if(a.Name!=null&&a.Name.substring(2)===e)return a.Hash;n.hamtDepth++;let u=await r.get(a.Hash,o);return t=Ge(u),Tg(t,e,r,n,o)},Ig=Tg;function Dv(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[r](){return this}}}var Ts=Dv;function Nv(t){return t[Symbol.asyncIterator]!=null}function Uv(t,e){if(Nv(t))return async function*(){for await(let c of t)await e(c)&&(yield c)}();let r=Ts(t),{value:n,done:o}=r.next();if(o===!0)return function*(){}();let i=e(n);if(typeof i.then=="function")return async function*(){await i&&(yield n);for await(let c of r)await e(c)&&(yield c)}();let s=e;return function*(){i===!0&&(yield n);for(let c of r)s(c)&&(yield c)}()}var Lg=Uv;function Pv(t){return t[Symbol.asyncIterator]!=null}function Fv(t,e){if(Pv(t))return async function*(){for await(let c of t)yield e(c)}();let r=Ts(t),{value:n,done:o}=r.next();if(o===!0)return function*(){}();let i=e(n);if(typeof i.then=="function")return async function*(){yield await i;for await(let c of r)yield e(c)}();let s=e;return function*(){yield i;for(let c of r)yield s(c)}()}var nn=Fv;function at(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var Is=globalThis.CustomEvent??Event;async function*rr(t,e={}){let r=e.concurrency??1/0;r<1&&(r=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,i=[],s=at(),c=at(),a=!1,u,l=!1;o.addEventListener("task-complete",()=>{c.resolve()}),Promise.resolve().then(async()=>{try{for await(let h of t){if(i.length===r&&(s=at(),await s.promise),l)break;let p={done:!1};i.push(p),h().then(w=>{p.done=!0,p.ok=!0,p.value=w,o.dispatchEvent(new Is("task-complete"))},w=>{p.done=!0,p.err=w,o.dispatchEvent(new Is("task-complete"))})}a=!0,o.dispatchEvent(new Is("task-complete"))}catch(h){u=h,o.dispatchEvent(new Is("task-complete"))}});function d(){return n?i[0]?.done:!!i.find(h=>h.done)}function*m(){for(;i.length>0&&i[0].done;){let h=i[0];if(i.shift(),h.ok)yield h.value;else throw l=!0,s.resolve(),h.err;s.resolve()}}function*f(){for(;d();)for(let h=0;h<i.length;h++)if(i[h].done){let p=i[h];if(i.splice(h,1),h--,p.ok)yield p.value;else throw l=!0,s.resolve(),p.err;s.resolve()}}for(;;){if(d()||(c=at(),await c.promise),u!=null)throw u;if(n?yield*m():yield*f(),a&&i.length===0)break}}var Ls=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},on=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ls(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Ls(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var nl=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function sn(t={}){return Mv(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Mv(t,e){e=e??{};let r=e.onEnd,n=new on,o,i,s,c=at(),a=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((w,g)=>{i=b=>{i=null,n.push(b);try{w(t(n))}catch(k){g(k)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=at()})}},u=w=>i!=null?i(w):(n.push(w),o),l=w=>(n=new on,i!=null?i({error:w}):(n.push({error:w}),o)),d=w=>{if(s)return o;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:w})},m=w=>s?o:(s=!0,w!=null?l(w):u({done:!0})),f=()=>(n=new on,m(),{done:!0}),h=w=>(m(w),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:a,return:f,throw:h,push:d,end:m,get readableLength(){return n.size},onEmpty:async w=>{let g=w?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let b,k;g!=null&&(b=new Promise((v,C)=>{k=()=>{C(new nl)},g.addEventListener("abort",k)}));try{await Promise.race([c.promise,b])}finally{k!=null&&g!=null&&g?.removeEventListener("abort",k)}}},r==null)return o;let p=o;return o={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(w){return p.throw(w),r!=null&&(r(w),r=void 0),{done:!0}},return(){return p.return(),r!=null&&(r(),r=void 0),{done:!0}},push:d,end(w){return p.end(w),r!=null&&(r(w),r=void 0),o},get readableLength(){return p.readableLength}},o}function Rv(t){return t[Symbol.asyncIterator]!=null}function Ov(...t){let e=[];for(let r of t)Rv(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=sn({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let o of n)r.push(o)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var Dg=Ov;function an(t,...e){if(t==null)throw new Error("Empty pipeline");if(ol(t)){let n=t;t=()=>n.source}else if(Ug(t)||Ng(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&ol(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)ol(r[n])&&(r[n]=$v(r[n]));return zv(...r)}var zv=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Ng=t=>t?.[Symbol.asyncIterator]!=null,Ug=t=>t?.[Symbol.iterator]!=null,ol=t=>t==null?!1:t.sink!=null&&t.source!=null,$v=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=sn({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let o,i=t.source;if(Ng(i))o=async function*(){yield*i,n.end()};else if(Ug(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Dg(n,o())}return t.source};var Hv=(t,e,r,n,o,i,s)=>{async function*c(a={}){let u=a.offset??0,l=a.length??e.Links.length,d=e.Links.slice(u,l);a.onProgress?.(new ae("unixfs:exporter:walk:directory",{cid:t})),yield*an(d,m=>nn(m,f=>async()=>{let h=f.Name??"",p=`${n}/${h}`;return(await o(f.Hash,h,p,[],i+1,s,a)).entry}),m=>rr(m,{ordered:!0}),m=>Lg(m,f=>f!=null))}return c},Pg=Hv;var or=V(Ye(),1);var Wg=V(Mg(),1);var go=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},sl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Rg=t=>globalThis.DOMException===void 0?new sl(t):new DOMException(t),Og=t=>{let e=t.reason===void 0?Rg("This operation was aborted."):t.reason;return e instanceof Error?e:Rg(e)};function al(t,e,r,n){let o,i=new Promise((s,c)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){s(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:a}=n;a.aborted&&c(Og(a)),a.addEventListener("abort",()=>{c(Og(a))})}o=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{s(r())}catch(l){c(l)}return}let a=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new go(a);typeof t.cancel=="function"&&t.cancel(),c(u)},e),(async()=>{try{s(await t)}catch(a){c(a)}finally{n.customTimers.clearTimeout.call(void 0,o)}})()});return i.clear=()=>{clearTimeout(o),o=void 0},i}function cl(t,e,r){let n=0,o=t.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;r(t[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var nr=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},ct,wo=class{constructor(){ct.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&nr(this,ct,"f")[this.size-1].priority>=r.priority){nr(this,ct,"f").push(n);return}let o=cl(nr(this,ct,"f"),n,(i,s)=>s.priority-i.priority);nr(this,ct,"f").splice(o,0,n)}dequeue(){let e=nr(this,ct,"f").shift();return e?.run}filter(e){return nr(this,ct,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return nr(this,ct,"f").length}};ct=new WeakMap;var W=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},I=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},X,xo,ko,Ct,Rs,vo,Ns,Oe,bo,ve,Us,Ee,Eo,Bt,Ps,zg,$g,Vg,Hg,jg,Fs,ul,ll,Os,qg,Ms,zs=class extends Error{},So=class extends Wg.default{constructor(e){var r,n,o,i;if(super(),X.add(this),xo.set(this,void 0),ko.set(this,void 0),Ct.set(this,0),Rs.set(this,void 0),vo.set(this,void 0),Ns.set(this,0),Oe.set(this,void 0),bo.set(this,void 0),ve.set(this,void 0),Us.set(this,void 0),Ee.set(this,0),Eo.set(this,void 0),Bt.set(this,void 0),Ps.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:wo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(i=(o=e.interval)===null||o===void 0?void 0:o.toString())!==null&&i!==void 0?i:""}\` (${typeof e.interval})`);W(this,xo,e.carryoverConcurrencyCount,"f"),W(this,ko,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),W(this,Rs,e.intervalCap,"f"),W(this,vo,e.interval,"f"),W(this,ve,new e.queueClass,"f"),W(this,Us,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,W(this,Ps,e.throwOnTimeout===!0,"f"),W(this,Bt,e.autoStart===!1,"f")}get concurrency(){return I(this,Eo,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);W(this,Eo,e,"f"),I(this,X,"m",Os).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:I(this,Ps,"f"),...r},new Promise((n,o)=>{I(this,ve,"f").enqueue(async()=>{var i,s,c;W(this,Ee,(s=I(this,Ee,"f"),s++,s),"f"),W(this,Ct,(c=I(this,Ct,"f"),c++,c),"f");try{if(!((i=r.signal)===null||i===void 0)&&i.aborted)throw new zs("The task was aborted.");let a=e({signal:r.signal});r.timeout&&(a=al(Promise.resolve(a),r.timeout)),r.signal&&(a=Promise.race([a,I(this,X,"m",qg).call(this,r.signal)]));let u=await a;n(u),this.emit("completed",u)}catch(a){if(a instanceof go&&!r.throwOnTimeout){n();return}o(a),this.emit("error",a)}finally{I(this,X,"m",Vg).call(this)}},r),this.emit("add"),I(this,X,"m",Fs).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return I(this,Bt,"f")?(W(this,Bt,!1,"f"),I(this,X,"m",Os).call(this),this):this}pause(){W(this,Bt,!0,"f")}clear(){W(this,ve,new(I(this,Us,"f")),"f")}async onEmpty(){I(this,ve,"f").size!==0&&await I(this,X,"m",Ms).call(this,"empty")}async onSizeLessThan(e){I(this,ve,"f").size<e||await I(this,X,"m",Ms).call(this,"next",()=>I(this,ve,"f").size<e)}async onIdle(){I(this,Ee,"f")===0&&I(this,ve,"f").size===0||await I(this,X,"m",Ms).call(this,"idle")}get size(){return I(this,ve,"f").size}sizeBy(e){return I(this,ve,"f").filter(e).length}get pending(){return I(this,Ee,"f")}get isPaused(){return I(this,Bt,"f")}};xo=new WeakMap,ko=new WeakMap,Ct=new WeakMap,Rs=new WeakMap,vo=new WeakMap,Ns=new WeakMap,Oe=new WeakMap,bo=new WeakMap,ve=new WeakMap,Us=new WeakMap,Ee=new WeakMap,Eo=new WeakMap,Bt=new WeakMap,Ps=new WeakMap,X=new WeakSet,zg=function(){return I(this,ko,"f")||I(this,Ct,"f")<I(this,Rs,"f")},$g=function(){return I(this,Ee,"f")<I(this,Eo,"f")},Vg=function(){var e;W(this,Ee,(e=I(this,Ee,"f"),e--,e),"f"),I(this,X,"m",Fs).call(this),this.emit("next")},Hg=function(){I(this,X,"m",ll).call(this),I(this,X,"m",ul).call(this),W(this,bo,void 0,"f")},jg=function(){let e=Date.now();if(I(this,Oe,"f")===void 0){let r=I(this,Ns,"f")-e;if(r<0)W(this,Ct,I(this,xo,"f")?I(this,Ee,"f"):0,"f");else return I(this,bo,"f")===void 0&&W(this,bo,setTimeout(()=>{I(this,X,"m",Hg).call(this)},r),"f"),!0}return!1},Fs=function(){if(I(this,ve,"f").size===0)return I(this,Oe,"f")&&clearInterval(I(this,Oe,"f")),W(this,Oe,void 0,"f"),this.emit("empty"),I(this,Ee,"f")===0&&this.emit("idle"),!1;if(!I(this,Bt,"f")){let e=!I(this,X,"a",jg);if(I(this,X,"a",zg)&&I(this,X,"a",$g)){let r=I(this,ve,"f").dequeue();return r?(this.emit("active"),r(),e&&I(this,X,"m",ul).call(this),!0):!1}}return!1},ul=function(){I(this,ko,"f")||I(this,Oe,"f")!==void 0||(W(this,Oe,setInterval(()=>{I(this,X,"m",ll).call(this)},I(this,vo,"f")),"f"),W(this,Ns,Date.now()+I(this,vo,"f"),"f"))},ll=function(){I(this,Ct,"f")===0&&I(this,Ee,"f")===0&&I(this,Oe,"f")&&(clearInterval(I(this,Oe,"f")),W(this,Oe,void 0,"f")),W(this,Ct,I(this,xo,"f")?I(this,Ee,"f"):0,"f"),I(this,X,"m",Os).call(this)},Os=function(){for(;I(this,X,"m",Fs).call(this););},qg=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new zs("The task was aborted."))},{once:!0})})},Ms=async function(e,r){return new Promise(n=>{let o=()=>{r&&!r()||(this.off(e,o),n())};this.on(e,o)})};async function Kg(t,e,r,n,o,i,s){if(e instanceof Uint8Array){let u=er(e,n,o,i);r.push(u);return}if(e.Data==null)throw(0,or.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let c;try{c=tn.unmarshal(e.Data)}catch(u){throw(0,or.default)(u,"ERR_NOT_UNIXFS")}if(c.data!=null){let u=c.data,l=er(u,n,o,i);r.push(l),n+=BigInt(l.byteLength)}let a=[];if(e.Links.length!==c.blockSizes.length)throw(0,or.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let u=0;u<e.Links.length;u++){let l=e.Links[u],d=n,m=d+c.blockSizes[u];if((o>=d&&o<m||i>=d&&i<=m||o<d&&i>m)&&a.push({link:l,blockStart:n}),n=m,n>i)break}await an(a,u=>nn(u,l=>async()=>{let d=await t.get(l.link.Hash,s);return{...l,block:d}}),u=>rr(u,{ordered:!0}),async u=>{for await(let{link:l,block:d,blockStart:m}of u){let f;switch(l.Hash.code){case Jt:f=Ge(d);break;case Un:f=d;break;default:r.end((0,or.default)(new Error(`Unsupported codec: ${l.Hash.code}`),"ERR_NOT_UNIXFS"));return}let h=new So({concurrency:1});h.on("error",p=>{r.end(p)}),h.add(async()=>{s.onProgress?.(new ae("unixfs:exporter:walk:file",{cid:l.Hash})),await Kg(t,f,r,m,o,i,s)}),await h.onIdle()}}),n>=i&&r.end()}var qv=(t,e,r,n,o,i,s)=>{async function*c(a={}){let u=r.fileSize();if(u===void 0)throw new Error("File was a directory");let{start:l,end:d}=Zr(u,a.offset,a.length);if(d===0n)return;let m=0n,f=d-l,h=sn();a.onProgress?.(new ae("unixfs:exporter:walk:file",{cid:t})),Kg(s,e,h,0n,l,d,a).catch(p=>{h.end(p)});for await(let p of h)if(p!=null){if(m+=BigInt(p.byteLength),m>f)throw h.end(),(0,or.default)(new Error("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect"),"ERR_OVER_READ");m===f&&h.end(),a.onProgress?.(new ae("unixfs:exporter:progress:unixfs:file",{bytesRead:m,totalBytes:f,fileSize:u})),yield p}if(m<f)throw(0,or.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return c},fl=qv;var Wv=(t,e,r,n,o,i,s)=>{function c(a={}){return a.onProgress?.(new ae("unixfs:exporter:walk:hamt-sharded-directory",{cid:t})),Gg(e,n,o,i,s,a)}return c};async function*Gg(t,e,r,n,o,i){let s=t.Links,c=an(s,a=>nn(a,u=>async()=>{let l=u.Name!=null?u.Name.substring(2):null;if(l!=null&&l!==""){let d=await r(u.Hash,l,`${e}/${l}`,[],n+1,o,i);return{entries:d.entry==null?[]:[d.entry]}}else{let d=await o.get(u.Hash,i);return t=Ge(d),i.onProgress?.(new ae("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:Gg(t,e,r,n,o,i)}}}),a=>rr(a,{ordered:!0}));for await(let{entries:a}of c)yield*a}var Qg=Wv;var Kv=(t,e)=>t.Links.find(n=>n.Name===e)?.Hash,Gv={raw:fl,file:fl,directory:Pg,"hamt-sharded-directory":Qg,metadata:(t,e,r,n,o,i,s)=>()=>[],symlink:(t,e,r,n,o,i,s)=>()=>[]},Qv=async(t,e,r,n,o,i,s,c)=>{let a=await s.get(t,c),u=Ge(a),l,d;if(e==null&&(e=t.toString()),u.Data==null)throw(0,Ao.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{l=tn.unmarshal(u.Data)}catch(f){throw(0,Ao.default)(f,"ERR_NOT_UNIXFS")}if(r==null&&(r=e),n.length>0){let f;if(l?.type==="hamt-sharded-directory"?f=await Ig(u,n[0],s):f=Kv(u,n[0]),f==null)throw(0,Ao.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let h=n.shift(),p=`${r}/${h}`;d={cid:f,toResolve:n,name:h??"",path:p}}let m=Gv[l.type](t,u,l,r,o,i,s);if(m==null)throw(0,Ao.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return l.isDirectory()?{entry:{type:"directory",name:e,path:r,cid:t,content:m,unixfs:l,depth:i,node:u,size:l.fileSize()},next:d}:{entry:{type:"file",name:e,path:r,cid:t,content:m,unixfs:l,depth:i,node:u,size:l.fileSize()},next:d}},Jg=Qv;var Jv={[Jt]:Jg,[Un]:og,[ka]:eg,[Ym.code]:rg},Yg=async(t,e,r,n,o,i,s)=>{let c=Jv[t.code];if(c==null)throw(0,Xg.default)(new Error(`No resolver for code ${t.code}`),"ERR_NO_RESOLVER");return c(t,e,r,n,Yg,o,i,s)},Zg=Yg;var Xv=(t="")=>(t.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),Yv=t=>{if(t instanceof Uint8Array)return{cid:j.decode(t),toResolve:[]};let e=j.asCID(t);if(e!=null)return{cid:e,toResolve:[]};if(typeof t=="string"){t.indexOf("/ipfs/")===0&&(t=t.substring(6));let r=Xv(t);return{cid:j.parse(r[0]),toResolve:r.slice(1)}}throw(0,$s.default)(new Error(`Unknown path type ${t}`),"ERR_BAD_PATH")};async function*Zv(t,e,r={}){let{cid:n,toResolve:o}=Yv(t),i=n.toString(),s=i,c=o.length;for(;;){let a=await Zg(n,i,s,o,c,e,r);if(a.entry==null&&a.next==null)throw(0,$s.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");if(a.entry!=null&&(yield a.entry),a.next==null)return;o=a.next.toResolve,n=a.next.cid,i=a.next.name,s=a.next.path}}async function ew(t,e,r={}){let n=await Qm(Zv(t,e,r));if(n==null)throw(0,$s.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");return n}var eE=Wm(),tE=_t({fileChunkEncoder:gt,smallFileEncoder:gt,chunker:ku(1024*1024),fileLayout:cs(1024)});async function tw(t){let e=rE(t),r=await nE(e);return{cid:r.at(-1).cid,blocks:r}}async function rw(t,e,r){let n=await ew(e.toString(),t,{length:r.size}),o=[];for await(let i of n.content())o.push(i);return new File(o,n.name,{type:r.type,lastModified:0})}function rE(t){let{readable:e,writable:r}=new TransformStream({},eE),n=qm({writable:r,settings:tE}),o=new dl("",t);return(async()=>(await o.finalize(n),await n.close()))(),e}async function nE(t){let e=[];return await t.pipeTo(new WritableStream({write(r){e.push(r)}})),e}var dl=class{#e;name;constructor(e,r){this.name=e,this.#e=r}async finalize(e){let r=oo(e);return await this.#e.stream().pipeTo(new WritableStream({async write(n){await r.write(n)}})),await r.close()}};async function iw(t,e,r,n){let o;for(let i of r){let s=await oE(t,i);o=await yp(t,e,i.key,s,n);let c=o.root.toString();o.additions.some(u=>u.cid.toString()===c)||await t.get(o.root)||(console.error(`missing root in additions: ${o.additions.length} ${c} keys: ${r.map(l=>l.key).toString()}`),o.head=e);for(let{cid:u,bytes:l}of[...o.additions,...o.removals,o.event])t.putSync(u,l);e=o.head}return{head:e}}async function oE(t,e){let r;e.del?r={del:!0}:(await iE(t,e.value),r={doc:e.value});let n=await Ve({value:r,hasher:le,codec:q});return t.putSync(n.cid,n.bytes),n.cid}async function iE(t,e){e._files&&await nw(t,e._files),e._publicFiles&&await nw(t,e._publicFiles,!0)}async function nw(t,e,r=!1){let n=t.parent,o=new xt(n);n.transactions.add(o);let i=[],s=0;for(let c in e)if(File===e[c].constructor){let a=e[c];s+=a.size;let{cid:u,blocks:l}=await tw(a);i.push(c);for(let d of l)o.putSync(d.cid,d.bytes);e[c]={cid:u,type:a.type,size:a.size}}if(s>1024*1024*1)throw new Error("Sync limit for files in a single update is 1MB");if(i.length){let c=await n.loader?.commit(o,{files:e},{public:r});if(c)for(let a of i)e[a]={car:c,...e[a]}}}async function sw(t,e,r){if(!e.length)throw new Error("Getting from an empty database");let n=await mp(t,e,r);if(!n)throw new Error(`Missing key ${r}`);return await ml(t,n)}function yl(t,{doc:e}){e&&(e._files&&ow(t,e._files),e._publicFiles&&ow(t,e._publicFiles,!0))}function ow(t,e,r=!1){for(let n in e){let o=e[n];if(o.cid&&(r&&(o.url=`https://${o.cid.toString()}.ipfs.w3s.link/`),o.car&&t.loader)){let i=t.loader;o.file=async()=>await rw({get:async s=>{let a=await(await i.loadFileCar(o.car,r)).get(s);if(!a)throw new Error(`Missing block ${s.toString()}`);return a.bytes}},o.cid,o)}e[n]=o}}async function ml(t,e){let r=await t.get(e);if(!r)throw new Error(`Missing linked block ${e.toString()}`);let{value:n}=await mt({bytes:r.bytes,hasher:le,codec:q});return yl(t,n),n}var hl=class extends We{async get(e){try{return await super.get(e)}catch(r){return console.error("missing event",e.toString(),r),{value:null}}}};async function _o(t,e,r,n){let o=n.dirty?new hl(t):new We(t);return{result:(await pl(t,o,e,r,[],new Set,new Set,n.limit||1/0)).reverse(),head:e}}async function pl(t,e,r,n,o=[],i,s,c){if(c<=0)return o;let a=r.map(u=>u.toString());for(let u of n)if(a.includes(u.toString()))return o;for(let u of r){if(s.has(u.toString()))continue;s.add(u.toString());let{value:l}=await e.get(u);if(!l)continue;let{key:d,value:m}=l.data;if(i.has(d))l.parents&&(o=await pl(t,e,l.parents,n,o,i,s,c));else{i.add(d);let f=await ml(t,m);o.push({key:d,value:f.doc,del:f.del}),c--,l.parents&&(o=await pl(t,e,l.parents,n,o,i,s,c))}}return o}async function*aw(t,e){for await(let[r,n]of Lc(t,e)){let o=await ml(t,n);yield{key:r,value:o.doc,del:o.del}}}async function*cw(t,e){for await(let r of Cc(t,e))yield r}async function uw(t,e){let r=new Pi(t),n=new xt(t);for await(let[,i]of Lc(r,e))if(!await r.get(i))throw new Error("Missing block: "+i.toString());for await(let i of Cc(r,e));let o=await Or(r,e);for(let{cid:i,bytes:s}of[...o.additions,...o.removals])n.putSync(i,s);await _o(r,e,[],{});for(let i of r.cids){let s=await t.get(i);if(!s)throw new Error("Missing block: "+i.toString());await n.put(i,s.bytes)}await t.commitCompaction(n,e)}var Hs=class{head=[];zoomers=new Set;watchers=new Set;blocks=null;setHead(e){this.head=e}async applyHead(e,r,n,o=null){let i=this.head.sort((u,l)=>u.toString().localeCompare(l.toString()));if(r=r.sort((u,l)=>u.toString().localeCompare(l.toString())),i.toString()===r.toString()){this.watchers.forEach(u=>u(o||[]));return}let s=n.sort((u,l)=>u.toString().localeCompare(l.toString()));if(i.toString()===s.toString()){this.setHead(r),this.watchers.forEach(u=>u(o||[]));return}let c=async(u,l)=>{if(u instanceof xt)return await l(u);if(!this.blocks)throw new Error("missing blocks");return await this.blocks.transaction(l,void 0,{noLoader:!0})},{head:a}=await c(e,async u=>{let l=this.head;for(let m of r)l=await jn(u,l,m);let d=await Or(u,l);for(let{cid:m,bytes:f}of[...d.additions,...d.removals])u.putSync(m,f);return{head:l}});this.watchers.size&&!o&&(o=(await _o(this.blocks,a,n,{})).result),this.setHead(a),this.zoomers.forEach(u=>u()),this.watchers.forEach(u=>u(o||[]))}onTick(e){this.watchers.add(e)}onZoom(e){this.zoomers.add(e)}};var js=class{name;opts={};ready;blocks;indexBlocks;indexers=new Map;clock=new Hs;constructor(e,r){this.name=e||null,this.opts=r||this.opts,this.blocks=new Ui(this.name,this.clock,this.opts),this.clock.blocks=this.blocks,this.indexBlocks=new Ni(this.opts.persistIndexes&&this.name?this.name+".idx":null,this,this.opts),this.ready=Promise.all([this.blocks.ready,this.indexBlocks.ready]).then(()=>{}),this.clock.onZoom(()=>{for(let n of this.indexers.values())n._resetIndex()})}async bulk(e,r){return await this.ready,await this.blocks.transaction(async n=>{let o=[...this.clock.head],{head:i}=await iw(n,this.clock.head,e,r);return e=e.map(({key:s,value:c,del:a})=>(yl(this.blocks,{doc:c}),{key:s,value:c,del:a})),await this.clock.applyHead(n,i,o,e),{head:i}})}async allDocs(){await this.ready;let e=[];for await(let r of aw(this.blocks,this.clock.head))e.push(r);return{result:e,head:this.clock.head}}async vis(){await this.ready;let e=[];for await(let r of cw(this.blocks,this.clock.head))e.push(r);return e.join(`
3
+ You can use close({ resize: true }) to resize header`)},xh=(t,e)=>{let{bytes:r,headerSize:n}=t;r.set(r.subarray(n,t.byteOffset),e),t.byteOffset+=e-n,t.headerSize=e},za=(t,e)=>{t.bytes.set(e,t.byteOffset),t.byteOffset+=e.length},wh=({bytes:t},e,r)=>{t.set(e),t.set(r,e.length)},c1=[new B(x.map,2),new B(x.string,"version"),new B(x.uint,1),new B(x.string,"roots")],u1=new B(x.tag,42),l1=t=>{let e=[...c1];e.push(new B(x.array,t.length));for(let n of t)e.push(u1),e.push(new B(x.bytes,{length:n+1}));let r=Oa(e);return Dn.default.encodingLength(r)+r},ci=({roots:t})=>l1(t.map(e=>e.bytes.byteLength));var kh=(t,e={})=>{let{roots:r=[],byteOffset:n=0,byteLength:o=t.byteLength,headerSize:i=ci({roots:r})}=e,s=new Uint8Array(t,n,o),c=new $a(s,i);for(let a of r)c.addRoot(a);return c};var Mt=({name:t,code:e,encode:r})=>new Ha(t,e,r),Ha=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Ut(this.code,r):r.then(n=>Ut(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ui({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*d1(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r],i=j.asCID(n);i?yield[o.join("/"),i]:typeof n=="object"&&(yield*ja(n,o))}else{let r=j.asCID(e);r?yield[t.join("/"),r]:yield*ja(e,t)}}function*ja(t,e){if(t==null||t instanceof Uint8Array)return;let r=j.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,o]of Object.entries(t)){let i=[...e,n];yield*d1(i,o)}}function*h1(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r];yield o.join("/"),typeof n=="object"&&!j.asCID(n)&&(yield*Va(n,o))}else yield*Va(e,t)}function*Va(t,e){if(!(t==null||typeof t!="object"))for(let[r,n]of Object.entries(t)){let o=[...e,r];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!j.asCID(n)&&(yield*h1(o,n))}}function p1(t,e){let r=t;for(let[n,o]of e.entries()){if(r=r[o],r==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=j.asCID(r);if(i)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:r}}var Nn=class{constructor({cid:e,bytes:r,value:n}){if(!e||!r||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=r,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:ui(),bytes:ui(),value:ui(),asBlock:ui()})}links(){return ja(this.value,[])}tree(){return Va(this.value,[])}get(e="/"){return p1(this.value,e.split("/").filter(Boolean))}};async function Ve({value:t,codec:e,hasher:r}){if(typeof t>"u")throw new Error('Missing required argument "value"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.encode(t),o=await r.digest(n),i=j.create(1,e.code,o);return new Nn({value:t,bytes:n,cid:i})}async function mt({bytes:t,codec:e,hasher:r}){if(!t)throw new Error('Missing required argument "bytes"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.decode(t),o=await r.digest(t),i=j.create(1,e.code,o);return new Nn({value:n,bytes:t,cid:i})}function y1({bytes:t,cid:e,value:r,codec:n}){let o=r!==void 0?r:n&&n.decode(t);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Nn({cid:e,bytes:t,value:o})}async function li({bytes:t,cid:e,hasher:r,codec:n}){if(!t)throw new Error('Missing required argument "bytes"');if(!r)throw new Error('Missing required argument "hasher"');let o=n.decode(t),i=await r.digest(t);if(!Nt.equals(e.multihash.bytes,i.bytes))throw new Error("CID hash does not match bytes");return y1({bytes:t,cid:e,value:o,codec:n})}var qa=V(require("crypto"),1);var le=Mt({name:"sha2-256",code:18,encode:t=>ie(qa.default.createHash("sha256").update(t).digest())}),C8=Mt({name:"sha2-512",code:19,encode:t=>ie(qa.default.createHash("sha512").update(t).digest())});var gt={};G(gt,{code:()=>Un,decode:()=>w1,encode:()=>g1,name:()=>m1});var m1="raw",Un=85,g1=t=>ie(t),w1=t=>ie(t);async function Pn(t,e){let r=0,n=ci({roots:t});r+=n;for(let{cid:s,bytes:c}of e.entries())r+=bh({cid:s,bytes:c});let o=new Uint8Array(r),i=kh(o,{headerSize:n});for(let s of t)i.addRoot(s);for(let{cid:s,bytes:c}of e.entries())i.write({cid:s,bytes:c});return i.close(),await Ve({value:i.bytes,hasher:le,codec:gt})}async function Wa(t){return await Ve({value:{fp:t},hasher:le,codec:q})}async function Ka(t){let e=await t.getRoots(),r=await t.get(e[0]);if(!r)throw new Error("missing header block");let{value:n}=await mt({bytes:r.bytes,hasher:le,codec:q});if(n&&n.fp===void 0)throw new Error("missing fp");let{fp:o}=n;return o}var Rt={};G(Rt,{code:()=>E1,crypto:()=>S1,decode:()=>v1,decrypt:()=>hi,encode:()=>k1,encrypt:()=>pi,name:()=>A1});function fi(){try{return window.crypto&&window.crypto.subtle?window.crypto:new Crypto}catch{return null}}var Fn=fi();function di(t){let e=new Uint8Array(t);return t>0&&Fn.getRandomValues(e),e}var b1=t=>{t=+t;let e=new Uint8Array(4);return e[3]=t>>>24,e[2]=t>>>16,e[1]=t>>>8,e[0]=t&255,e},x1=t=>{let e=t.byteLength-4;return(t[e]|t[e+1]<<8|t[e+2]<<16)+t[e+3]*16777216},Eh=t=>{let e=t.map(i=>i instanceof ArrayBuffer?new Uint8Array(i):i),r=e.reduce((i,s)=>i+s.length,0),n=new Uint8Array(r),o=0;for(let i of e)n.set(i,o),o+=i.length;return n},k1=({iv:t,bytes:e})=>Eh([t,e]),v1=t=>{let e=t.subarray(0,12);return t=t.slice(12),{iv:e,bytes:t}},E1=3145728+1337;async function Sh(t){return await Fn.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt","decrypt"])}var hi=async({key:t,value:e})=>{let{bytes:r,iv:n}=e,o=await Sh(t),i=await Fn.subtle.decrypt({name:"AES-GCM",iv:n,tagLength:128},o,r);r=new Uint8Array(i);let s=x1(r.subarray(0,4)),c=j.decode(r.subarray(4,4+s));return r=r.subarray(4+s),{cid:c,bytes:r}},pi=async({key:t,cid:e,bytes:r})=>{let n=b1(e.bytes.byteLength),o=di(12),i=Eh([n,e.bytes,r]);try{let s=await Sh(t),c=await Fn.subtle.encrypt({name:"AES-GCM",iv:o,tagLength:128},s,i);r=new Uint8Array(c)}catch(s){throw console.log("ee",s),s}return{value:{bytes:r,iv:o}}},S1=t=>({encrypt:e=>pi({key:t,...e}),decrypt:e=>hi({key:t,...e})}),A1="jchris@encrypted-block:aes-gcm";var Mn=t=>{let e=t.byteLength-4;return(t[e]|t[e+1]<<8|t[e+2]<<16)+t[e+3]*16777216};var Rn=t=>{let e=Math.floor(4294967295/t);return async r=>{let n=await r.identity();if(typeof n!="number")throw new Error("Identity must be a number");return n<=e}};var zt=(t,e)=>t===e?0:t>e?1:-1,Ah=(t,e)=>{for(let r=0;r<t.byteLength;r++){if(e.byteLength===r)return 1;let n=t[r],o=e[r];if(n!==o)return n>o?1:-1}return e.byteLength>t.byteLength?-1:0},Ot=class{constructor(){this._cids=new Set}add(e){if(!e.address)throw new Error("Cannot add node without address");if(e.address.then){let r=e.address.then(n=>this._cids.add(n.toString()));this._cids.add(r),r.then(()=>this._cids.delete(r))}else this._cids.add(e.address.toString())}async all(){return await Promise.all([...this._cids]),this._cids}};var $t=class{constructor({key:e,address:r},n={}){this.key=e,this.address=r,this.codec=n.codec,this.hasher=n.hasher}get isEntry(){return!0}},wt=class{constructor({entries:e,closed:r}){if(typeof r!="boolean")throw new Error('Missing required argument "closed"');this.entries=e,this.closed=r,this.startKey=e[0].key}find(e,r){let{entries:n}=this;for(let o=n.length-1;o>-1;o--){let i=n[o];if(r(e,i.key)>-1)return[o,i]}return null}findMany(e,r,n=!1,o=!1){let{entries:i}=this,s=new Map;n?e=[...e]:e=e.sort(r);for(let c=i.length-1;c>-1&&e.length;c--){let a=i[c],u=[];for(;e.length;){let l=e[e.length-1];l=l.key?l.key:l;let d=r(l,a.key);if(o)if(d===0)u.push(e.pop());else if(d>0)e.pop();else break;else if(d>-1)u.push(e.pop());else break}u.length&&s.set(c,[a,u])}return s}findRange(e,r,n){let{entries:o}=this,i,s=0;for(let c=o.length-1;c>-1;c--){let a=o[c];if(n(r,a.key)>0){i=c;break}}for(let c=0;c<o.length;c++){let a=o[c],u=n(e,a.key);if(u===0){s=c;break}else if(u<0)break;s=c}return{first:s,last:i,entries:o.slice(s,i+1)}}},_h=t=>typeof t=="string"?t:JSON.stringify(t);function _1(t,e){return t.sort(({key:r},{key:n})=>e.compare(r,n))}async function B1(t,e,r){let n=[];for(let o of e){let{key:i,del:s}=o;if(r(i,t)<0)s||n.push(o);else break}return n}async function C1(t,e,{chunker:r,compare:n}){return await bt.from({entries:t.map(o=>new e.LeafEntryClass(o,e)).sort((o,i)=>n(o.key,i.key)),chunker:r,NodeClass:e.LeafClass,distance:0,opts:e})}async function T1(t,e,r,n){return await Promise.all(e.map(async o=>{let i=await o.encode();return r.blocks.push({block:i,node:o}),t.cache.set(o),new n.BranchEntryClass({key:o.key,address:await o.address},n)}))}async function I1(t,e,r,n){let o=e.root;e.blocks.push({block:await o.encode(),node:o}),t.cache.set(o);let i=n.opts,s=o.distance,c=o.entryList.startKey,a=await B1(c,r,t.compare);if(a.length){let u=await C1(a,i,t),l=await T1(t,u,e,i),m=[new i.BranchEntryClass({key:o.entryList.startKey,address:await o.address},i),...l].sort(({key:p},{key:w})=>i.compare(p,w)),f=await bt.from({...n,entries:m,chunker:t.chunker,NodeClass:i.BranchClass,distance:s+1}),h=[...f];for(;f.length>1;){let p=await Promise.all(f.map(async w=>new i.BranchEntryClass({key:w.key,address:await w.address},i)));f=await bt.from({...n,entries:p.sort(({key:w},{key:g})=>i.compare(w,g)),chunker:t.chunker,NodeClass:i.BranchClass,distance:s+1}),h=[...h,...f]}await Promise.all(h.map(async p=>{let w=await p.encode();t.cache.set(p),e.blocks.push({block:w,node:p})})),e.root=f[0],e.nodes=[...e.nodes,...h]}}var bt=class t{constructor({entryList:e,chunker:r,distance:n,getNode:o,compare:i,cache:s}){this.entryList=e,this.chunker=r,this.distance=n,this.getNode=o,this.compare=i,this.cache=s}get closed(){return this.entryList.closed}get key(){return this.entryList.startKey}async getEntry(e,r=new Ot){return{result:await this._getEntry(e,r),cids:r}}async _getEntry(e,r){r.add(this);let n=this;for(;!n.isLeaf;){let s=n.entryList.find(e,this.compare);if(s===null)throw new Error("Not found");let[,c]=s;n=await this.getNode(await c.address),r.add(n)}let o=n.entryList.find(e,this.compare);if(o===null||o[1].key.toString()!==e.toString())throw new Error("Not found");let[,i]=o;return i}async getAllEntries(e=new Ot){return{result:await this._getAllEntries(e),cids:e}}_getAllEntries(e){if(e.add(this),this.isLeaf)return this.entryList.entries;{let{entries:r}=this.entryList,n=async o=>this.getNode(await o.address).then(i=>i._getAllEntries(e)).catch(async i=>{throw i});return Promise.all(r.map(n)).then(o=>o.flat())}}async*vis(e=new Set){let r=async i=>i.isLeaf?`Leaf [${i.entryList.entries.map(c=>`[${c.key},${JSON.stringify(c.value).replace(/"/g,"'")}]`).join(", ")}]`:`Branch [${i.entryList.entries.map(c=>`[${c.key}]`).join(", ")}]`,n=i=>i.toString().slice(0,4)+i.toString().slice(-4),o=async function*(i,s,c){let a=await i.address;if(!c.has(a)){c.add(a);let u=await r(i);yield` node [shape=ellipse fontname="Courier"]; ${n(a)} [label="${u}"];`,yield` ${n(s)} -> ${n(a)};`;for(let l of i.entryList.entries)if(l.address){let d=await l.address;try{let m=await i.getNode(d);yield*await o(m,a,c)}catch(m){yield` ${n(a)} -> ${n(d)};`,yield` node [shape=ellipse fontname="Courier"]; ${n(d)} [label="Error: ${m.message}"];`}}}};yield"digraph tree {",yield' node [shape=ellipse fontname="Courier"]; rootnode;';for await(let i of o(this,"rootnode",e))yield i;yield"}"}async getEntries(e,r=!1,n=new Ot){return{result:await this._getEntries(e,r,n),cids:n}}async _getEntries(e,r,n){n.add(this),r||(e=e.sort(this.compare));let o=this.entryList.findMany(e,this.compare,!0,this.isLeaf);if(this.isLeaf)return[...o.values()].map(([s])=>s);let i=[];for(let[s,c]of[...o.values()].reverse()){let a=this.getNode(await s.address);i.push(a.then(u=>u._getEntries(c.reverse(),!0,n)))}return i=await Promise.all(i),i.flat()}async getRangeEntries(e,r,n=new Ot){return{result:await this._getRangeEntries(e,r,n),cids:n}}_getRangeEntries(e,r,n){n.add(this);let{entries:o}=this.entryList.findRange(e,r,this.compare);if(this.isLeaf)return o.filter(a=>{let u=this.compare(e,a.key),l=this.compare(r,a.key);return u<=0&&l>=0});if(!o.length)return[];let i=async a=>this.getNode(await a.address).then(u=>u._getRangeEntries(e,r,n)),s=[i(o.shift())];if(!o.length)return s[0];let c=i(o.pop());for(;o.length;){let a=async u=>this.getNode(await u.address).then(async l=>l._getAllEntries(n));s.push(a(o.shift()))}return s.push(c),Promise.all(s).then(a=>a.flat())}async transaction(e,r={}){r={codec:this.codec,hasher:this.hasher,getNode:this.getNode,compare:this.compare,cache:this.cache,...r};let n={chunker:this.chunker,opts:r},o=this.entryList.findMany(e,r.compare,!0,this.isLeaf);return this.isLeaf?await this.transactionLeaf(e,r,n,o):await this.transactionBranch(e,r,n,o)}async transactionLeaf(e,r,n,o){let{LeafClass:i,LeafEntryClass:s}=r,{entries:c,previous:a}=this.processLeafEntries(e,o,s,r),u={...n,entries:c,NodeClass:i,distance:0},l=await t.from(u);return{nodes:l,previous:a,blocks:await Promise.all(l.map(async d=>{let m=await d.encode();return this.cache.set(d),{block:m,node:d}})),distance:0}}processLeafEntries(e,r,n,o){let i=[],s=[],c={},a=new Map;for(let{key:d,del:m,value:f}of e){let h=_h(d);m?typeof c[h]>"u"&&a.set(h,null):(c[h]={key:d,value:f},a.delete(h))}s=[...this.entryList.entries];for(let[d,[m]]of r){i.push(m);let f=_h(m.key);a.has(f)?a.set(f,d):(s[d]=new n(c[f],o),delete c[f])}let u=0;for(let[,d]of a)d!==null&&s.splice(d-u++,1);let l=Object.values(c).map(d=>new n(d,o));return s=s.concat(l).sort(({key:d},{key:m})=>o.compare(d,m)),{entries:s,previous:i}}async transactionBranch(e,r,n,o){let{BranchClass:i,BranchEntryClass:s}=r,c=0;for(let[h,[p,w]]of o){let g=this.getNode(await p.address).then(b=>b.transaction(w.reverse(),{...r,sorted:!0})).then(b=>({entry:p,keys:w,distance:c,...b}));o.set(h,g)}let a=[...this.entryList.entries],u={previous:[],blocks:[],nodes:[]};for(let[h,p]of o){let{nodes:w,previous:g,blocks:b,distance:k}=await p;c=k,a[h]=w,g.length&&(u.previous=u.previous.concat(g)),b.length&&(u.blocks=u.blocks.concat(b)),w.length&&(u.nodes=u.nodes.concat(w))}a=a.flat();let l=await this.handlePrepend(a,r,n,u,c);c++;let d=async h=>{if(h.isEntry)return h;let p=await h.encode();return u.blocks.push({block:p,node:h}),this.cache.set(h),new s(h,r)};a=await Promise.all(l.map(d));let m={...n,entries:a,NodeClass:i,distance:c},f=await t.from(m);return await Promise.all(f.map(async h=>{let p=await h.encode();u.blocks.push({block:p,node:h}),this.cache.set(h)})),u.nodes=f,{...u,distance:c}}async handlePrepend(e,r,n,o,i){let{BranchClass:s,LeafClass:c}=r,a=[],u=null;for(let l of e)if(u){let d=await this.mergeFirstLeftEntries(l,u,n,o,i);u=null;let m=d[0].address?s:c,f={...n,entries:d.sort(({key:p},{key:w})=>r.compare(p,w)),NodeClass:m,distance:i},h=await t.from(f);h[h.length-1].closed||(u=h.pop()),h.length&&(a=a.concat(h))}else!l.isEntry&&!l.closed?u=l:a.push(l);return u&&a.push(u),a}async getNodeFirstFromBlocks(e,r){for(let{block:n,node:o}of e)if(await n.cid===r)return o;return await this.getNode(r)}async mergeFirstLeftEntries(e,r,n,o,i){let s=n.opts,{LeafClass:c,BranchClass:a,BranchEntryClass:u}=s;if(e.isEntry){let f=await e.address;e=await this.getNodeFirstFromBlocks(o.blocks,f)}let l=e.entryList.entries;if(!l.length)throw new Error("unreachable no entries");let d=(f,h)=>f.concat(h),m=async(f,h,p)=>await Promise.all(f.map(async w=>(h.blocks.push({block:await w.encode(),node:w}),this.cache.set(w),new u({key:w.key,address:await w.address},p))));if(l[0].constructor.name===r.entryList.entries[0].constructor.name)return await d(r.entryList.entries,l);{let f=l.shift();if(!f)throw new Error("unreachable no left entry");if(!f.address)throw new Error("unreachable existing leaf, no leftEntry.address");let h=await this.mergeFirstLeftEntries(f,r,n,o,i-1),p=l.shift();if(!p)return h;if(!p.address)throw new Error("unreachable existing leaf, no esf.address");let w=await this.getNodeFirstFromBlocks(o.blocks,await p.address);if(w.entryList.entries[0].address){if(h[0].address)return h.concat(w.entryList.entries);{let g=await t.from({...n,entries:h.sort(({key:C},{key:N})=>s.compare(C,N)),NodeClass:c,distance:i}),b=await m(g,o,s),k=await t.from({...n,entries:[...w.entryList.entries,...b,...l].sort(({key:C},{key:N})=>s.compare(C,N)),NodeClass:a,distance:i});return await m(k,o,s)}}else{let g=await d(h,w.entryList.entries),b=await t.from({...n,entries:g.sort(({key:v},{key:C})=>s.compare(v,C)),NodeClass:c,distance:i}),k=await m(b,o,s);return await d(k,l)}}}async bulk(e,r={},n=!0){let{BranchClass:o}=r;r={codec:this.codec,hasher:this.hasher,getNode:this.getNode,compare:this.compare,cache:this.cache,...r},r.sorted||(e=_1(e,r),r.sorted=!0);let i={chunker:this.chunker,opts:r},s=await this.transaction(e,r);for(;s.nodes.length>1;){let c=s.nodes[0].distance+1,a=await Promise.all(s.nodes.map(async l=>{let d=await l.encode();return s.blocks.push({block:d,node:l}),this.cache.set(l),new r.BranchEntryClass(l,r)})),u=await t.from({...i,entries:a,NodeClass:o,distance:c});await Promise.all(u.map(async l=>{let d=await l.encode();this.cache.set(l),s.blocks.push({block:d,node:l})})),s.nodes=u}return s.root=s.nodes[0],n&&s.root&&await I1(this,s,e,i),s.blocks=s.blocks.map(({block:c})=>c),s}static async from({entries:e,chunker:r,NodeClass:n,distance:o,opts:i}){if(!e.every(a=>a.constructor.name===e[0].constructor.name))throw new Error("all entries must be of the same type");let s=[],c=[];for(let a of e)c.push(a),await r(a,o)&&(s.push(new wt({entries:c,closed:!0})),c=[]);return c.length&&s.push(new wt({entries:c,closed:!1})),s.map(a=>new n({entryList:a,chunker:r,distance:o,...i}))}},yi=class extends bt{constructor({codec:e,hasher:r,block:n,...o}){super(o),this.codec=e,this.hasher=r,n?(this.block=n,this.address=n.cid):(this.block=this.encode(),this.address=this.block.then(i=>i.cid))}async get(e){let{result:r,cids:n}=await this.getEntry(e);return{result:r.key,cids:n}}async encode(){if(this.block)return this.block;let e=await this.encodeNode(),r={codec:this.codec,hasher:this.hasher,value:e};return this.block=await Ve(r),this.block}},Lr=class extends yi{async encodeNode(){let{entries:e}=this.entryList,r=async o=>{if(!o.address)throw new Error("entry.address required");return[o.key,await o.address]},n=await Promise.all(e.map(r));return{branch:[this.distance,n],closed:this.closed}}get isBranch(){return!0}},Dr=class extends yi{async encodeNode(){return{leaf:await Promise.all(this.entryList.entries.map(async r=>await r.encodeNode())),closed:this.closed}}get isLeaf(){return!0}},mi=async function*(t){let{LeafClass:e,LeafEntryClass:r,BranchClass:n,BranchEntryClass:o,list:i,chunker:s,compare:c,...a}=t;i=i.map(d=>new r(d,a)),a.compare=c;let u=await bt.from({entries:i,chunker:s,NodeClass:e,distance:0,opts:a});yield*u;let l=1;for(;u.length>1;){let d=async f=>new o({key:f.key,address:await f.address},a),m=await Promise.all(u.map(d));u=await bt.from({entries:m,chunker:s,NodeClass:n,distance:l,opts:a}),yield*u,l++}};var Ga=({bytes:t},{bytes:e})=>Ah(t,e),gi=class extends $t{constructor(e){super({address:e,key:e}),this.cid=e}encodeNode(){return this.cid}identity(){let e=this.cid.multihash.bytes;return Mn(e)}},wi=class extends $t{async identity(){let{multihash:{bytes:e}}=await this.address;return Mn(e)}},bi=class extends Lr{},xi=class extends Dr{},Bh=(t,e,r,n,o)=>{let i=c=>{let{value:a}=c,u={chunker:r,cache:e,block:c,getNode:s,codec:n,hasher:o,compare:Ga},l,d;if(a.leaf)l=a.leaf.map(h=>new gi(h)),d=xi;else if(a.branch){let[h,p]=a.branch;u.distance=h,l=p.map(([w,g])=>new wi({key:w,address:g})),d=bi}else throw new Error("Unknown block data, does not match schema");let m=new wt({entries:l,closed:a.closed}),f=new d({entryList:m,...u});return e.set(f),f},s=c=>e.has(c)?e.get(c):t(c).then(a=>i(a));return s},Ch=({get:t,cache:e,chunker:r,list:n,codec:o,hasher:i,sorted:s})=>{s||(n=n.sort(Ga));let c=Bh(t,e,r,o,i);return mi({list:n,codec:o,hasher:i,chunker:r,getNode:c,sorted:s,compare:Ga,cache:e,LeafClass:xi,LeafEntryClass:gi,BranchClass:bi,BranchEntryClass:wi})},Th=({cid:t,get:e,cache:r,chunker:n,codec:o,hasher:i,...s})=>Bh(e,r,n,o,i,s)(t);var Ih=async function*({get:t,cids:e,hasher:r,key:n,cache:o,chunker:i,root:s}){let c=new Set,a;for(let f of e){let h=await t(f);if(!h)throw new Error("missing cid: "+f.toString());let p=await pi({...h,key:n}),w=await Ve({...p,codec:Rt,hasher:r});yield w,c.add(w.cid.toString()),h.cid.equals(s)&&(a=w.cid)}if(!a)throw new Error("cids does not include root");let u=[...c].map(f=>j.parse(f)),l;for await(let f of Ch({list:u,get:t,cache:o,chunker:i,hasher:r,codec:q})){let h=await f.block;yield h,l=h}if(!l)throw new Error("missing last block");let d=[a,l.cid];yield await Ve({value:d,codec:q,hasher:r})},Lh=async function*({root:t,get:e,key:r,cache:n,chunker:o,hasher:i}){let s=async w=>e(w).then(async g=>g?await mt({...g,codec:q,hasher:i}):void 0),c=async w=>e(w).then(async g=>g?await mt({...g,codec:Rt,hasher:i}):void 0),a=await s(t);if(!a)throw new Error("missing root");if(!a.bytes)throw new Error("missing bytes");let{value:[u,l]}=a,d=await e(u);if(!d)throw new Error("missing root block");let m=await Th({cid:l,get:s,cache:n,chunker:o,codec:Rt,hasher:i}),{result:f}=await m.getAllEntries(),h=async w=>{if(!w)throw new Error("missing block");w.value||(w=await mt({...w,codec:Rt,hasher:i}));let{bytes:g,cid:b}=await hi({...w,key:r}).catch(v=>{throw v});return await li({cid:b,bytes:g,hasher:i,codec:Rt})},p=[];for(let{cid:w}of f)d.cid.equals(w)||p.push(c(w).then(h));yield*p,yield h(d)};var Nr={has:()=>!1,get:()=>{throw new Error("Cannot ask for entries from nocache")},set:()=>{}};var Dh=Rn(30);function Nh(t){let e=t.length,r=new Uint8Array(e/2);for(let n=0;n<e;n+=2)r[n/2]=parseInt(t.substring(n,n+2),16);return r}async function Uh(t,e,r){let n=Nh(t),o=n.buffer.slice(0,n.byteLength),i=new Ae,s=[];for(let{cid:u}of r.entries())s.push(u);let c=null;for await(let u of Ih({cids:s,get:r.get.bind(r),key:o,hasher:le,chunker:Dh,cache:Nr,root:e}))await i.put(u.cid,u.bytes),c=u;if(!c)throw new Error("no blocks encrypted");return await Pn([c.cid],i)}async function Ph(t,e){let n=(await e.getRoots())[0];return await L1(n,e.get.bind(e),t)}async function L1(t,e,r){let n=Nh(r),o=n.buffer.slice(0,n.byteLength),i=new Ae,s=null;for await(let c of Lh({root:t,get:e,key:o,hasher:le,chunker:Dh,cache:Nr}))await i.put(c.cid,c.bytes),s=c;if(!s)throw new Error("no blocks decrypted");return{blocks:i,root:s.cid}}var Qa=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let r=this.inRecursive[this.inRecursive.length-1];r&&(r.type===y.array&&(r.elements++,r.elements!==1&&e.push([44])),r.type===y.map&&(r.elements++,r.elements!==1&&(r.elements%2===1?e.push([44]):e.push([58]))))}[y.uint.major](e,r){this.prefix(e);let n=String(r.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[y.negint.major](e,r){this[y.uint.major](e,r)}[y.bytes.major](e,r){throw new Error(`${Ze} unsupported type: Uint8Array`)}[y.string.major](e,r){this.prefix(e);let n=Po(JSON.stringify(r.value));e.push(n.length>32?hn(n):n)}[y.array.major](e,r){this.prefix(e),this.inRecursive.push({type:y.array,elements:0}),e.push([91])}[y.map.major](e,r){this.prefix(e),this.inRecursive.push({type:y.map,elements:0}),e.push([123])}[y.tag.major](e,r){}[y.float.major](e,r){if(r.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===y.array)e.push([93]);else if(s.type===y.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(r.value===void 0)throw new Error(`${Ze} unsupported type: undefined`);if(this.prefix(e),r.type.name==="true"){e.push([116,114,117,101]);return}else if(r.type.name==="false"){e.push([102,97,108,115,101]);return}else if(r.type.name==="null"){e.push([110,117,108,108]);return}let n=String(r.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function D1(t,e){if(Array.isArray(t[0])||Array.isArray(e[0]))throw new Error(`${Ze} complex map keys are not supported`);let r=t[0],n=e[0];if(r.type!==y.string||n.type!==y.string)throw new Error(`${Ze} non-string map keys are not supported`);if(r<n)return-1;if(r>n)return 1;throw new Error(`${Ze} unexpected duplicate map keys, this is not supported`)}var N1={addBreakTokens:!0,mapSorter:D1};function Ja(t,e){return e=Object.assign({},N1,e),ua(t,new Qa,e)}var Ur=class{constructor(e,r={}){this.pos=0,this.data=e,this.options=r,this.modeStack=["value"],this.lastToken=""}done(){return this.pos>=this.data.length}ch(){return this.data[this.pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this.pos]}expect(e){if(this.data.length-this.pos<e.length)throw new Error(`${T} unexpected end of input at position ${this.pos}`);for(let r=0;r<e.length;r++)if(this.data[this.pos++]!==e[r])throw new Error(`${T} unexpected token at position ${this.pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this.pos,r=!1,n=!1,o=c=>{for(;!this.done();){let a=this.ch();if(c.includes(a))this.pos++;else break}};if(this.ch()===45&&(r=!0,this.pos++),this.ch()===48)if(this.pos++,this.ch()===46)this.pos++,n=!0;else return new E(y.uint,0,this.pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),r&&this.pos===e+1)throw new Error(`${T} unexpected token at position ${this.pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${T} unexpected token at position ${this.pos}`);n=!0,this.pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this.pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this.pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this.pos)),s=parseFloat(i);return n?new E(y.float,s,this.pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new E(s>=0?y.uint:y.negint,s,this.pos-e):new E(s>=0?y.uint:y.negint,BigInt(i),this.pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${T} unexpected character at position ${this.pos}; this shouldn't happen`);this.pos++;for(let i=this.pos,s=0;i<this.data.length&&s<65536;i++,s++){let c=this.data[i];if(c===92||c<32||c>=128)break;if(c===34){let a=String.fromCharCode.apply(null,this.data.subarray(this.pos,i));return this.pos=i+1,new E(y.string,a,s)}}let e=this.pos,r=[],n=()=>{if(this.pos+4>=this.data.length)throw new Error(`${T} unexpected end of unicode escape sequence at position ${this.pos}`);let i=0;for(let s=0;s<4;s++){let c=this.ch();if(c>=48&&c<=57)c-=48;else if(c>=97&&c<=102)c=c-97+10;else if(c>=65&&c<=70)c=c-65+10;else throw new Error(`${T} unexpected unicode escape character at position ${this.pos}`);i=i*16+c,this.pos++}return i},o=()=>{let i=this.ch(),s=null,c=i>239?4:i>223?3:i>191?2:1;if(this.pos+c>this.data.length)throw new Error(`${T} unexpected unicode sequence at position ${this.pos}`);let a,u,l,d;switch(c){case 1:i<128&&(s=i);break;case 2:a=this.data[this.pos+1],(a&192)===128&&(d=(i&31)<<6|a&63,d>127&&(s=d));break;case 3:a=this.data[this.pos+1],u=this.data[this.pos+2],(a&192)===128&&(u&192)===128&&(d=(i&15)<<12|(a&63)<<6|u&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:a=this.data[this.pos+1],u=this.data[this.pos+2],l=this.data[this.pos+3],(a&192)===128&&(u&192)===128&&(l&192)===128&&(d=(i&15)<<18|(a&63)<<12|(u&63)<<6|l&63,d>65535&&d<1114112&&(s=d))}s===null?(s=65533,c=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|s&1023),r.push(s),this.pos+=c};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this.pos++,this.done())throw new Error(`${T} unexpected string termination at position ${this.pos}`);switch(s=this.ch(),this.pos++,s){case 34:case 39:case 92:case 47:r.push(s);break;case 98:r.push(8);break;case 116:r.push(9);break;case 110:r.push(10);break;case 102:r.push(12);break;case 114:r.push(13);break;case 117:r.push(n());break;default:throw new Error(`${T} unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new E(y.string,na(r),this.pos-e);default:if(i<32)throw new Error(`${T} invalid control character at position ${this.pos}`);i<128?(r.push(i),this.pos++):o()}}throw new Error(`${T} unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new E(y.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new E(y.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new E(y.null,null,4);case 102:return this.expect([102,97,108,115,101]),new E(y.false,!1,5);case 116:return this.expect([116,114,117,101]),new E(y.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${T} unexpected character at position ${this.pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this.pos++,this.skipWhitespace(),new E(y.break,void 0,1);if(this.ch()!==44)throw new Error(`${T} unexpected character at position ${this.pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this.pos++,this.skipWhitespace(),new E(y.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this.pos++,this.skipWhitespace(),new E(y.break,void 0,1);if(this.ch()!==44)throw new Error(`${T} unexpected character at position ${this.pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this.pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this.pos++,this.skipWhitespace(),new E(y.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${T} unexpected character at position ${this.pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${T} unexpected parse state at position ${this.pos}; this shouldn't happen`)}}};function Xa(t,e){return e=Object.assign({tokenizer:new Ur(t,e)},e),xn(t,e)}var Ya=se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),m6=se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),g6=se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),w6=se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function P1(t){if(t.asCID!==t&&t["/"]!==t.bytes)return null;let e=j.asCID(t);if(!e)return null;let r=e.toString();return[new E(y.map,1/0,1),new E(y.string,"/",1),new E(y.string,r,r.length),new E(y.break,void 0,1)]}function ki(t){let e=Ya.encode(t).slice(1);return[new E(y.map,1/0,1),new E(y.string,"/",1),new E(y.map,1/0,1),new E(y.string,"bytes",5),new E(y.string,e,e.length),new E(y.break,void 0,1),new E(y.break,void 0,1)]}function Ue(t){return ki(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function F1(t){return ki(new Uint8Array(t))}function M1(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function R1(t){if(Number.isNaN(t))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(t===1/0||t===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var O1={typeEncoders:{Object:P1,Buffer:ki,Uint8Array:ki,Int8Array:Ue,Uint16Array:Ue,Int16Array:Ue,Uint32Array:Ue,Int32Array:Ue,Float32Array:Ue,Float64Array:Ue,Uint8ClampedArray:Ue,BigInt64Array:Ue,BigUint64Array:Ue,DataView:Ue,ArrayBuffer:F1,undefined:M1,number:R1}},Za=class extends Ur{constructor(e,r){super(e,r),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===y.map){let r=this._next();if(r.type===y.string&&r.value==="/"){let n=this._next();if(n.type===y.string){if(this._next().type!==y.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new E(y.tag,42,0)}if(n.type===y.map){let o=this._next();if(o.type===y.string&&o.value==="bytes"){let i=this._next();if(i.type===y.string){for(let c=0;c<2;c++)if(this._next().type!==y.break)throw new Error("Invalid encoded Bytes form");let s=Ya.decode(`m${i.value}`);return new E(y.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(r)}return e}},ec={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};ec.tags[42]=j.parse;var z1=t=>Ja(t,O1),$1=t=>{let e=Object.assign(ec,{tokenizer:new Za(t,ec)});return Xa(t,e)},vi=t=>H1.decode(z1(t));var H1=new TextDecoder,Ei=t=>$1(j1.encode(t)),j1=new TextEncoder;var V1=(t,e)=>e.some(r=>t instanceof r),Fh,Mh;function q1(){return Fh||(Fh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function W1(){return Mh||(Mh=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Rh=new WeakMap,rc=new WeakMap,Oh=new WeakMap,tc=new WeakMap,oc=new WeakMap;function K1(t){let e=new Promise((r,n)=>{let o=()=>{t.removeEventListener("success",i),t.removeEventListener("error",s)},i=()=>{r(qe(t.result)),o()},s=()=>{n(t.error),o()};t.addEventListener("success",i),t.addEventListener("error",s)});return e.then(r=>{r instanceof IDBCursor&&Rh.set(r,t)}).catch(()=>{}),oc.set(e,t),e}function G1(t){if(rc.has(t))return;let e=new Promise((r,n)=>{let o=()=>{t.removeEventListener("complete",i),t.removeEventListener("error",s),t.removeEventListener("abort",s)},i=()=>{r(),o()},s=()=>{n(t.error||new DOMException("AbortError","AbortError")),o()};t.addEventListener("complete",i),t.addEventListener("error",s),t.addEventListener("abort",s)});rc.set(t,e)}var nc={get(t,e,r){if(t instanceof IDBTransaction){if(e==="done")return rc.get(t);if(e==="objectStoreNames")return t.objectStoreNames||Oh.get(t);if(e==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return qe(t[e])},set(t,e,r){return t[e]=r,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function zh(t){nc=t(nc)}function Q1(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...r){let n=t.call(Si(this),e,...r);return Oh.set(n,e.sort?e.sort():[e]),qe(n)}:W1().includes(t)?function(...e){return t.apply(Si(this),e),qe(Rh.get(this))}:function(...e){return qe(t.apply(Si(this),e))}}function J1(t){return typeof t=="function"?Q1(t):(t instanceof IDBTransaction&&G1(t),V1(t,q1())?new Proxy(t,nc):t)}function qe(t){if(t instanceof IDBRequest)return K1(t);if(tc.has(t))return tc.get(t);let e=J1(t);return e!==t&&(tc.set(t,e),oc.set(e,t)),e}var Si=t=>oc.get(t);function Hh(t,e,{blocked:r,upgrade:n,blocking:o,terminated:i}={}){let s=indexedDB.open(t,e),c=qe(s);return n&&s.addEventListener("upgradeneeded",a=>{n(qe(s.result),a.oldVersion,a.newVersion,qe(s.transaction),a)}),r&&s.addEventListener("blocked",a=>r(a.oldVersion,a.newVersion,a)),c.then(a=>{i&&a.addEventListener("close",()=>i()),o&&a.addEventListener("versionchange",u=>o(u.oldVersion,u.newVersion,u))}).catch(()=>{}),c}var X1=["get","getKey","getAll","getAllKeys","count"],Y1=["put","add","delete","clear"],ic=new Map;function $h(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(ic.get(e))return ic.get(e);let r=e.replace(/FromIndex$/,""),n=e!==r,o=Y1.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||X1.includes(r)))return;let i=async function(s,...c){let a=this.transaction(s,o?"readwrite":"readonly"),u=a.store;return n&&(u=u.index(c.shift())),(await Promise.all([u[r](...c),o&&a.done]))[0]};return ic.set(e,i),i}zh(t=>({...t,get:(e,r,n)=>$h(e,r)||t.get(e,r,n),has:(e,r)=>!!$h(e,r)||t.has(e,r)}));var sc="0.13.4-dev";var jh=sc.match(/^([^.]*\.[^.]*)/);if(!jh)throw new Error("invalid version: "+sc);var $n=jh[0],ac=class{STORAGE_VERSION=$n;name;constructor(e){this.name=e}},On=class extends ac{tag="header-base";makeHeader({car:e,key:r}){return vi({car:e,key:r})}parseHeader(e){return Ei(e)}},zn=class{tag="car-base";STORAGE_VERSION=$n;loader;constructor(e){this.loader=e}};var Ai=class{tag="rwal-base";STORAGE_VERSION=$n;loader;ready;walState={operations:[],noLoaderOps:[],fileOperations:[]};processing=void 0;constructor(e){this.loader=e,this.ready=(async()=>{let r=await this.load().catch(n=>(console.error("error loading wal",n),null));this.walState.operations=r?.operations||[],this.walState.fileOperations=r?.fileOperations||[]})()}async enqueue(e,r){await this.ready,r.noLoader?this.walState.noLoaderOps.push(e):this.walState.operations.push(e),await this.save(this.walState),r.noLoader||this._process()}async enqueueFile(e,r=!1){await this.ready,this.walState.fileOperations.push({cid:e,public:r})}async _process(){if(await this.ready,!this.loader.remoteCarStore)return;if(this.processing)return this.processing;let e=(async()=>{await this._int_process()})();this.processing=e;try{await e}finally{this.processing=void 0}(this.walState.operations.length||this.walState.fileOperations.length||this.walState.noLoaderOps.length)&&setTimeout(()=>void this._process(),0)}async _int_process(){if(!this.loader.remoteCarStore)return;let e=(async()=>{let r=[...this.walState.operations],n=[...this.walState.fileOperations],o=[],i=[...this.walState.noLoaderOps],s=dn(5);if(r.length+n.length+i.length!==0){for(let c of i){let a=s(async()=>{let u=await this.loader.carStore.load(c.car).catch(()=>null);if(!u)throw new Error(`missing car ${c.car.toString()}`);await this.loader.remoteCarStore.save(u),this.walState.noLoaderOps=this.walState.noLoaderOps.filter(l=>l!==c)});o.push(a)}for(let c of r){let a=s(async()=>{let u=await this.loader.carStore.load(c.car).catch(()=>null);if(!u)throw new Error(`missing car ${c.car.toString()}`);await this.loader.remoteCarStore.save(u),this.walState.operations=this.walState.operations.filter(l=>l!==c)});o.push(a)}if(n.length){let c=this.loader;for(let{cid:a,public:u}of n){let l=s(async()=>{let d=await c.fileStore.load(a);await c.remoteFileStore?.save(d,{public:u}),this.walState.fileOperations=this.walState.fileOperations.filter(m=>m.cid!==a)});o.push(l)}}try{let a=(await Promise.allSettled(o)).filter(u=>u.status==="rejected");if(a.length)throw console.error("error uploading",a),a[0].reason;if(r.length){let u=r[r.length-1];await this.loader.remoteMetaStore?.save(u).catch(l=>{throw console.error("error saving remote meta",l),this.walState.operations.push(u),l})}}finally{await this.save(this.walState)}}})();this.loader.remoteMetaLoading=e,await e}};var Pr=class extends zn{tag="car-browser-idb";idb=null;async _withDB(e){if(!this.idb){let r=`fp.${this.STORAGE_VERSION}.${this.loader.keyId}.${this.loader.name}`;this.idb=await Hh(r,1,{upgrade(n){n.createObjectStore("cars")}})}return await e(this.idb)}async load(e){return await this._withDB(async r=>{let o=await r.transaction(["cars"],"readonly").objectStore("cars").get(e.toString());if(!o)throw new Error(`missing idb block ${e.toString()}`);return{cid:e,bytes:o}})}async save(e){return await this._withDB(async r=>{let n=r.transaction(["cars"],"readwrite");return await n.objectStore("cars").put(e.bytes,e.cid.toString()),await n.done})}async remove(e){return await this._withDB(async r=>{let n=r.transaction(["cars"],"readwrite");return await n.objectStore("cars").delete(e.toString()),await n.done})}},_i=class extends Ai{tag="wal-browser-ls";headerKey(e){return`fp.${this.STORAGE_VERSION}.wal.${this.loader.name}.${e}`}async load(e="main"){try{let r=localStorage.getItem(this.headerKey(e));return r?Ei(r):null}catch{return null}}async save(e,r="main"){try{let n=vi(e);localStorage.setItem(this.headerKey(r),n)}catch{}}},Bi=class extends On{tag="header-browser-ls";headerKey(e){return`fp.${this.STORAGE_VERSION}.meta.${this.name}.${e}`}async load(e="main"){try{let r=localStorage.getItem(this.headerKey(e));return r?[this.parseHeader(r)]:null}catch{return null}}async save(e,r="main"){try{let n=this.headerKey(r),o=this.makeHeader(e);return localStorage.setItem(n,o),null}catch{return null}}};function cc(t,e){return t.some(r=>r.equals(e))}function Vh(t,e=[]){let r=new Map;for(let n of t)cc(e,n)||r.set(n.toString(),n);return[...r.values()]}function qh(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Fr=class{name;opts={};remoteMetaLoading;remoteMetaStore;remoteCarStore;remoteWAL;metaStore;carStore;carLog=[];carReaders=new Map;ready;key;keyId;getBlockCache=new Map;static defaultHeader;constructor(e,r){this.name=e,this.opts=r||this.opts,this.metaStore=new Bi(this.name),this.carStore=new Pr(this),this.remoteWAL=new _i(this),this.ready=Promise.resolve().then(async()=>{if(!this.metaStore||!this.carStore||!this.remoteWAL)throw new Error("stores not initialized");let n=this.opts.meta?[this.opts.meta]:await this.metaStore.load("main");n&&await this.handleDbMetasFromStore(n)})}async snapToCar(e){await this.ready,typeof e=="string"&&(e=j.parse(e));let r=await this.loadCarHeaderFromMeta({car:e,key:this.key||null});this.carLog=[e,...r.cars],await this.getMoreReaders(r.cars),await this._applyCarHeader(r,!0)}async handleDbMetasFromStore(e){for(let r of e)await this.mergeDbMetaIntoClock(r)}async mergeDbMetaIntoClock(e){if(e.key&&await this.setKey(e.key),cc(this.carLog,e.car))return;let r=await this.loadCarHeaderFromMeta(e);await this.getMoreReaders(r.cars),this.carLog=[...Vh([e.car,...this.carLog,...r.cars],r.compact)],await this._applyCarHeader(r)}async ingestKeyFromMeta(e){let{key:r}=e;r&&await this.setKey(r)}async loadCarHeaderFromMeta({car:e}){let r=await this.loadCar(e);return await Ka(r)}async _getKey(){return this.key?this.key:(this.opts.public||(fi()?await this.setKey(qh(di(32))):console.warn("missing crypto module, using public mode")),this.key)}committing;async commit(e,r,n={noLoader:!1,compact:!1}){this.committing&&await this.committing,this.committing=this._commitInternal(e,r,n);let o=await this.committing;return this.committing=void 0,o}async _commitInternal(e,r,n={noLoader:!1,compact:!1}){await this.ready;let o=this.makeCarHeader(r,this.carLog,!!n.compact),i=[];if(o.files)i=o.files;else{let l=await Wa(o);await e.put(l.cid,l.bytes),i=[l.cid]}let s=n.public?null:await this._getKey(),{cid:c,bytes:a}=s?await Uh(s,i[0],e):await Pn(i,e);if(uc(r))return await this.fileStore.save({cid:c,bytes:a}),await this.remoteWAL.enqueueFile(c,n.public),c;await this.carStore.save({cid:c,bytes:a});let u={car:c,key:s||null};if(await this.remoteWAL.enqueue(u,n),await this.metaStore.save(u),n.compact){let l=o;this.carLog=[...Vh([c,...this.carLog],l.compact)],(async()=>{this.remoteMetaLoading&&await this.remoteMetaLoading;for(let d of l.compact)await this.carStore.remove(d)})()}else this.carLog.unshift(c);return c}async getBlock(e){await this.ready;let r=e.toString();if(this.getBlockCache.has(r))return this.getBlockCache.get(r);let n=await Promise.any(this.carLog.map(async o=>{let i=await this.loadCar(o);if(!i)throw new Error(`missing car reader ${o.toString()}`);let s=await i.get(e);if(s)return s;throw new Error(`block not in reader: ${e.toString()}`)})).catch(()=>{});return n&&this.getBlockCache.set(r,n),n}async loadCar(e){if(!this.carStore)throw new Error("car store not initialized");return await this.storesLoadCar(e,this.carStore,this.remoteCarStore)}async storesLoadCar(e,r,n,o){let i=e.toString();return this.carReaders.has(i)||this.carReaders.set(i,(async()=>{let s=null;try{s=await r.load(e)}catch{if(n){let l=await n.load(e);l&&(await r.save(l),s=l)}}if(!s)throw new Error(`missing car file ${i}`);let c=await Ar.fromBytes(s.bytes),a=o?Promise.resolve(c):this.ensureDecryptedReader(c);return this.carReaders.set(i,a),a})().catch(s=>{throw this.carReaders.delete(i),s})),this.carReaders.get(i)}async ensureDecryptedReader(e){let r=await this._getKey();if(!r)return e;let{blocks:n,root:o}=await Ph(r,e);return{getRoots:()=>[o],get:n.get.bind(n)}}async setKey(e){if(this.key&&this.key!==e)throw new Error("key mismatch");this.key=e;let r=fi();if(!r)throw new Error("missing crypto module");let n=r.subtle,i=new TextEncoder().encode(e),s=await n.digest("SHA-256",i),c=Array.from(new Uint8Array(s));this.keyId=c.map(a=>a.toString(16).padStart(2,"0")).join("")}async getMoreReaders(e){let r=dn(5),n=e.filter(o=>!this.carReaders.has(o.toString()));await Promise.all(n.map(o=>r(()=>this.loadCar(o))))}};var Mr=V(Xh(),1);var Ci=class extends $t{async identity(){let e=await this.codec.encode(await this.encodeNode()),r=await this.hasher.encode(e);return Mn(r)}},Ht=class extends Ci{constructor(e,r){super(e,r),this.value=e.value}encodeNode(){return[this.key,this.value]}},jt=class extends Ci{constructor(e,r){if(!e.address)throw new Error("Cannot create MapBranchEntry without address");super(e,r)}async encodeNode(){return[this.key,await this.address]}},Yh=async(t,e)=>{let{result:r,cids:n}=await t.getEntry(e);return{result:r.value,cids:n}},Zh=async(t,e)=>{let{result:r,cids:n}=await t.getEntries(e);return{result:r.map(o=>o.value),cids:n}},Vt=class extends Dr{get(e){return Yh(this,e)}getMany(e){return Zh(this,e)}bulk(e,r={},n=!0){return super.bulk(e,{...ep,...r},n)}},qt=class extends Lr{get(e){return Yh(this,e)}getMany(e){return Zh(this,e)}bulk(e,r={},n=!0){return super.bulk(e,{...ep,...r},n)}},ep={LeafClass:Vt,LeafEntryClass:Ht,BranchClass:qt,BranchEntryClass:jt},tp=(t,e,r,n,o,i,s)=>{let c=s.LeafClass||Vt,a=s.LeafEntryClass||Ht,u=s.BranchClass||qt,l=s.BranchEntryClass||jt,d=async f=>e.has(f)?e.get(f):t(f).then(h=>m(h)),m=sx({chunker:r,cache:e,getNode:d,codec:n,hasher:o,compare:i,LeafEntryClass:a,LeafClass:c,BranchEntryClass:l,BranchClass:u});return d},rp=({get:t,cache:e,chunker:r,list:n,codec:o,hasher:i,sorted:s,compare:c,...a})=>{s||(n=n.sort(({key:d},{key:m})=>c(d,m)));let u=tp(t,e,r,o,i,c,a),l={list:n,codec:o,hasher:i,chunker:r,getNode:u,sorted:s,compare:c,cache:e,LeafClass:a.LeafClass||Vt,LeafEntryClass:a.LeafEntryClass||Ht,BranchClass:a.BranchClass||qt,BranchEntryClass:a.BranchEntryClass||jt};return mi(l)},np=({cid:t,get:e,cache:r,chunker:n,codec:o,hasher:i,compare:s,...c})=>tp(e,r,n,o,i,s,c)(t);function sx({chunker:t,cache:e,getNode:r,codec:n,hasher:o,compare:i,LeafEntryClass:s,LeafClass:c,BranchEntryClass:a,BranchClass:u}){let l={codec:n,hasher:o};return d=>{let{value:m}=d,f={chunker:t,cache:e,block:d,getNode:r,codec:n,hasher:o,compare:i},h,p;if(m.leaf)h=m.leaf.map(([b,k])=>new s({key:b,value:k},l)),p=c;else if(m.branch){let[b,k]=m.branch;f.distance=b,h=k.map(([v,C])=>new a({key:v,address:C},l)),p=u}else throw new Error("Unknown block data, does not match schema");let w=new wt({entries:h,closed:m.closed}),g=new p({entryList:w,...f});return e.set(g),g}}var ax=(t,e)=>{let[r,n]=t,[o,i]=e,s=zt(r,o);return s!==0?s:cx(n,i)},cx=(t,e)=>{if(Number.isNaN(t))return-1;if(Number.isNaN(e))throw new Error("ref may not be Infinity or NaN");return Number.isFinite(t)?zt(t,e):1},op=async(t,e)=>{let r=[e,NaN],n=[e,1/0],{result:o,cids:i}=await t.getRangeEntries(r,n);return{result:o.map(s=>{let[c,a]=s.key;return{id:a,key:c,row:s.value}}),cids:i}},ip=async(t,e,r)=>{e=[e,NaN],r=[r,1/0];let{result:n,cids:o}=await t.getRangeEntries(e,r);return{result:n.map(s=>{let[c,a]=s.key;return{id:a,key:c,row:s.value}}),cids:o}},fc=class extends Vt{get(e){return op(this,e)}range(e,r){return ip(this,e,r)}bulk(e,r={},n=!0){return super.bulk(e,{...hc,...r},n)}},dc=class extends qt{get(e){return op(this,e)}range(e,r){return ip(this,e,r)}bulk(e,r={},n=!0){return super.bulk(e,{...hc,...r},n)}},ux=fc,lx=dc,hc={LeafClass:ux,BranchClass:lx,LeafEntryClass:Ht,BranchEntryClass:jt},sp={...hc,compare:ax},ap=t=>(t={...sp,...t},rp(t)),pc=t=>(t={...sp,...t},np(t));var Wt=class{cid=null;root=null},dx=(t,e)=>{if(Number.isNaN(t))return-1;if(Number.isNaN(e))throw new Error("ref may not be Infinity or NaN");return t===1/0?1:zt(t,e)},hx=(t,e)=>{let[r,n]=t,[o,i]=e,s=zt(r,o);return s!==0?s:dx(n,i)},mc={cache:Nr,chunker:Rn(30),codec:q,hasher:le,compare:hx},gc={cache:Nr,chunker:Rn(30),codec:q,hasher:le,compare:zt};function cp(t,e){let r=[];return t.forEach(({key:n,value:o,del:i})=>{if(i||!o)return;let s=!1,c=e({_id:n,...o},(a,u)=>{s=!0,!(typeof a>"u")&&r.push({key:[Mr.default.encode(a),n],value:u||null})});!s&&c&&r.push({key:[Mr.default.encode(c),n],value:null})}),r}function yc(t){return async e=>{let r=await t.get(e);if(!r)throw new Error(`Missing block ${e.toString()}`);let{cid:n,bytes:o}=r;return li({cid:n,bytes:o,hasher:le,codec:q})}}async function wc(t,e,r,n){if(!r.length)return e;if(!e.root)if(e.cid)e.root=await pc({cid:e.cid,get:yc(t),...n});else{let s=null,c=null;for await(let a of await ap({get:yc(t),list:r,...n})){let u=await a.block;await t.put(u.cid,u.bytes),s=u,c=a}if(!c||!s)throw new Error("failed to create index");return{root:c,cid:s.cid}}let{root:o,blocks:i}=await e.root.bulk(r);if(o){for await(let s of i)await t.put(s.cid,s.bytes);return{root:o,cid:(await o.block).cid}}else return{root:null,cid:null}}async function bc(t,e,r){return await pc({cid:e,get:yc(t),...r})}async function Kt(t,e,r){return r.descending&&(e.result=e.result.reverse()),r.limit&&(e.result=e.result.slice(0,r.limit)),r.includeDocs&&(e.result=await Promise.all(e.result.map(async n=>{let o=await t.get(n.id),i=o?{_id:n.id,...o.doc}:null;return{...n,doc:i}}))),{rows:e.result.map(n=>(n.key=Mr.default.decode(n.key),n.row&&!n.value&&(n.value=n.row,delete n.row),n))}}function xc(t){return t.map(e=>Mr.default.encode(e))}function kc(t){return Mr.default.encode(t)}function Rr({_crdt:t},e,r,n){if(r&&n)throw new Error("cannot provide both mapFn and meta");if(r&&r.constructor.name!=="Function")throw new Error("mapFn must be a function");if(t.indexers.has(e))t.indexers.get(e).applyMapFn(e,r,n);else{let o=new Ti(t,e,r,n);t.indexers.set(e,o)}return t.indexers.get(e)}var Ti=class{blocks;crdt;name=null;mapFn=null;mapFnString="";byKey=new Wt;byId=new Wt;indexHead=void 0;includeDocsDefault=!1;initError=null;ready;constructor(e,r,n,o){if(this.blocks=e.indexBlocks,this.crdt=e,this.applyMapFn(r,n,o),!(this.mapFnString||this.initError))throw new Error("missing mapFnString");this.ready=this.blocks.ready.then(()=>{})}applyMapFn(e,r,n){if(r&&n)throw new Error("cannot provide both mapFn and meta");if(this.name&&this.name!==e)throw new Error("cannot change name");this.name=e;try{if(n){if(this.indexHead&&this.indexHead.map(i=>i.toString()).join()!==n.head.map(i=>i.toString()).join())throw new Error("cannot apply meta to existing index");this.mapFnString?this.mapFnString!==n.map?console.log("cannot apply different mapFn meta: old mapFnString",this.mapFnString,"new mapFnString",n.map):(this.byId.cid=n.byId,this.byKey.cid=n.byKey,this.indexHead=n.head):(this.mapFnString=n.map,this.byId.cid=n.byId,this.byKey.cid=n.byKey,this.indexHead=n.head)}else if(this.mapFn){if(r&&this.mapFn.toString()!==r.toString())throw new Error("cannot apply different mapFn app2")}else{if(r||(r=px(e)),this.mapFnString){if(this.mapFnString!==r.toString())throw new Error("cannot apply different mapFn app")}else this.mapFnString=r.toString();this.mapFn=r}let o=/=>\s*(.*)/.test(this.mapFnString);this.includeDocsDefault=o}catch(o){this.initError=o}}async query(e={}){if(await this._updateIndex(),await this._hydrateIndex(),!this.byKey.root)return await Kt(this.crdt,{result:[]},e);if(this.includeDocsDefault&&e.includeDocs===void 0&&(e.includeDocs=!0),e.range){let{result:o,...i}=await this.byKey.root.range(...xc(e.range));return await Kt(this.crdt,{result:o,...i},e)}if(e.key){let o=kc(e.key);return await Kt(this.crdt,await this.byKey.root.get(o),e)}if(Array.isArray(e.keys))return{rows:(await Promise.all(e.keys.map(async i=>{let s=kc(i);return(await Kt(this.crdt,await this.byKey.root.get(s),e)).rows}))).flat()};if(e.prefix){Array.isArray(e.prefix)||(e.prefix=[e.prefix]);let o=[...e.prefix,NaN],i=[...e.prefix,1/0],s=xc([o,i]);return await Kt(this.crdt,await this.byKey.root.range(...s),e)}let{result:r,...n}=await this.byKey.root.getAllEntries();return await Kt(this.crdt,{result:r.map(({key:[o,i],value:s})=>({key:o,id:i,value:s})),...n},e)}_resetIndex(){this.byId=new Wt,this.byKey=new Wt,this.indexHead=void 0}async _hydrateIndex(){this.byId.root&&this.byKey.root||!this.byId.cid||!this.byKey.cid||(this.byId.root=await bc(this.blocks,this.byId.cid,gc),this.byKey.root=await bc(this.blocks,this.byKey.cid,mc))}async _updateIndex(){if(await this.ready,this.initError)throw this.initError;if(!this.mapFn)throw new Error("No map function defined");let e,r;if(!this.indexHead||this.indexHead.length===0?{result:e,head:r}=await this.crdt.allDocs():{result:e,head:r}=await this.crdt.changes(this.indexHead),e.length===0)return this.indexHead=r,{byId:this.byId,byKey:this.byKey};let n=[],o=[];if(this.byId.root){let a=e.map(({key:l})=>l),{result:u}=await this.byId.root.getMany(a);n=u.map(l=>({key:l,del:!0})),o=u.map(l=>({key:l[1],del:!0}))}let i=cp(e,this.mapFn),s=i.map(({key:a})=>({key:a[1],value:a})),c=new Map;for(let[a,u]of this.crdt.indexers)u.indexHead&&c.set(a,{byId:u.byId.cid,byKey:u.byKey.cid,head:u.indexHead,map:u.mapFnString,name:u.name});return await this.blocks.transaction(async a=>(this.byId=await wc(a,this.byId,o.concat(s),gc),this.byKey=await wc(a,this.byKey,n.concat(i),mc),this.indexHead=r,{byId:this.byId.cid,byKey:this.byKey.cid,head:r,map:this.mapFnString,name:this.name}),c)}};function px(t){return e=>{if(e[t])return e[t]}}var Ii=class t extends Fr{crdt;static defaultHeader={cars:[],compact:[],indexes:new Map};defaultHeader=t.defaultHeader;constructor(e,r,n){super(e,n),this.crdt=r}async _applyCarHeader(e){for(let[r,n]of Object.entries(e.indexes))Rr({_crdt:this.crdt},r,void 0,n)}makeCarHeader({indexes:e},r,n=!1){return n?{indexes:e,cars:[],compact:r}:{indexes:e,cars:r,compact:[]}}},Li=class t extends Fr{static defaultHeader={cars:[],compact:[],head:[]};defaultHeader=t.defaultHeader;clock;remoteFileStore;fileStore;constructor(e,r,n){super(e,n),this.fileStore=new Pr(this),this.clock=r}async loadFileCar(e,r=!1){return await this.storesLoadCar(e,this.fileStore,this.remoteFileStore,r)}async _applyCarHeader(e,r=!1){r?await this.clock.applyHead(null,e.head,this.clock.head):await this.clock.applyHead(null,e.head,[])}makeCarHeader(e,r,n=!1){if(uc(e)){let o=[];for(let[,i]of Object.entries(e.files))o.push(i.cid);return{files:o}}else{let{head:o}=e;return n?{head:o,cars:[],compact:r}:{head:o,cars:r,compact:[]}}}};function uc(t){return t&&t.files!==void 0}var xt=class extends Ae{parent;constructor(e){super(),this.parent=e}async get(e){return this.parent.get(e)}async superGet(e){return super.get(e)}},Di=class{ready;name=null;loader=null;opts={};transactions=new Set;constructor(e,r,n){if(this.opts=n||this.opts,e){if(this.name=e,!r)throw new Error("missing loader");this.loader=r,this.ready=this.loader.ready}else this.ready=Promise.resolve()}async put(){throw new Error("use a transaction to put")}async get(e){if(!e)throw new Error("required cid");for(let r of this.transactions){let n=await r.superGet(e);if(n)return n}if(this.loader)return await this.loader.getBlock(e)}async commitCompaction(e,r){return this.transactions.clear(),this.transactions.add(e),await this.loader?.commit(e,{head:r},{compact:!0})}async*entries(){let e=new Set;for(let r of this.transactions)for await(let n of r.entries())e.has(n.cid.toString())||(e.add(n.cid.toString()),yield n)}async executeTransaction(e,r){let n=new xt(this);this.transactions.add(n);let o=await e(n),{car:i,done:s}=await r(n,o);return i?{...s,car:i}:s}},Ni=class extends Di{constructor(e,r,n){e?super(e,new Ii(e,r,n),n):super(null)}async transaction(e,r){return this.executeTransaction(e,async(n,o)=>(r.set(o.name,o),{car:await this.loader?.commit(n,{indexes:r}),done:o}))}},Ui=class extends Di{constructor(e,r,n){e?super(e,new Li(e,r,n),n):super(null)}async transaction(e,r,n={noLoader:!1}){return this.executeTransaction(e,async(o,i)=>({car:await this.loader?.commit(o,i,n),done:i}))}},Pi=class{blocks;loader=null;cids=new Set;constructor(e){this.blocks=e,this.loader=e.loader}async get(e){return this.cids.add(e),await this.blocks.get(e)}};var Ec=({name:t,code:e,encode:r})=>new vc(t,e,r),vc=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Tt(this.code,r):r.then(n=>Tt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Fi({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*yx(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r],i=H.asCID(n);i?yield[o.join("/"),i]:typeof n=="object"&&(yield*Sc(n,o))}else{let r=H.asCID(e);r?yield[t.join("/"),r]:yield*Sc(e,t)}}function*Sc(t,e){if(t==null||t instanceof Uint8Array)return;let r=H.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,o]of Object.entries(t)){let i=[...e,n];yield*yx(i,o)}}function*mx(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r];yield o.join("/"),typeof n=="object"&&!H.asCID(n)&&(yield*Ac(n,o))}else yield*Ac(e,t)}function*Ac(t,e){if(!(t==null||typeof t!="object"))for(let[r,n]of Object.entries(t)){let o=[...e,r];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&!H.asCID(n)&&(yield*mx(o,n))}}function gx(t,e){let r=t;for(let[n,o]of e.entries()){if(r=r[o],r==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=H.asCID(r);if(i)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:r}}var Pe=class{constructor({cid:e,bytes:r,value:n}){if(!e||!r||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=r,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:Fi(),bytes:Fi(),value:Fi(),asBlock:Fi()})}links(){return Sc(this.value,[])}tree(){return Ac(this.value,[])}get(e="/"){return gx(this.value,e.split("/").filter(Boolean))}};async function Mi({value:t,codec:e,hasher:r}){if(typeof t>"u")throw new Error('Missing required argument "value"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.encode(t),o=await r.digest(n),i=H.create(1,e.code,o);return new Pe({value:t,bytes:n,cid:i})}async function Ri({bytes:t,codec:e,hasher:r}){if(!t)throw new Error('Missing required argument "bytes"');if(!e||!r)throw new Error("Missing required argument: codec or hasher");let n=e.decode(t),o=await r.digest(t),i=H.create(1,e.code,o);return new Pe({value:n,bytes:t,cid:i})}var Bc={};G(Bc,{sha256:()=>nt,sha512:()=>wx});var _c=V(require("crypto"),1);var nt=Ec({name:"sha2-256",code:18,encode:t=>Se(_c.default.createHash("sha256").update(t).digest())}),wx=Ec({name:"sha2-512",code:19,encode:t=>Se(_c.default.createHash("sha512").update(t).digest())});async function jn(t,e,r){let n=new We(t),o=new Map(e.map(s=>[s.toString(),s]));if(o.has(r.toString()))return e;let i=!1;for(let s of e)await lp(n,r,s)&&(o.delete(s.toString()),o.set(r.toString(),r),i=!0);if(i)return[...o.values()];for(let s of e)if(await lp(n,s,r))return e;return e.concat(r)}var Hn=class extends Pe{constructor({cid:e,value:r,bytes:n,prefix:o}){super({cid:e,value:r,bytes:n}),this.prefix=o}static create(e,r){return bx({data:e,parents:r??[]})}},We=class{constructor(e){this._blocks=e}async get(e){let r=await this._blocks.get(e);if(!r)throw new Error(`missing block: ${e}`);return xx(r.bytes)}};async function bx(t){let{cid:e,bytes:r}=await Mi({value:t,codec:q,hasher:nt});return new Pe({cid:e,value:t,bytes:r})}async function xx(t){let{cid:e,value:r}=await Ri({bytes:t,codec:q,hasher:nt});return new Pe({cid:e,value:r,bytes:t})}async function lp(t,e,r){if(e.toString()===r.toString())return!0;let[{value:n},{value:o}]=await Promise.all([t.get(e),t.get(r)]),i=[...n.parents],s=new Set;for(;i.length;){let c=i.shift();if(!c)break;if(c.toString()===r.toString())return!0;if(o.parents.some(u=>c.toString()===u.toString())||s.has(c.toString()))continue;s.add(c.toString());let{value:a}=await t.get(c);i.push(...a.parents)}return!1}async function*Cc(t,e,r={}){let n=r.renderNodeLabel??(a=>kx(a.cid)),o=new We(t);yield"digraph clock {",yield' node [shape=point fontname="Courier"]; head;';let i=await Promise.all(e.map(a=>o.get(a))),s=[],c=new Set;for(let a of i){c.add(a.cid.toString()),yield` node [shape=oval fontname="Courier"]; ${a.cid} [label="${n(a)}"];`,yield` head -> ${a.cid};`;for(let u of a.value.parents)yield` ${a.cid} -> ${u};`;s.push(...a.value.parents)}for(;s.length;){let a=s.shift();if(!a)break;if(c.has(a.toString()))continue;c.add(a.toString());let u=await o.get(a);yield` node [shape=oval]; ${a} [label="${n(u)}" fontname="Courier"];`;for(let l of u.value.parents)yield` ${a} -> ${l};`;s.push(...u.value.parents)}yield"}"}var kx=t=>`${String(t).slice(0,4)}..${String(t).slice(-4)}`;var Gt=class extends Pe{constructor({cid:e,value:r,bytes:n,prefix:o}){super({cid:e,value:r,bytes:n}),this.prefix=o}static create(){return Ke([])}};async function Ke(t,e){let{cid:r,bytes:n}=await Mi({value:t,codec:q,hasher:nt});return new Gt({cid:r,value:t,bytes:n,prefix:e??""})}async function fp(t,e){let{cid:r,value:n}=await Ri({bytes:t,codec:q,hasher:nt});if(!Array.isArray(n))throw new Error(`invalid shard: ${r}`);return new Gt({cid:r,value:n,bytes:t,prefix:e??""})}var Qt=class{constructor(e){this._blocks=e}async get(e,r=""){let n=await this._blocks.get(e);if(!n)throw new Error(`missing block: ${e}`);return fp(n.bytes,r)}};function Tc(t,e){if(!t.length)return[e];let r=[];for(let[n,[o,i]]of t.entries()){if(e[0]===o){if(Array.isArray(e[1]))Array.isArray(i)&&i[1]!=null&&e[1][1]==null?r.push([o,[e[1][0],i[1]]]):r.push(e);else{let s=Array.isArray(i)?[o,[i[0],e[1]]]:e;r.push(s)}for(let s=n+1;s<t.length;s++)r.push(t[s]);return r}if(n===0&&e[0]<o){r.push(e);for(let s=n;s<t.length;s++)r.push(t[s]);return r}if(n>0&&e[0]>t[n-1][0]&&e[0]<o){r.push(e);for(let s=n;s<t.length;s++)r.push(t[s]);return r}r.push([o,i])}return r.push(e),r}function dp(t,e){let r=t.findIndex(([i])=>e===i);if(r===-1)throw new Error(`key not found in shard: ${e}`);let n=r,o;for(;;){if(o=t[n][0].slice(0,-1),o.length)for(;;){let i=t.filter(s=>s[0].startsWith(o));if(i.length>1)return{prefix:o,matches:i};if(o=o.slice(0,-1),!o.length)break}if(n++,n>=t.length&&(n=0),n===r)return}}var Oi=64,Ex=512*1024;async function Vn(t,e,r,n,o={}){let i=new Qt(t),s=await i.get(e),c=await zi(i,s,r),a=c[c.length-1],u=r.slice(a.prefix.length),l=[u,n],d=[];if(u.length>Oi){let h=Array.from(Array(Math.ceil(u.length/Oi)),(w,g)=>{let b=g*Oi;return{prefix:a.prefix+u.slice(0,b),skey:u.slice(b,b+Oi)}}),p=await Ke([[h[h.length-1].skey,n]],h[h.length-1].prefix);d.push(p);for(let w=h.length-2;w>0;w--)p=await Ke([[h[w].skey,[p.cid]]],h[w].prefix),d.push(p);l=[h[0].skey,[p.cid]]}let m=Tc(a.value,l),f=await Ke(m,a.prefix);if(f.bytes.length>(o.maxShardSize??Ex)){let h=dp(m,l[0]);if(!h)throw new Error("shard limit reached");let{prefix:p,matches:w}=h,g=await Ke(w.filter(([v])=>v!==p).map(([v,C])=>[v.slice(p.length),C]),a.prefix+p);d.push(g);let b,k=w.find(([v])=>v===p);if(k){if(Array.isArray(k[1]))throw new Error(`expected "${p}" to be a shard value but found a shard link`);b=[g.cid,k[1]]}else b=[g.cid];m=m.filter(v=>w.every(C=>v[0]!==C[0])),m=Tc(m,[p,b]),f=await Ke(m,a.prefix)}d.push(f);for(let h=c.length-2;h>=0;h--){let p=c[h],w=f.prefix.slice(p.prefix.length),g=p.value.map(b=>{let[k,v]=b;if(k!==w)return b;if(!Array.isArray(v))throw new Error(`"${w}" is not a shard link in: ${p.cid}`);return v[1]==null?[k,[f.cid]]:[k,[f.cid,v[1]]]});f=await Ke(g,p.prefix),d.push(f)}return{root:d[d.length-1].cid,additions:d,removals:c}}async function hp(t,e,r){let n=new Qt(t),o=await n.get(e),i=await zi(n,o,r),s=i[i.length-1],c=r.slice(s.prefix.length),a=s.value.find(([u])=>u===c);if(a)return Array.isArray(a[1])?a[1][1]:a[1]}async function Ic(t,e,r){let n=new Qt(t),o=await n.get(e),i=await zi(n,o,r),s=i[i.length-1],c=r.slice(s.prefix.length),a=s.value.findIndex(([h])=>h===c);if(a===-1)return{root:e,additions:[],removals:[]};let u=s.value[a];if(Array.isArray(u[1])&&u[1][1]==null)return{root:e,additions:[],removals:[]};let l=[],d=[...i],m=[...s.value];if(Array.isArray(u[1]))m[a]=[u[0],[u[1][0]]];else for(m.splice(a,1);!m.length;){let h=i[i.length-1],p=i[i.length-2];if(!p)break;i.pop(),m=p.value.filter(w=>Array.isArray(w[1])?w[1][0].toString()!==h.cid.toString():!0)}let f=await Ke(m,i[i.length-1].prefix);l.push(f);for(let h=i.length-2;h>=0;h--){let p=i[h],w=f.prefix.slice(p.prefix.length),g=p.value.map(b=>{let[k,v]=b;if(k!==w)return b;if(!Array.isArray(v))throw new Error(`"${w}" is not a shard link in: ${p.cid}`);return v[1]==null?[k,[f.cid]]:[k,[f.cid,v[1]]]});f=await Ke(g,p.prefix),l.push(f)}return{root:l[l.length-1].cid,additions:l,removals:d}}async function*pp(t,e,r={}){let{prefix:n}=r,o=new Qt(t),i=await o.get(e);yield*async function*s(c){for(let a of c.value){let u=c.prefix+a[0];if(Array.isArray(a[1])){if(a[1][1]&&(!n||n&&u.startsWith(n))&&(yield[u,a[1][1]]),n&&(n.length<=u.length&&!u.startsWith(n)||n.length>u.length&&!n.startsWith(u)))continue;yield*s(await o.get(a[1][0],u))}else{if(n&&!u.startsWith(n))continue;yield[u,a[1]]}}}(i)}async function zi(t,e,r){for(let[n,o]of e.value){if(r===n)return[e];if(r.startsWith(n)&&Array.isArray(o)){let i=await zi(t,await t.get(o[0],e.prefix+n),r.slice(n.length));return[e,...i]}}return[e]}async function yp(t,e,r,n,o){let i=new Ae;if(t=new Lt(i,t),!e.length){let g=await Gt.create();i.putSync(g.cid,g.bytes);let b=await Vn(t,g.cid,r,n,o),k={type:"put",root:b.root,key:r,value:n},v=await Hn.create(k,e);return e=await jn(t,e,v.cid),{root:b.root,additions:[g,...b.additions],removals:b.removals,head:e,event:v}}let s=new We(t),c=await Dc(s,e);if(!c)throw new Error("failed to find common ancestor event");let a=await s.get(c),{root:u}=a.value.data,l=await gp(s,e,c),d=new Map,m=new Map;for(let{value:g}of l){if(!["put","del"].includes(g.data.type))throw new Error(`unknown event type: ${g.data.type}`);let b=g.data.type==="put"?await Vn(t,u,g.data.key,g.data.value):await Ic(t,u,g.data.key);u=b.root;for(let k of b.additions)i.putSync(k.cid,k.bytes),d.set(k.cid.toString(),k);for(let k of b.removals)m.set(k.cid.toString(),k)}let f=await Vn(t,u,r,n,o);for(let g of f.additions)i.putSync(g.cid,g.bytes),d.set(g.cid.toString(),g);for(let g of f.removals)m.set(g.cid.toString(),g);let h={type:"put",root:f.root,key:r,value:n},p=await Hn.create(h,e);i.putSync(p.cid,p.bytes),e=await jn(t,e,p.cid);let w=f.root.toString();for(let g of m.keys())d.has(g)&&g!==w&&(d.delete(g),m.delete(g));return{root:f.root,additions:[...d.values()],removals:[...m.values()],head:e,event:p}}async function Or(t,e){if(!e.length)throw new Error("cannot determine root of headless clock");let r=new Ae;t=new Lt(r,t);let n=new We(t);if(e.length===1){let d=await n.get(e[0]),{root:m}=d.value.data;return{root:m,additions:[],removals:[]}}let o=await Dc(n,e);if(!o)throw new Error("failed to find common ancestor event");let i=await n.get(o),{root:s}=i.value.data,c=await gp(n,e,o),a=new Map,u=new Map;for(let{value:d}of c){if(!["put","del"].includes(d.data.type))throw new Error(`unknown event type: ${d.data.type}`);let m=d.data.type==="put"?await Vn(t,s,d.data.key,d.data.value):await Ic(t,s,d.data.key);s=m.root;for(let f of m.additions)r.putSync(f.cid,f.bytes),a.set(f.cid.toString(),f);for(let f of m.removals)u.set(f.cid.toString(),f)}let l=s.toString();for(let d of u.keys())a.has(d)&&d!==l&&(a.delete(d),u.delete(d));return{root:s,additions:[...a.values()],removals:[...u.values()]}}async function mp(t,e,r){if(!e.length)return;let n=await Or(t,e);return n.additions.length&&(t=new Lt(new Ae(n.additions),t)),hp(t,n.root,r)}async function*Lc(t,e,r){if(!e.length)return;let n=await Or(t,e);n.additions.length&&(t=new Lt(new Ae(n.additions),t)),yield*pp(t,n.root,r)}async function Dc(t,e){if(!e.length)return;let r=e.map(n=>[n]);for(;;){let n=!1;for(let o of r){let i=await Ax(t,o[o.length-1]);if(!i)continue;n=!0,o.push(i);let s=_x(r);if(s)return s}if(!n)return}}async function Ax(t,e){let{value:r}=await t.get(e);return r.parents.length?r.parents.length===1?r.parents[0]:Dc(t,r.parents):e}function _x(t){t=t.map(e=>[...e]);for(let e of t)for(let r of e){let n=!0;for(let o of t)if(e!==o&&(n=o.some(i=>String(i)===String(r)),!n))break;if(n)return r}}async function gp(t,e,r){if(e.length===1&&String(e[0])===String(r))return[];let n=new Map,o=await Promise.all(e.map(s=>wp(t,s,r)));for(let s of o)for(let{event:c,depth:a}of s){let u=n.get(c.cid.toString());u?u.weight+=a:n.set(c.cid.toString(),{event:c,weight:a})}let i=new Map;for(let{event:s,weight:c}of n.values()){let a=i.get(c);a?a.push(s):i.set(c,[s])}return Array.from(i).sort((s,c)=>c[0]-s[0]).flatMap(([,s])=>s.sort((c,a)=>String(c.cid)<String(a.cid)?-1:1))}async function wp(t,e,r,n=0){let o=await t.get(e),i=[{event:o,depth:n}],{parents:s}=o.value;if(s.length===1&&String(s[0])===String(r))return i;let c=await Promise.all(s.map(a=>wp(t,a,r,n+1)));return i.concat(...c)}var Wr={};G(Wr,{DEFAULT_DIRECTORY_MODE:()=>By,DEFAULT_FILE_MODE:()=>_y,NodeType:()=>P,code:()=>Vr,createAdvancedFile:()=>Qx,createComplexFile:()=>Xx,createDirectoryShard:()=>Ly,createEmptyFile:()=>Kx,createFileChunk:()=>Gx,createFileShard:()=>Jx,createFlatDirectory:()=>Yi,createRaw:()=>Cy,createShardedDirectory:()=>Iy,createSimpleFile:()=>Ty,createSymlink:()=>Ny,cumulativeContentByteLength:()=>Xe,cumulativeDagByteLength:()=>qr,decode:()=>Fy,decodeMetadata:()=>Zt,encode:()=>Py,encodeAdvancedFile:()=>eu,encodeComplexFile:()=>tu,encodeDirectory:()=>ts,encodeDirectoryMetadata:()=>iu,encodeFile:()=>Dy,encodeFileChunk:()=>Zc,encodeFileShard:()=>Yx,encodeHAMTShard:()=>ru,encodeLink:()=>Zi,encodeMetadata:()=>Jn,encodeMode:()=>Ry,encodeRaw:()=>Yc,encodeSimpleFile:()=>es,encodeSymlink:()=>Uy,filesize:()=>rk,matchFile:()=>tk,name:()=>Xc});var Bx=new TextDecoder;function Nc(t,e){let r=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=t.length)throw new Error("protobuf: unexpected end of data");let o=t[e++];if(r+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[r,e]}function $i(t,e){let r;[r,e]=Nc(t,e);let n=e+r;if(r<0||n<0)throw new Error("protobuf: invalid length");if(n>t.length)throw new Error("protobuf: unexpected end of data");return[t.subarray(e,n),n]}function bp(t,e){let r;return[r,e]=Nc(t,e),[r&7,r>>3,e]}function Cx(t){let e={},r=t.length,n=0;for(;n<r;){let o,i;if([o,i,n]=bp(t,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=$i(t,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=$i(t,n),e.Name=Bx.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=Nc(t,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>r)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function xp(t){let e=t.length,r=0,n,o=!1,i;for(;r<e;){let c,a;if([c,a,r]=bp(t,r),c!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${c}`);if(a===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,r]=$i(t,r),n&&(o=!0)}else if(a===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let u;[u,r]=$i(t,r),n.push(Cx(u))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${a}`)}if(r>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var vp=new TextEncoder,kp=2**32,Tx=2**31;function Ix(t,e){let r=e.length;if(typeof t.Tsize=="number"){if(t.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(t.Tsize))throw new Error("Tsize too large for encoding");r=qn(e,r,t.Tsize)-1,e[r]=24}if(typeof t.Name=="string"){let n=vp.encode(t.Name);r-=n.length,e.set(n,r),r=qn(e,r,n.length)-1,e[r]=18}return t.Hash&&(r-=t.Hash.length,e.set(t.Hash,r),r=qn(e,r,t.Hash.length)-1,e[r]=10),e.length-r}function Ep(t){let e=Dx(t),r=new Uint8Array(e),n=e;if(t.Data&&(n-=t.Data.length,r.set(t.Data,n),n=qn(r,n,t.Data.length)-1,r[n]=10),t.Links)for(let o=t.Links.length-1;o>=0;o--){let i=Ix(t.Links[o],r.subarray(0,n));n-=i,n=qn(r,n,i)-1,r[n]=18}return r}function Lx(t){let e=0;if(t.Hash){let r=t.Hash.length;e+=1+r+zr(r)}if(typeof t.Name=="string"){let r=vp.encode(t.Name).length;e+=1+r+zr(r)}return typeof t.Tsize=="number"&&(e+=1+zr(t.Tsize)),e}function Dx(t){let e=0;if(t.Data){let r=t.Data.length;e+=1+r+zr(r)}if(t.Links)for(let r of t.Links){let n=Lx(r);e+=1+n+zr(n)}return e}function qn(t,e,r){e-=zr(r);let n=e;for(;r>=Tx;)t[e++]=r&127|128,r/=128;for(;r>=128;)t[e++]=r&127|128,r>>>=7;return t[e]=r,n}function zr(t){return t%2===0&&t++,Math.floor((Nx(t)+6)/7)}function Nx(t){let e=0;return t>=kp&&(t=Math.floor(t/kp),e=32),t>=65536&&(t>>>=16,e+=16),t>=256&&(t>>>=8,e+=8),e+Ux[t]}var Ux=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var Px=["Data","Links"],Fx=["Hash","Name","Tsize"],Uc=new TextEncoder;function Ap(t,e){if(t===e)return 0;let r=t.Name?Uc.encode(t.Name):[],n=e.Name?Uc.encode(e.Name):[],o=r.length,i=n.length;for(let s=0,c=Math.min(o,i);s<c;++s)if(r[s]!==n[s]){o=r[s],i=n[s];break}return o<i?-1:i<o?1:0}function Sp(t,e){return!Object.keys(t).some(r=>!e.includes(r))}function Mx(t){if(typeof t.asCID=="object"){let r=H.asCID(t);if(!r)throw new TypeError("Invalid DAG-PB form");return{Hash:r}}if(typeof t!="object"||Array.isArray(t))throw new TypeError("Invalid DAG-PB form");let e={};if(t.Hash){let r=H.asCID(t.Hash);try{r||(typeof t.Hash=="string"?r=H.parse(t.Hash):t.Hash instanceof Uint8Array&&(r=H.decode(t.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}r&&(e.Hash=r)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof t.Name=="string"&&(e.Name=t.Name),typeof t.Tsize=="number"&&(e.Tsize=t.Tsize),e}function Pc(t){if((t instanceof Uint8Array||typeof t=="string")&&(t={Data:t}),typeof t!="object"||Array.isArray(t))throw new TypeError("Invalid DAG-PB form");let e={};if(t.Data!==void 0)if(typeof t.Data=="string")e.Data=Uc.encode(t.Data);else if(t.Data instanceof Uint8Array)e.Data=t.Data;else throw new TypeError("Invalid DAG-PB form");if(t.Links!==void 0)if(Array.isArray(t.Links))e.Links=t.Links.map(Mx),e.Links.sort(Ap);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function _p(t){if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form");if(!Sp(t,Px))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(t.Data!==void 0&&!(t.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(t.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<t.Links.length;e++){let r=t.Links[e];if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!Sp(r,Fx))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(r.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(r.Hash==null||!r.Hash["/"]||r.Hash["/"]!==r.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(r.Name!==void 0&&typeof r.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(r.Tsize!==void 0){if(typeof r.Tsize!="number"||r.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(r.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&Ap(r,t.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}var Jt=112;function Bp(t){_p(t);let e={};return t.Links&&(e.Links=t.Links.map(r=>{let n={};return r.Hash&&(n.Hash=r.Hash.bytes),r.Name!==void 0&&(n.Name=r.Name),r.Tsize!==void 0&&(n.Tsize=r.Tsize),n})),t.Data&&(e.Data=t.Data),Ep(e)}function Ge(t){let e=xp(t),r={};return e.Data&&(r.Data=e.Data),e.Links&&(r.Links=e.Links.map(n=>{let o={};try{o.Hash=H.decode(n.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return n.Name!==void 0&&(o.Name=n.Name),n.Tsize!==void 0&&(o.Tsize=n.Tsize),o})),r}var it=V(vy(),1),Hr=it.default.Reader,Qc=it.default.Writer,D=it.default.util,ne=it.default.roots.unixfs||(it.default.roots.unixfs={}),jr=ne.Data=(()=>{function t(e){if(this.blocksizes=[],e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.Type=0,t.prototype.Data=D.newBuffer([]),t.prototype.filesize=D.Long?D.Long.fromBits(0,0,!0):0,t.prototype.blocksizes=D.emptyArray,t.prototype.hashType=D.Long?D.Long.fromBits(0,0,!0):0,t.prototype.fanout=D.Long?D.Long.fromBits(0,0,!0):0,t.prototype.mode=0,t.prototype.mtime=null,t.encode=function(r,n){if(n||(n=Qc.create()),n.uint32(8).int32(r.Type),r.Data!=null&&Object.hasOwnProperty.call(r,"Data")&&n.uint32(18).bytes(r.Data),r.filesize!=null&&Object.hasOwnProperty.call(r,"filesize")&&n.uint32(24).uint64(r.filesize),r.blocksizes!=null&&r.blocksizes.length)for(var o=0;o<r.blocksizes.length;++o)n.uint32(32).uint64(r.blocksizes[o]);return r.hashType!=null&&Object.hasOwnProperty.call(r,"hashType")&&n.uint32(40).uint64(r.hashType),r.fanout!=null&&Object.hasOwnProperty.call(r,"fanout")&&n.uint32(48).uint64(r.fanout),r.mode!=null&&Object.hasOwnProperty.call(r,"mode")&&n.uint32(56).uint32(r.mode),r.mtime!=null&&Object.hasOwnProperty.call(r,"mtime")&&ne.UnixTime.encode(r.mtime,n.uint32(66).fork()).ldelim(),n},t.decode=function(r,n){r instanceof Hr||(r=Hr.create(r));for(var o=n===void 0?r.len:r.pos+n,i=new ne.Data;r.pos<o;){var s=r.uint32();switch(s>>>3){case 1:i.Type=r.int32();break;case 2:i.Data=r.bytes();break;case 3:i.filesize=r.uint64();break;case 4:if(i.blocksizes&&i.blocksizes.length||(i.blocksizes=[]),(s&7)===2)for(var c=r.uint32()+r.pos;r.pos<c;)i.blocksizes.push(r.uint64());else i.blocksizes.push(r.uint64());break;case 5:i.hashType=r.uint64();break;case 6:i.fanout=r.uint64();break;case 7:i.mode=r.uint32();break;case 8:i.mtime=ne.UnixTime.decode(r,r.uint32());break;default:r.skipType(s&7);break}}if(!i.hasOwnProperty("Type"))throw D.ProtocolError("missing required 'Type'",{instance:i});return i},t.fromObject=function(r){if(r instanceof ne.Data)return r;var n=new ne.Data;switch(r.Type){case"Raw":case 0:n.Type=0;break;case"Directory":case 1:n.Type=1;break;case"File":case 2:n.Type=2;break;case"Metadata":case 3:n.Type=3;break;case"Symlink":case 4:n.Type=4;break;case"HAMTShard":case 5:n.Type=5;break}if(r.Data!=null&&(typeof r.Data=="string"?D.base64.decode(r.Data,n.Data=D.newBuffer(D.base64.length(r.Data)),0):r.Data.length&&(n.Data=r.Data)),r.filesize!=null&&(D.Long?(n.filesize=D.Long.fromValue(r.filesize)).unsigned=!0:typeof r.filesize=="string"?n.filesize=parseInt(r.filesize,10):typeof r.filesize=="number"?n.filesize=r.filesize:typeof r.filesize=="object"&&(n.filesize=new D.LongBits(r.filesize.low>>>0,r.filesize.high>>>0).toNumber(!0))),r.blocksizes){if(!Array.isArray(r.blocksizes))throw TypeError(".Data.blocksizes: array expected");n.blocksizes=[];for(var o=0;o<r.blocksizes.length;++o)D.Long?(n.blocksizes[o]=D.Long.fromValue(r.blocksizes[o])).unsigned=!0:typeof r.blocksizes[o]=="string"?n.blocksizes[o]=parseInt(r.blocksizes[o],10):typeof r.blocksizes[o]=="number"?n.blocksizes[o]=r.blocksizes[o]:typeof r.blocksizes[o]=="object"&&(n.blocksizes[o]=new D.LongBits(r.blocksizes[o].low>>>0,r.blocksizes[o].high>>>0).toNumber(!0))}if(r.hashType!=null&&(D.Long?(n.hashType=D.Long.fromValue(r.hashType)).unsigned=!0:typeof r.hashType=="string"?n.hashType=parseInt(r.hashType,10):typeof r.hashType=="number"?n.hashType=r.hashType:typeof r.hashType=="object"&&(n.hashType=new D.LongBits(r.hashType.low>>>0,r.hashType.high>>>0).toNumber(!0))),r.fanout!=null&&(D.Long?(n.fanout=D.Long.fromValue(r.fanout)).unsigned=!0:typeof r.fanout=="string"?n.fanout=parseInt(r.fanout,10):typeof r.fanout=="number"?n.fanout=r.fanout:typeof r.fanout=="object"&&(n.fanout=new D.LongBits(r.fanout.low>>>0,r.fanout.high>>>0).toNumber(!0))),r.mode!=null&&(n.mode=r.mode>>>0),r.mtime!=null){if(typeof r.mtime!="object")throw TypeError(".Data.mtime: object expected");n.mtime=ne.UnixTime.fromObject(r.mtime)}return n},t.toObject=function(r,n){n||(n={});var o={};if((n.arrays||n.defaults)&&(o.blocksizes=[]),n.defaults){if(o.Type=n.enums===String?"Raw":0,n.bytes===String?o.Data="":(o.Data=[],n.bytes!==Array&&(o.Data=D.newBuffer(o.Data))),D.Long){var i=new D.Long(0,0,!0);o.filesize=n.longs===String?i.toString():n.longs===Number?i.toNumber():i}else o.filesize=n.longs===String?"0":0;if(D.Long){var i=new D.Long(0,0,!0);o.hashType=n.longs===String?i.toString():n.longs===Number?i.toNumber():i}else o.hashType=n.longs===String?"0":0;if(D.Long){var i=new D.Long(0,0,!0);o.fanout=n.longs===String?i.toString():n.longs===Number?i.toNumber():i}else o.fanout=n.longs===String?"0":0;o.mode=0,o.mtime=null}if(r.Type!=null&&r.hasOwnProperty("Type")&&(o.Type=n.enums===String?ne.Data.DataType[r.Type]:r.Type),r.Data!=null&&r.hasOwnProperty("Data")&&(o.Data=n.bytes===String?D.base64.encode(r.Data,0,r.Data.length):n.bytes===Array?Array.prototype.slice.call(r.Data):r.Data),r.filesize!=null&&r.hasOwnProperty("filesize")&&(typeof r.filesize=="number"?o.filesize=n.longs===String?String(r.filesize):r.filesize:o.filesize=n.longs===String?D.Long.prototype.toString.call(r.filesize):n.longs===Number?new D.LongBits(r.filesize.low>>>0,r.filesize.high>>>0).toNumber(!0):r.filesize),r.blocksizes&&r.blocksizes.length){o.blocksizes=[];for(var s=0;s<r.blocksizes.length;++s)typeof r.blocksizes[s]=="number"?o.blocksizes[s]=n.longs===String?String(r.blocksizes[s]):r.blocksizes[s]:o.blocksizes[s]=n.longs===String?D.Long.prototype.toString.call(r.blocksizes[s]):n.longs===Number?new D.LongBits(r.blocksizes[s].low>>>0,r.blocksizes[s].high>>>0).toNumber(!0):r.blocksizes[s]}return r.hashType!=null&&r.hasOwnProperty("hashType")&&(typeof r.hashType=="number"?o.hashType=n.longs===String?String(r.hashType):r.hashType:o.hashType=n.longs===String?D.Long.prototype.toString.call(r.hashType):n.longs===Number?new D.LongBits(r.hashType.low>>>0,r.hashType.high>>>0).toNumber(!0):r.hashType),r.fanout!=null&&r.hasOwnProperty("fanout")&&(typeof r.fanout=="number"?o.fanout=n.longs===String?String(r.fanout):r.fanout:o.fanout=n.longs===String?D.Long.prototype.toString.call(r.fanout):n.longs===Number?new D.LongBits(r.fanout.low>>>0,r.fanout.high>>>0).toNumber(!0):r.fanout),r.mode!=null&&r.hasOwnProperty("mode")&&(o.mode=r.mode),r.mtime!=null&&r.hasOwnProperty("mtime")&&(o.mtime=ne.UnixTime.toObject(r.mtime,n)),o},t.prototype.toJSON=function(){return this.constructor.toObject(this,it.default.util.toJSONOptions)},t.DataType=function(){let e={},r=Object.create(e);return r[e[0]="Raw"]=0,r[e[1]="Directory"]=1,r[e[2]="File"]=2,r[e[3]="Metadata"]=3,r[e[4]="Symlink"]=4,r[e[5]="HAMTShard"]=5,r}(),t})(),h3=ne.UnixTime=(()=>{function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.Seconds=D.Long?D.Long.fromBits(0,0,!1):0,t.prototype.FractionalNanoseconds=0,t.encode=function(r,n){return n||(n=Qc.create()),n.uint32(8).int64(r.Seconds),r.FractionalNanoseconds!=null&&Object.hasOwnProperty.call(r,"FractionalNanoseconds")&&n.uint32(21).fixed32(r.FractionalNanoseconds),n},t.decode=function(r,n){r instanceof Hr||(r=Hr.create(r));for(var o=n===void 0?r.len:r.pos+n,i=new ne.UnixTime;r.pos<o;){var s=r.uint32();switch(s>>>3){case 1:i.Seconds=r.int64();break;case 2:i.FractionalNanoseconds=r.fixed32();break;default:r.skipType(s&7);break}}if(!i.hasOwnProperty("Seconds"))throw D.ProtocolError("missing required 'Seconds'",{instance:i});return i},t.fromObject=function(r){if(r instanceof ne.UnixTime)return r;var n=new ne.UnixTime;return r.Seconds!=null&&(D.Long?(n.Seconds=D.Long.fromValue(r.Seconds)).unsigned=!1:typeof r.Seconds=="string"?n.Seconds=parseInt(r.Seconds,10):typeof r.Seconds=="number"?n.Seconds=r.Seconds:typeof r.Seconds=="object"&&(n.Seconds=new D.LongBits(r.Seconds.low>>>0,r.Seconds.high>>>0).toNumber())),r.FractionalNanoseconds!=null&&(n.FractionalNanoseconds=r.FractionalNanoseconds>>>0),n},t.toObject=function(r,n){n||(n={});var o={};if(n.defaults){if(D.Long){var i=new D.Long(0,0,!1);o.Seconds=n.longs===String?i.toString():n.longs===Number?i.toNumber():i}else o.Seconds=n.longs===String?"0":0;o.FractionalNanoseconds=0}return r.Seconds!=null&&r.hasOwnProperty("Seconds")&&(typeof r.Seconds=="number"?o.Seconds=n.longs===String?String(r.Seconds):r.Seconds:o.Seconds=n.longs===String?D.Long.prototype.toString.call(r.Seconds):n.longs===Number?new D.LongBits(r.Seconds.low>>>0,r.Seconds.high>>>0).toNumber():r.Seconds),r.FractionalNanoseconds!=null&&r.hasOwnProperty("FractionalNanoseconds")&&(o.FractionalNanoseconds=r.FractionalNanoseconds),o},t.prototype.toJSON=function(){return this.constructor.toObject(this,it.default.util.toJSONOptions)},t})(),p3=ne.Metadata=(()=>{function t(e){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)e[r[n]]!=null&&(this[r[n]]=e[r[n]])}return t.prototype.MimeType="",t.encode=function(r,n){return n||(n=Qc.create()),r.MimeType!=null&&Object.hasOwnProperty.call(r,"MimeType")&&n.uint32(10).string(r.MimeType),n},t.decode=function(r,n){r instanceof Hr||(r=Hr.create(r));for(var o=n===void 0?r.len:r.pos+n,i=new ne.Metadata;r.pos<o;){var s=r.uint32();switch(s>>>3){case 1:i.MimeType=r.string();break;default:r.skipType(s&7);break}}return i},t.fromObject=function(r){if(r instanceof ne.Metadata)return r;var n=new ne.Metadata;return r.MimeType!=null&&(n.MimeType=String(r.MimeType)),n},t.toObject=function(r,n){n||(n={});var o={};return n.defaults&&(o.MimeType=""),r.MimeType!=null&&r.hasOwnProperty("MimeType")&&(o.MimeType=r.MimeType),o},t.prototype.toJSON=function(){return this.constructor.toObject(this,it.default.util.toJSONOptions)},t})();var P=jr.DataType;var Ay=Object.freeze([]),Jc=new Uint8Array(0),ke=Object.freeze({}),_y=parseInt("0644",8),By=parseInt("0755",8),Vr=Jt,Xc="UnixFS",Et=(t,e)=>(Object(globalThis).debug&&console.log({data:t,links:e}),Bp(Pc({Data:jr.encode(t).finish(),Links:e}))),Cy=t=>({type:P.Raw,content:t}),Kx=t=>Ty(Jc,t),Ty=(t,e)=>({type:P.File,layout:"simple",content:t,metadata:Zt(e)}),Gx=t=>({type:P.File,layout:"simple",content:t}),Qx=(t,e)=>({type:P.File,layout:"advanced",parts:t,metadata:Zt(e)}),Jx=t=>({type:P.File,layout:"advanced",parts:t}),Xx=(t,e,r)=>({type:P.File,layout:"complex",content:t,parts:e,metadata:Zt(r)}),Yi=(t,e)=>({type:P.Directory,metadata:Zt(e),entries:t}),Iy=(t,e,r,n,o=ke)=>({type:P.HAMTShard,bitfield:e,fanout:nu(r),hashType:ou(n),entries:t,metadata:Zt(o)}),Ly=(t,e,r,n)=>({type:P.HAMTShard,bitfield:e,fanout:nu(r),hashType:ou(n),entries:t}),Yc=t=>Et({Type:P.Raw,Data:t.byteLength>0?t:void 0,filesize:t.byteLength,blocksizes:Ay},[]),Dy=(t,e=!1)=>{let r=e?ke:Object(t).metadata;switch(t.layout){case"simple":return es(t.content,r);case"advanced":return eu(t.parts,r);case"complex":return tu(t.content,t.parts,r);default:throw new TypeError(`File with unknown layout "${Object(t).layout}" was passed`)}},Zc=t=>es(t,ke),Yx=t=>Et({Type:P.File,blocksizes:t.map(Qn),filesize:Xe(t)},t.map(Zi)),eu=(t,e=ke)=>Et({Type:P.File,blocksizes:t.map(Qn),filesize:Xe(t),...Jn(e)},t.map(Zi)),Zi=t=>({Name:"",Tsize:t.dagByteLength,Hash:t.cid}),es=(t,e=ke)=>Et({Type:P.File,Data:t.byteLength>0?t:void 0,filesize:t.byteLength,blocksizes:[],...Jn(e)},[]),tu=(t,e,r=ke)=>Et({Type:P.File,Data:t,filesize:t.byteLength+Xe(e),blocksizes:e.map(Qn)},e.map(Zi)),ts=t=>Et({Type:t.type,...iu(t.metadata||ke)},t.entries.map(My)),ru=({bitfield:t,fanout:e,hashType:r,entries:n,metadata:o=ke})=>Et({Type:P.HAMTShard,Data:t.byteLength>0?t:void 0,fanout:nu(e),hashType:ou(r),...iu(o)},n.map(My)),nu=t=>{if(Math.log2(t)%1===0)return t;throw new TypeError(`Expected hamt size to be a power of two instead got ${t}`)},ou=t=>{if(Number.isInteger(t))return t;throw new TypeError(`Expected an integer value instead got ${t}`)};var Ny=(t,e=ke)=>({type:P.Symlink,content:t,metadata:Zt(e)}),Uy=(t,e=!1)=>{let r=e?ke:Object(t).metadata;return Et({Type:P.Symlink,Data:t.content,...Jn(r||ke)},[])},Py=(t,e=!0)=>{switch(t.type){case P.Raw:return Yc(t.content);case P.File:return Dy(t);case P.Directory:return ts(t);case P.HAMTShard:return ru(t);case P.Symlink:return Uy(t);default:throw new Error(`Unknown node type ${Object(t).type}`)}},Fy=t=>{let e=Ge(t),r=jr.decode(e.Data),{Type:n,Data:o,mtime:i,mode:s,blocksizes:c,...a}=jr.toObject(r,{defaults:!1,arrays:!0,longs:Number,objects:!1}),u={...s&&{mode:s},...Zx(i)},l=e.Links;switch(r.Type){case P.Raw:return Cy(o);case P.File:return l.length===0?new Qi(o,u):o.byteLength===0?new Ji(Ey(a.blocksizes,l),u):new Xi(o,Ey(a.blocksizes,l),u);case P.Directory:return Yi(Sy(l),u);case P.HAMTShard:return Iy(Sy(l),o||Jc,a.fanout,a.hashType,u);case P.Symlink:return Ny(o,u);default:throw new TypeError(`Unsupported node type ${r.Type}`)}},Zx=t=>t==null?void 0:{mtime:{secs:t.Seconds,nsecs:t.FractionalNanoseconds||0}};var Ey=(t,e)=>{let r=[],n=t.length,o=0;for(;o<n;)r.push({cid:e[o].Hash,dagByteLength:e[o].Tsize||0,contentByteLength:t[o]});return r},Sy=t=>t.map(e=>({cid:e.Hash,name:e.Name||"",dagByteLength:e.Tsize||0})),Xe=t=>t.reduce((e,r)=>e+r.contentByteLength,0),qr=(t,e)=>e.reduce((r,n)=>r+n.dagByteLength,t.byteLength),Qn=t=>t.contentByteLength,My=({name:t,dagByteLength:e,cid:r})=>({Name:t,Tsize:e,Hash:r}),iu=t=>Jn(t,By),Jn=({mode:t,mtime:e},r=_y)=>({mode:t!=null?Ry(t,r):void 0,mtime:e!=null?ek(e):void 0}),Zt=t=>t==null?ke:{...t.mode==null?void 0:{mode:Oy(t.mode)},...t.mtime==null?void 0:{mtime:t.mtime}},ek=t=>t==null?void 0:t.nsecs!==0?{Seconds:t.secs,FractionalNanoseconds:t.nsecs}:{Seconds:t.secs},Ry=(t,e)=>{let r=t==null?void 0:Oy(t);return r===e||r==null?void 0:r},Oy=t=>t&4095|t&4294963200,tk=({content:t=Jc,parts:e=Ay,metadata:r=ke,...n})=>e.length===0?new Qi(t,r):t.byteLength===0?new Ji(e,r):new Xi(t,e,r),Qi=class{constructor(e,r){this.content=e,this.metadata=r,this.layout="simple",this.type=P.File}get filesize(){return this.content.byteLength}encode(){return es(this.content,this.metadata)}},Ji=class{constructor(e,r){this.parts=e,this.metadata=r}get layout(){return"advanced"}get type(){return P.File}get fileSize(){return Xe(this.parts)}get blockSizes(){return this.parts.map(Qn)}encode(){return eu(this.parts,this.metadata)}},Xi=class{constructor(e,r,n){this.content=e,this.parts=r,this.metadata=n}get layout(){return"complex"}get type(){return P.File}get fileSize(){return this.content.byteLength+Xe(this.parts)}get blockSizes(){return this.parts.map(Qn)}encode(){return tu(this.content,this.parts,this.metadata)}},rk=t=>{switch(t.type){case P.Raw:case P.Symlink:return t.content.byteLength;case P.File:switch(t.layout){case"simple":return t.content.byteLength;case"advanced":return Xe(t.parts);case"complex":return t.content.byteLength+Xe(t.parts)}default:return 0}};var nk=function*(t){let e=yield*t;yield*ns(e)};function*lu(){return yield ss}var Gr=function*(){yield as};var rs=function*(t){let e=yield*lu();if(ik(t)){let r=!1,n;if(t.then(o=>{r=!1,n=o,St(e)},o=>{r=!0,n=o,St(e)}),yield*Gr(),r)throw n;return n}else return uk(ok(e)),yield*Gr(),t};function*ok(t){St(t)}var ik=t=>t!=null&&typeof t.then=="function",ns=function*(t){yield t},os=function*(t){let e=[];for(let r of Object.entries(t)){let[n,o]=r;o!==Zn&&e.push(yield*Jr(ak(o,n)))}yield*du(e)},is=t=>t.length>0?sk(t.map(nk)):Zn;function*sk(t){let e=[];for(let r of t)e.push(yield*Jr(r));yield*du(e)}var ak=(t,e)=>t===Zn?Zn:t instanceof Xn?new Xn([...t.tags,e],t.source):new Xn([e],t),Xn=class{constructor(e,r){this.tags=e,this.source=r,this.controller}[Symbol.iterator](){return this.controller||(this.controller=this.source[Symbol.iterator]()),this}box(e){if(e.done)return e;switch(e.value){case as:case ss:return e;default:{let r=e,{value:n}=r;for(let o of this.tags)n=ck(o,n);return r.value=n,r}}}next(e){return this.box(this.controller.next(e))}throw(e){return this.box(this.controller.throw(e))}return(e){return this.box(this.controller.return(e))}get[Symbol.toStringTag](){return"TaggedEffect"}},eo=()=>Zn;var ck=(t,e)=>({type:t,[t]:e});var ss=Symbol("current"),as=Symbol("suspend");var st=class t{static of(e){return e.group||Kr}static enqueue(e,r){e.group=r,r.stack.active.push(e)}constructor(e,r=[],n=new Set,o=new Qr(r,n)){this.driver=e,this.parent=t.of(e),this.stack=o,this.id=++jy}},su=class{constructor(){this.status=Yn,this.stack=new Qr,this.id=0}},Qr=class{constructor(e=[],r=new Set){this.active=e,this.idle=r}static size({active:e,idle:r}){return e.length+r.size}},uk=t=>St(t[Symbol.iterator]()),St=t=>{let e=st.of(t);for(e.stack.active.push(t),e.stack.idle.delete(t);e.parent;){let{idle:r,active:n}=e.parent.stack;if(r.has(e.driver))r.delete(e.driver),n.push(e.driver);else break;e=e.parent}if(Kr.status===Yn)for(Kr.status=Vy;;)try{for(let r of fu(Kr));Kr.status=Yn;break}catch{Kr.stack.active.shift()}},lk=t=>St(t),fu=function*(t){let{active:e}=t.stack,r=e[0];for(t.stack.idle.delete(r);r;){let n=qy;e:for(;!n.done&&r===e[0];){let o=n.value;switch(o){case as:t.stack.idle.add(r);break e;case ss:n=r.next(r);break;default:n=r.next(yield o);break}}e.shift(),r=e[0],t.stack.idle.delete(r)}};var Jr=(t,e)=>new uu(t,e),fk=(t,e)=>$y(t,{ok:!0,value:e});var au=(t,e)=>$y(t,{ok:!1,error:e});function*$y(t,e){try{let r=t,n=e.ok?r.return(e.value):r.throw(e.error);if(!n.done)if(n.value===as){let{idle:o}=st.of(r).stack;o.add(r)}else St(r)}catch{}}function*du(t){if(t.length===0)return;let e=yield*lu(),r=new st(e),n=null;for(let o of t){let{result:i}=o;if(i){!i.ok&&!n&&(n=i);continue}dk(o,r)}try{if(n)throw n.error;for(;yield*fu(r),Qr.size(r.stack)>0;)yield*Gr()}catch(o){for(let i of r.stack.active)yield*au(i,o);for(let i of r.stack.idle)yield*au(i,o),St(i);throw o}}var dk=(t,e)=>{let r=st.of(t);if(r!==e){let{active:n,idle:o}=r.stack,i=e.stack;if(t.group=e,o.has(t))o.delete(t),i.idle.add(t);else{let s=n.indexOf(t);s>=0&&(n.splice(s,1),i.active.push(t))}}};function*hu(t){t.status===Yn&&(yield*t),t.result||(yield*du([t]));let e=t.result;if(e.ok)return e.value;throw e.error}var cu=class{constructor(e){this.handler=e,this.result}get promise(){let{result:e}=this,r=e==null?new Promise((n,o)=>{this.handler.onsuccess=n,this.handler.onfailure=o}):e.ok?Promise.resolve(e.value):Promise.reject(e.error);return Object.defineProperty(this,"promise",{value:r}),r}then(e,r){return this.activate().promise.then(e,r)}catch(e){return this.activate().promise.catch(e)}finally(e){return this.activate().promise.finally(e)}activate(){return this}},uu=class extends cu{constructor(e,r=hk,n={},o=qy){super(n),this.id=++jy,this.name=r.name||"",this.task=e,this.state=o,this.status=Yn,this.result,this.handler=n,this.controller}*resume(){lk(this)}join(){return hu(this)}abort(e){return au(this,e)}exit(e){return fk(this,e)}get[Symbol.toStringTag](){return"Fork"}*[Symbol.iterator](){return this.activate()}activate(){return this.controller=this.task[Symbol.iterator](),this.status=Vy,St(this),this}panic(e){this.result={ok:!1,error:e},this.status=zy;let{handler:r}=this;throw r.onfailure&&r.onfailure(e),e}step(e){if(this.state=e,e.done){this.result={ok:!0,value:e.value},this.status=zy;let{handler:r}=this;r.onsuccess&&r.onsuccess(e.value)}return e}next(e){try{return this.step(this.controller.next(e))}catch(r){return this.panic(r)}}return(e){try{return this.step(this.controller.return(e))}catch(r){return this.panic(r)}}throw(e){try{return this.step(this.controller.throw(e))}catch(r){return this.panic(r)}}},Hy=function*(t,e){let r=yield*lu(),n=new st(r);for(st.enqueue(t[Symbol.iterator](),n);;){for(let o of fu(n))st.enqueue(e(o)[Symbol.iterator](),n);if(Qr.size(n.stack)>0)yield*Gr();else break}},jy=0,Yn="idle",Vy="active",zy="finished",qy={done:!1,value:ss},hk={},Zn=function*(){}(),Kr=new su;function pu(){}Object.defineProperties(pu,{prototype:{value:new Proxy(Object.prototype,{get(t,e,r){return typeof e=="symbol"?Reflect.get(t,e,r):r.get(e)}})}});var yu=()=>new to;var Ky=(t,e=0,r=t.byteLength)=>{let n=[],o=e<0?t.byteLength-e:e,i=r<0?t.byteLength-r:r;if(o===0&&i>=t.byteLength)return t;if(o>i||o>t.byteLength||i<=0)return yu();let s=0,c=0;for(let a of t.segments){let u=c+a.byteLength;if(s===0){if(i<=u){let l=a.subarray(o-c,i-c);n.push(l),s=l.byteLength;break}else if(o<u){let l=o===c?a:a.subarray(o-c);n.push(l),s=l.byteLength}}else if(i<=u){let l=i===u?a:a.subarray(0,i-c);n.push(l),s+=l.byteLength;break}else n.push(a),s+=a.byteLength;c=u}return new to(n,t.byteOffset+o,s)},pk=(t,e)=>e.byteLength>0?(t.segments.push(e),new to(t.segments,t.byteOffset,t.byteLength+e.byteLength)):t,yk=(t,e)=>{if(e<t.byteLength){let r=0;for(let n of t.segments){if(e<r+n.byteLength)return n[e-r];r+=n.byteLength}}},mk=(t,e,r)=>{let n=r;for(let o of t.segments)e.set(o,n),n+=o.byteLength;return e};function*gk(t){for(let e of t.segments)yield*e}var to=class extends pu{constructor(e=[],r=0,n=0){super(),this.segments=e,this.byteLength=n,this.length=n,this.byteOffset=r}[Symbol.iterator](){return gk(this)}slice(e,r){return Ky(this,e,r)}subarray(e,r){return Ky(this,e,r)}push(e){return pk(this,e)}get(e){return yk(this,e)}copyTo(e,r){return mk(this,e,r)}};var ro=t=>{throw new Error(t)},Gy=(t,e,...r)=>ro(String.raw(t,JSON.stringify(e),...r)),Qy=new Uint8Array(0),Jy=[];var Xy=t=>({config:t,buffer:yu()}),Yy=(t,e)=>e.byteLength>0?em(t.config,t.buffer.push(e),!1):{...t,chunks:Jy},Zy=t=>em(t.config,t.buffer,!0),em=(t,e,r)=>{let n=t.chunker,o=[],i=0;for(let s of n.cut(n.context,e,r))if(s>0){let c=e.subarray(i,i+s);o.push(c),i+=s}return{config:t,chunks:o,buffer:e.subarray(i)}};var tm=()=>({mutable:!0,needs:{},nodes:{},links:{},linked:wu});var bu=(t,e)=>{let r=Xr(e,{});for(let n of t){let{ready:o,has:i,wants:s}=nm(n.children,r.links);s.length===0?r=Xr(r,{links:gu(void 0,i),linked:[{id:n.id,links:o}]}):r=Xr(r,{needs:gu(n.id,s),nodes:{[n.id]:{children:n.children,count:s.length}}})}return r},rm=(t,e,r)=>{let n=r.needs[t],o=r.nodes[n];if(o!=null)if(o.count===1){let{ready:i,has:s}=nm(o.children,{...r.links,[t]:e});return Xr(r,{needs:{[t]:void 0},links:gu(void 0,s),nodes:{[n]:void 0},linked:[{id:n,links:i}]})}else return Xr(r,{needs:{[t]:void 0},links:{[t]:e},nodes:{[n]:{...o,count:o.count-1}}});else return Xr(r,{links:{[t]:e}})},Xr=(t,{needs:e,nodes:r,links:n,linked:o})=>{let i=t.mutable?t:{...t},s=t.mutable?kk:void 0;return e&&(i.needs=mu(t.needs,e,s)),r&&(i.nodes=mu(t.nodes,r,s)),n&&(i.links=mu(t.links,n,s)),i.linked=o?xk(t.linked||wu,o,wu):t.linked||[],i},gu=(t,e)=>{let r={};for(let n of e)r[n]=t;return r},mu=(t,e,r=t)=>{let n=t===r?{...t}:t;for(let o of Object.entries(e)){let[i,s]=o;s==null?delete n[i]:n[i]=s}return n};var xk=(t,e,r=t)=>{if(t===r)return[...t,...e];for(let n of e)t.push(n);return t},nm=(t,e)=>{let r=[],n=[],o=[];for(let i of t){let s=e[i];s?(r.push(i),o.push(s)):n.push(i)}return{has:r,wants:n,ready:o}},wu=Object.freeze([]),kk=Object.freeze({});var om=(t,e)=>{switch(t.type){case"write":return Ek(e,t.bytes);case"link":return Sk(e,t.link);case"block":return{state:e,effect:eo()};case"close":return Ak(e);case"end":return{state:e,effect:eo()};default:return Gy`File Writer got unknown message ${t}`}},im=(t,e,r)=>({status:"open",metadata:e,config:r,writer:t,chunker:Xy({chunker:r.chunker}),layout:r.fileLayout.open(),nodeQueue:tm()}),Ek=(t,e)=>{if(t.status==="open"){let{chunks:r,...n}=Yy(t.chunker,e),{nodes:o,leaves:i,layout:s}=t.config.fileLayout.write(t.layout,r),{linked:c,...a}=bu(o,t.nodeQueue),u=[...sm(i,t.config),...xu(c,t.config)];return{state:{...t,chunker:n,layout:s,nodeQueue:a},effect:os({link:is(u)})}}else return ro("Unable to perform write on closed file")},Sk=(t,{id:e,link:r,block:n})=>{let{linked:o,...i}=rm(e,r,t.nodeQueue),s=xu(o,t.config),c=t.status==="closed"&&e===t.rootID?{...t,status:"linked",link:r,nodeQueue:i}:{...t,nodeQueue:i},a=t.status==="closed"&&e===t.rootID&&t.end?t.end.resume():eo();return{state:c,effect:os({link:is(s),block:Ck(t.writer,n),end:a})}},Ak=t=>{if(t.status==="open"){let{chunks:e}=Zy(t.chunker),{layout:r,...n}=t.config.fileLayout.write(t.layout,e),{root:o,...i}=t.config.fileLayout.close(r,t.metadata),[s,c]=Ik(o)?[[...n.nodes,...i.nodes],[...n.leaves,...i.leaves,o]]:[[...n.nodes,...i.nodes,o],[...n.leaves,...i.leaves]],{linked:a,...u}=bu(s,t.nodeQueue),l=[...sm(c,t.config),...xu(a,t.config)],d=Jr(Gr());return{state:{...t,chunker:null,layout:null,rootID:o.id,status:"closed",end:d,nodeQueue:u},effect:os({link:is(l),end:hu(d)})}}else return{state:t,effect:eo()}},sm=(t,e)=>t.map(r=>_k(e,r,e.fileChunkEncoder)),_k=function*({hasher:t,linker:e},{id:r,content:n},o){let i=o.encode(n?Tk(n):Qy),s=yield*rs(t.digest(i)),c=e.createLink(o.code,s),a={cid:c,bytes:i},u={cid:c,contentByteLength:n?n.byteLength:0,dagByteLength:i.byteLength};return{id:r,block:a,link:u}},xu=(t,e)=>t.map(r=>Bk(e,r)),Bk=function*(t,{id:e,links:r},n){let o=t.fileEncoder.encode({type:P.File,layout:"advanced",parts:r,metadata:n}),i=yield*rs(Promise.resolve(t.hasher.digest(o))),s=t.linker.createLink(t.fileEncoder.code,i),c={bytes:o,cid:s},a={cid:s,contentByteLength:Xe(r),dagByteLength:qr(o,r)};return{id:e,block:c,link:a}},Ck=function*(t,e){(t.desiredSize||0)<=0&&(yield*rs(t.ready)),t.write(e)},Tk=t=>t instanceof Uint8Array?t:t.copyTo(new Uint8Array(t.byteLength),0),Ik=t=>t.children==null;var vu={};G(vu,{context:()=>Dk,cut:()=>cm,name:()=>am,type:()=>Nk,withMaxChunkSize:()=>ku});var am="fixed",Dk={maxChunkSize:262144},Nk="Stateless",ku=t=>({type:"Stateless",context:{maxChunkSize:t},name:am,cut:cm}),cm=({maxChunkSize:t},{byteLength:e},r)=>{let n=e/t|0,o=new Array(n).fill(t),i=r?e-n*t:0;return i>0&&o.push(i),o};var no=class{constructor(e,r,n){this.id=e,this.children=r,this.metadata=n}},cs=t=>({open:()=>Pk({width:t}),write:Fk,close:Mk}),Uk={width:174},Pk=({width:t}=Uk)=>({width:t,head:null,leafIndex:[],nodeIndex:[],lastID:0}),Fk=(t,e)=>{if(e.length===0)return{layout:t,nodes:de,leaves:de};{let{lastID:r}=t,[n,o]=t.head?[null,(e.unshift(t.head),e)]:e.length===1&&t.leafIndex.length===0?[e[0],de]:[null,e];if(o.length===0)return{layout:{...t,head:n},nodes:de,leaves:de};{let i=[...t.leafIndex],s=[];for(let c of o){let a={id:++r,content:c};s.push(a),i.push(a.id)}return i.length>=t.width?lm({...t,leafIndex:i,head:n,lastID:r},s):{layout:{...t,head:n,leafIndex:i,lastID:r},leaves:s,nodes:de}}}},lm=(t,e=de,r=[],n=!1)=>{let{lastID:o}=t,i=t.nodeIndex.map(u=>[...u]),s=[...t.leafIndex],{width:c}=t;for(;s.length>=c||s.length>0&&n;){um(i,1);let u=new no(++o,s.splice(0,c));i[0].push(u.id),r.push(u)}let a=0;for(;a<i.length;){let u=i[a];for(a++;u.length>=c||u.length>0&&n&&a<i.length;){let l=new no(++o,u.splice(0,c));um(i,a+1),i[a].push(l.id),r.push(l)}}return{layout:{...t,lastID:o,leafIndex:s,nodeIndex:i},leaves:e,nodes:r}},Mk=(t,e)=>{let r=t;if(t.head)return{root:{id:1,content:t.head,metadata:e},leaves:de,nodes:de};if(t.leafIndex.length===0)return{root:{id:1,metadata:e},leaves:de,nodes:de};{let{nodes:n,layout:o}=lm(r,de,[],!0),{nodeIndex:i}=o,s=i.length-1,c=i[s];if(c.length===1){let a=n[n.length-1];return n.length=n.length-1,{root:a,nodes:n,leaves:de}}else return{root:new no(o.lastID+1,c,e),nodes:n,leaves:de}}},um=(t,e)=>{for(;t.length<e;)t.push([]);return t},de=[];var At=()=>({chunker:vu,fileChunkEncoder:Eu,smallFileEncoder:Eu,fileEncoder:Wr,fileLayout:cs(174),hasher:nt,linker:{createLink:H.createV1}}),_t=t=>({...At(),...t}),Eu={code:Vr,name:Xc,encode:Zc};var oo=({writer:t,metadata:e={},settings:r=At()})=>new Su(im(t,e,_t(r))),fm=async(t,e)=>(await hm(t,ns({type:"write",bytes:e})),t),dm=async(t,{releaseLock:e=!1,closeWriter:r=!1}={})=>{await hm(t,ns({type:"close"}));let{state:n}=t;if(n.status==="linked")return r?await t.state.writer.close():e&&t.state.writer.releaseLock(),n.link;ro(`Expected writer to be in 'linked' state after close, but it is in "${n.status}" instead`)},hm=(t,e)=>Jr(Hy(e,r=>{let{state:n,effect:o}=om(r,t.state);return t.state=n,o})),Su=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.config}write(e){return fm(this,e)}close(e){return dm(this,e)}};var Ok=At,_u=({writer:t,settings:e=Ok(),metadata:r={}})=>new us({writer:t,metadata:r,settings:e,entries:new Map,closed:!1}),ls=(t,e,r,{overwrite:n=!1}={})=>{let o=Bu(t.state);if(e.includes("/"))throw new Error(`Directory entry name "${e}" contains forbidden "/" character`);if(!n&&o.entries.has(e))throw new Error(`Directory already contains entry with name "${e}"`);return o.entries.set(e,r),t},fs=(t,e)=>(Bu(t.state).entries.delete(e),t),Bu=t=>{if(t.closed)throw new Error("Can not change written directory, but you can .fork() and make changes to it");return t},pm=async(t,{closeWriter:e=!1,releaseLock:r=!1}={})=>{let{writer:n,settings:o,metadata:i}=Bu(t.state);t.state.closed=!0;let s=[...ym(t)],c=Yi(s,i),a=ts(c),u=await o.hasher.digest(a),l=o.linker.createLink(Vr,u);return(n.desiredSize||0)<=0&&await n.ready,n.write({cid:l,bytes:a}),e?await n.close():r&&n.releaseLock(),{cid:l,dagByteLength:qr(a,s)}},ym=function*({state:t}){for(let[e,{dagByteLength:r,cid:n}]of t.entries)yield{name:e,dagByteLength:r,cid:n}},mm=({state:t},{writer:e=t.writer,metadata:r=t.metadata,settings:n=t.settings}={})=>new us({writer:e,metadata:r,settings:n,entries:new Map(t.entries.entries()),closed:!1}),us=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.settings}links(){return ym(this)}set(e,r,n){return ls(this,e,r,n)}remove(e){return fs(this,e)}fork(e){return mm(this,e)}close(e){return pm(this,e)}entries(){return this.state.entries.entries()}has(e){return this.state.entries.has(e)}get size(){return this.state.entries.size}};var ps={};G(ps,{API:()=>ds,and:()=>Kk,bitCount:()=>hs,empty:()=>gm,from:()=>$k,fromBytes:()=>Jk,get:()=>Wk,or:()=>Gk,popcount:()=>Cu,set:()=>wm,size:()=>Hk,toBytes:()=>Qk,unset:()=>qk});var ds={};var gm=(t=32)=>{if(t!==32)throw new Error(`Uint32 BitField does not support size: ${t}`);return 0},$k=(t,e)=>{let r=gm(e);for(let n of t)r=wm(r,n);return r},Hk=t=>32,jk=(t,e)=>t>>>e&31,Vk=(t,e)=>1<<jk(t,e),Cu=(t,e=31)=>hs(t&Vk(e,0)-1),wm=(t,e)=>t|1<<e,qk=(t,e)=>t&(255^1<<e),Wk=(t,e)=>(t>>e&1)!==0,hs=t=>{let e=t-(t>>1&1431655765),r=(e&858993459)+(e>>2&858993459);return(r+(r>>4)&252645135)*16843009>>24},Kk=(t,e)=>t&e,Gk=(t,e)=>t|e,Qk=t=>Uint8Array.of(t>>24&255,t>>16&255,t>>8&255,t&255),Jk=t=>{if(t.length!==4)throw new Error(`Expected 4 bytes instead got ${t.length}`);return(t[0]<<24)+(t[1]<<16)+(t[2]<<8)+t[3]};var km=V(Tu(),1),Xk=new TextEncoder,Yk=km.default.x64.hash126,vm=({bitWidth:t=5,hash:e=Yk})=>{if(t>4*8)throw new RangeError(`Can not use bitWidth ${t} which exceeds the hashSize 4`);if(4*8>32)throw new RangeError("Can not use hashSize 4 as it can not be encoded in Uint32");let n=4294967295>>>32-t;return{at:(s,c)=>s>>>c*t&n,from:s=>e(Xk.encode(s)),size:Math.ceil(4*8/t)}};var Yr=class{constructor(e,r,n,o,i){this.edit=e,this.config=i,this.datamap=r,this.nodemap=n,this.children=o}get nodeArity(){return this.config.BitField.popcount(this.nodemap)}get dataArity(){return this.config.BitField.popcount(this.datamap)}empty(){return so(this.config)}lookup(e,r,n,o){return Sm(this,e,r,n,o)}associate(e,r,n,o,i,s){return Du(this,e,r,n,o,i,s)}dissociate(e,r,n,o,i){return Am(this,e,r,n,o,i)}fork(e=null){return ao(this,e)}entries(){return _m(this)}keys(){return Bm(this)}values(){return Cm(this)}},ms=class{constructor(e,r,n,o){this.edit=e,this.count=r,this.children=n,this.config=o}get nodeArity(){return 0}get dataArity(){return this.count}lookup(e,r,n,o){return Zk(this,n,o)}associate(e,r,n,o,i,s){return e2(this,e,n,o,i,s)}dissociate(e,r,n,o,i){return t2(this,e,n,o,i)}fork(e=null){return r2(this,e)}entries(){return _m(this)}keys(){return Bm(this)}values(){return Cm(this)}},Zk=(t,e,r)=>{let{children:n,count:o}=t,i=Iu(n,o,e);return n[i]===e?n[i+1]:r},e2=(t,e,r,n,o,i)=>{let{children:s,count:c}=t,a=Iu(s,c,n);if(s[a]!==n){let u=t.fork(e);return i.value=!0,u.count+=1,u.children.splice(a,r,o),u}else if(s[a+1]!==o){let u=t.fork(e);return u.children[a+1]=o,u}else return t},t2=(t,e,r,n,o)=>{let{children:i,count:s,config:c}=t,a=Iu(i,s,n);if(i[a]!==n)return t;if(o.value=!0,s===2){let u=a===0?2:0;return Du(so(c),e,0,r,i[u],i[u+1],o)}else{let u=t.fork(e);return u.children.splice(a,2),u.count-=1,u}},r2=(t,e=null)=>Dm(t.edit,e)?t:new ms(e,t.count,t.children.slice(),t.config),Iu=(t,e,r)=>{let n=0;for(;n<e&&t[n]>r;)n+=2;return n};var so=(t,e=null)=>new Yr(e,t.BitField.empty(Math.pow(2,t.bitWidth)),t.BitField.empty(Math.pow(2,t.bitWidth)),[],t),ws=(t,e,r)=>Sm(t,0,t.config.Path.from(e),e,r),Sm=(t,e,r,n,o)=>{let{datamap:i,nodemap:s,config:c}=t,{Path:a,BitField:u}=c,l=a.at(r,e);if(u.get(i,l)){let d=u.popcount(i,l);return bs(t,d)===n?gs(t,d):o}else return u.get(s,l)?xs(t,l).lookup(e+1,r,n,o):o},Lu=(t,e,r,n,o)=>Du(t,e,0,t.config.Path.from(r),r,n,o),Du=(t,e,r,n,o,i,s)=>{let{datamap:c,nodemap:a,config:u}=t,{Path:l,BitField:d}=u,m=l.at(n,r);if(d.get(c,m)){let f=d.popcount(c,m),h=bs(t,f);if(o===h)return gs(t,f)===i?t:n2(t,e,f,i);{let p=Im(u,e,r+1,l.from(h),h,gs(t,f),n,o,i);return s.value=!0,i2(t,e,m,p)}}else if(d.get(a,m)){let f=xs(t,m),h=f.associate(e,r+1,n,o,i,s);return f===h?t:Tm(t,e,m,h)}else{let f=d.popcount(c,m);s.value=!0;let h=t.fork(e);return h.datamap=d.set(c,m),h.children.splice(co(f),0,o,i),h}},Nu=(t,e,r,n)=>Am(t,e,0,t.config.Path.from(r),r,n);var Am=(t,e,r,n,o,i)=>{let{datamap:s,nodemap:c,config:a}=t,{BitField:u,Path:l}=a,d=l.at(n,r);if(u.get(s,d)){let m=u.popcount(s,d);if(o===bs(t,m)){i.value=!0;let f=ao(t,e);return f.datamap=u.unset(t.datamap,d),f.children.splice(co(m),2),f}else return t}else if(u.get(c,d)){let m=xs(t,d),f=m.dissociate(e,r+1,n,o,i);return s2(f)?a2(t)?f:o2(t,e,d,f):m===f?t:Tm(t,e,d,f)}else return t},_m=function*({children:t}){let e=0,r=t.length;for(;e<r;){let n=t[e];if(typeof n=="string"){e+=1;let o=t[e];yield[n,o],e+=1}else break}for(;e<r;)yield*t[e].entries(),e+=1},ao=(t,e)=>Dm(t.edit,e)?t:new Yr(e,t.datamap,t.nodemap,t.children.slice(),t.config),Bm=function*({children:t}){let e=0,r=t.length;for(;e<r;){let n=t[e];if(typeof n=="string")yield n,e+=2;else break}for(;e<r;)yield*t[e].keys(),e+=1},Cm=function*({children:t}){let e=0,r=t.length;for(;e<r&&typeof t[e]=="string";)e+=1,yield t[e],e+=1;for(;e<r;)yield*t[e].values(),e+=1},n2=(t,e,r,n)=>{let o=t.fork(e);return o.children[Lm(r)]=n,o},o2=(t,e,r,n)=>{let{datamap:o,nodemap:i,config:s}=t,{BitField:c}=s,a=ao(t,e);return a.children.splice(ks(t,r),1),a.children.splice(co(c.popcount(o,r)),0,n.children[0],n.children[1]),a.datamap=c.set(o,r),a.nodemap=c.unset(i,r),a},Tm=(t,e,r,n)=>{let o=ao(t,e);return o.children[ks(t,r)]=n,o},i2=(t,e,r,n)=>{let{nodemap:o,datamap:i,config:s}=t,{BitField:c}=s,a=c.popcount(i,r),u=co(a),l=ks(t,r),d=ao(t,e);return d.datamap=c.unset(i,r),d.children.splice(u,2),d.nodemap=c.set(o,r),d.children.splice(l-1,0,n),d},Im=(t,e,r,n,o,i,s,c,a)=>{let{BitField:u,Path:l}=t;if(l.size<r)return new ms(e,2,[o,i,c,a],t);{let d=l.at(n,r),m=l.at(s,r);return d===m?new Yr(e,u.empty(Math.pow(2,t.bitWidth)),u.from([d],Math.pow(2,t.bitWidth)),[Im(t,e,r+1,n,o,i,s,c,a)],t):new Yr(e,u.from([d,m],Math.pow(2,t.bitWidth)),u.empty(Math.pow(2,t.bitWidth)),d<m?[o,i,c,a]:[c,a,o,i],t)}},bs=({children:t},e)=>t[co(e)],co=t=>t*2,gs=({children:t},e)=>t[Lm(e)],Lm=t=>t*2+1,xs=(t,e)=>t.children[ks(t,e)],ks=({children:t,nodemap:e,config:r},n)=>t.length-1-r.BitField.popcount(e,n),Dm=(t,e)=>t!=null&&t===e,s2=t=>t.nodeArity===0&&t.dataArity===1,a2=({config:{BitField:t},datamap:e,nodemap:r})=>t.popcount(e)===0&&t.popcount(r)===1;var vs=V(Tu(),1);function c2(t){let e=new Array(4);for(let r=0;r<4;r++)e[r]=t&255,t=t>>8;return new Uint8Array(e)}var V3=Mt({name:"murmur3-32",code:35,encode:t=>c2(vs.default.x86.hash32(t))}),Um=Mt({name:"murmur3-128",code:34,encode:t=>Nt.fromHex(vs.default.x64.hash128(t))}),uo=Mt({name:"murmur3-x64-64",code:34,encode:t=>Nt.fromHex(vs.default.x64.hash128(t)).subarray(0,8)});var u2=new TextEncoder,l2=t=>uo.encode(t),Pm=({bitWidth:t=8,hash:e=l2}={})=>{let r=e(new Uint8Array).byteLength;return{from:i=>e(u2.encode(i)),at:(i,s)=>{let c=s*t;if(c>r)throw new RangeError("Out of bounds");return Uu(i,c,t)},size:Math.ceil(r*8/t)}},Uu=(t,e,r)=>{let n=e/8|0,o=e%8,i=r,s=0;for(;i>0&&n<t.byteLength;){let c=t[n],a=8-o,u=a<i?a:i,l=8-o-u,m=(255>>o&c)>>l;s=(s<<u)+m,i-=u,n++,o=0}return s};var Pu={};G(Pu,{API:()=>ds,and:()=>k2,empty:()=>Fm,from:()=>d2,fromBytes:()=>w2,get:()=>m2,or:()=>x2,popcount:()=>b2,set:()=>p2,size:()=>h2,toBytes:()=>g2,unset:()=>y2});var Fm=(t=256)=>{if(t%8!==0)throw new Error("Must be multiple of 8");return new Uint8Array(t/8)},d2=(t,e)=>{let r=Fm(e);for(let n of t){let{byte:o,byteOffset:i,bitOffset:s}=lo(r,n);r[i]=o|1<<s}return r},h2=t=>t.byteLength*8,lo=(t,e)=>{let r=t.byteLength-1-(e/8|0),n=e%8;return{byte:t[r],byteOffset:r,bitOffset:n}},Mm=(t,e,r)=>{if(t[e]!==r){let n=t.slice(0);return n[e]=r,n}return t},p2=(t,e)=>{let{byte:r,byteOffset:n,bitOffset:o}=lo(t,e);return Mm(t,n,r|1<<o)},y2=(t,e)=>{let{byte:r,byteOffset:n,bitOffset:o}=lo(t,e);return Mm(t,n,r&(255^1<<o))},m2=(t,e)=>{var{byte:r,bitOffset:n}=lo(t,e);return(r>>n&1)!==0},g2=t=>t,w2=t=>t,b2=(t,e=t.byteLength*8)=>{let{byteOffset:r,bitOffset:n,byte:o}=lo(t,e),i=Cu(o,n),s=t.byteLength-1;for(;s>r;){let c=t[s];i+=hs(c),s--}return i},x2=(t,e)=>{let r=t.slice(),n=0;for(;n<t.length;)r[n]|=e[n],n++;return r},k2=(t,e)=>{let r=t.slice(),n=0;for(;n<t.length;)r[n]&=e[n],n++;return r};var Rm=new RangeError("Not Found");var v2=({bitWidth:t=5,BitField:e=t===5?ps:Pu,Path:r=t===5?vm({bitWidth:t}):Pm({bitWidth:t})}={})=>({bitWidth:t,BitField:e,Path:r});var Mu=(t,e)=>ws(t.root,e,Rm)!==Rm,Om=(t,e,r=void 0)=>ws(t.root,e,r),zm=t=>{let e={},r=v2(t);return new Es(e,0,so(r,e),r)},Fu=class t{constructor(e=0,r,n){this.count=e,this.root=r,this.config=n}get size(){return this.count}clone(){return new t(this.count,this.root,this.config)}empty(){return new t(0,so(this.config,null),this.config)}has(e){return Mu(this,e)}get(e){return ws(this.root,e,void 0)}set(e,r){let n={value:!1},o=Lu(this.root,null,e,r,n);return o===this.root?this:new t(n.value?this.count+1:this.count,o,this.config)}delete(e){let r=Nu(this.root,null,e,{value:!1});return r===this.root?this:new t(this.count-1,r,this.config)}get bitField(){return this.config.BitField.or(this.root.datamap,this.root.nodemap)}[Symbol.iterator](){return this.entries()}entries(){return this.root.entries()}keys(){return this.root.keys()}values(){return this.root.values()}createBuilder(){return new Es({},this.count,this.root,this.config)}},Es=class{constructor(e,r,n,o){this.edit=e,this.count=r,this.root=n,this.config=o}get size(){if(this.edit)return this.count;throw new Error(".size was accessed on the finalized builder")}set(e,r){if(this.edit){let n={value:!1},o=Lu(this.root,this.edit,e,r,n);return this.root!==o&&(this.root=o),n.value&&(this.count+=1),this}else throw new Error(".set was called on the finalized builder")}delete(e){if(this.edit){if(this.count===0)return this;let r={value:!1},n=Nu(this.root,this.edit,e,r);return n!==this.root&&(this.root=n),r.value&&(this.count-=1),this}else throw new Error(".delete was called on the finalized builder")}build(){if(this.edit)return this.edit=null,new Fu(this.count,this.root,this.config);throw new Error(".build was called on the finalized builder")}};var E2=new TextEncoder,S2=t=>uo.encode(t),Hm=({bitWidth:t=8,hash:e=S2})=>{let r=e(new Uint8Array).byteLength,n={bitWidth:t,hash:e,hashSize:r};return{at:(s,c)=>A2(s,c,n),from:s=>E2.encode(s),size:1/0}},A2=(t,e=0,{bitWidth:r=8,hash:n,hashSize:o})=>{let i=o*8,s=0,c=r,a=r*e;for(;c>0;){let u=a/i>>0,l=n(u===0?t:_2(t,u)),d=i<=a?a%i:a,m=i-d,f=m<c?m:c;s=(s<<f)+Uu(l,d,f),c-=f,a+=f}return s},_2=(t,e)=>{let r=new Uint8Array(t.byteLength+1).fill(e,t.byteLength);return r.set(t),r};var jm=8,C2={bitWidth:jm,Path:Hm({bitWidth:jm})};var Ru=(t=C2)=>zm(t);var Vm=class extends Map{constructor(e=Ru()){super(),this.builder=e}clear(){this.builder=Ru()}delete(e){let{root:r}=this.builder;return this.builder.delete(e),this.builder.root!==r}forEach(e,r=this){for(let[n,o]of this.builder.root.entries())e.call(r,o,n,this)}get(e){return Om(this.builder,e)}has(e){return Mu(this.builder,e)}set(e,r){return this.builder.set(e,r),this}get size(){return this.builder.size}[Symbol.iterator](){return this.builder.root.entries()}entries(){return this.builder.root.entries()}keys(){return this.builder.root.keys()}values(){return this.builder.root.values()}};var qm=({writable:t,settings:e=At()})=>new Ou({writer:t.getWriter(),settings:e}),I2=async(t,{releaseLock:e=!0,closeWriter:r=!0}={})=>(r?await t.writer.close():e&&t.writer.releaseLock(),t),Ou=class{constructor({writer:e,settings:r}){this.writer=e,this.settings=_t(r)}createFileWriter({settings:e=this.settings,metadata:r}={}){return oo({writer:this.writer,settings:e,metadata:r})}createDirectoryWriter({settings:e=this.settings,metadata:r}={}){return _u({writer:this.writer,settings:e,metadata:r})}close(e){return I2(this,e)}},L2=1048576,D2=L2*100,Wm=(t=D2)=>({highWaterMark:t,size:e=>e.bytes.length});var $s=V(Ye(),1);function P2(t){return t[Symbol.asyncIterator]!=null}function F2(t){if(P2(t))return(async()=>{let r;for await(let n of t)r=n;return r})();let e;for(let r of t)e=r;return e}var Qm=F2;var Xg=V(Ye(),1);var Jm=0,M2="identity",Xm=ie,R2=t=>Ut(Jm,Xm(t)),Ym={code:Jm,name:M2,encode:Xm,digest:R2};var Zm=V(Ye(),1);var O2=async(t,e,r,n,o,i,s,c)=>{let a=await s.get(t,c),u=xr(a),l=u,d=r;for(;n.length>0;){let m=n[0];if(m in l){n.shift(),d=`${d}/${m}`;let f=j.asCID(l[m]);if(f!=null)return{entry:{type:"object",name:e,path:r,cid:t,node:a,depth:i,size:BigInt(a.length),content:async function*(){yield u}},next:{cid:f,name:m,path:d,toResolve:n}};l=l[m]}else throw(0,Zm.default)(new Error(`No property named ${m} found in cbor node ${t}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:r,cid:t,node:a,depth:i,size:BigInt(a.length),content:async function*(){yield u}}}},eg=O2;var tg=V(Ye(),1);var ae=class extends Event{constructor(e,r){super(e),this.detail=r}};function z2(t,e,r,n){let o=BigInt(t.length),i=BigInt(e+o);return r>=i||n<e?new Uint8Array(0):(n>=e&&n<i&&(t=t.subarray(0,Number(n-e))),r>=e&&r<i&&(t=t.subarray(Number(r-e))),t)}var er=z2;var fo=V(Ye(),1),$2=(t,e=0,r=t)=>{let n=BigInt(t),o=BigInt(e??0),i=BigInt(r);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw(0,fo.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(o>n)throw(0,fo.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(i<0n)throw(0,fo.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,fo.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:o,end:i}},Zr=$2;var H2=t=>{async function*e(r={}){let{start:n,end:o}=Zr(t.length,r.offset,r.length),i=er(t,0n,n,o);r.onProgress?.(new ae("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(t.byteLength)})),yield i}return e},j2=async(t,e,r,n,o,i,s,c)=>{if(n.length>0)throw(0,tg.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let a=Wo(t.multihash.bytes);return{entry:{type:"identity",name:e,path:r,cid:t,content:H2(a.digest),depth:i,size:BigInt(a.digest.length),node:a.digest}}},rg=j2;var ng=V(Ye(),1);var V2=t=>{async function*e(r={}){let{start:n,end:o}=Zr(t.length,r.offset,r.length),i=er(t,0n,n,o);r.onProgress?.(new ae("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(t.byteLength)})),yield i}return e},q2=async(t,e,r,n,o,i,s,c)=>{if(n.length>0)throw(0,ng.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let a=await s.get(t,c);return{entry:{type:"raw",name:e,path:r,cid:t,content:V2(a),depth:i,size:BigInt(a.length),node:a}}},og=q2;var Ao=V(Ye(),1);var qu=V(Ye(),1);var zu=V(Gi(),1),ig=V(Kc(),1),sg=V(ot(),1),$u=V(Wi(),1),ag=V(Vc(),1);function W2(){sg.default._configure(),zu.default._configure(ig.default),$u.default._configure(ag.default)}W2();var cg=["uint64","int64","sint64","fixed64","sfixed64"];function K2(t){for(let e of cg){if(t[e]==null)continue;let r=t[e];t[e]=function(){return BigInt(r.call(this).toString())}}return t}function Hu(t){return K2(new zu.default(t))}function G2(t){for(let e of cg){if(t[e]==null)continue;let r=t[e];t[e]=function(n){return r.call(this,n.toString())}}return t}function ju(){return G2($u.default.create())}function ho(t,e){let r=Hu(t instanceof Uint8Array?t:t.subarray());return e.decode(r)}function po(t,e){let r=ju();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var en;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(en||(en={}));function Ss(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function Vu(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}let r=function(i,s){let c=e(i);s.int32(c)},n=function(i){let s=i.int32();return e(s)};return Ss("enum",en.VARINT,r,n)}function yo(t,e){return Ss("message",en.LENGTH_DELIMITED,t,e)}var Re;(function(t){let e;(function(o){o.Raw="Raw",o.Directory="Directory",o.File="File",o.Metadata="Metadata",o.Symlink="Symlink",o.HAMTShard="HAMTShard"})(e=t.DataType||(t.DataType={}));let r;(function(o){o[o.Raw=0]="Raw",o[o.Directory=1]="Directory",o[o.File=2]="File",o[o.Metadata=3]="Metadata",o[o.Symlink=4]="Symlink",o[o.HAMTShard=5]="HAMTShard"})(r||(r={})),function(o){o.codec=()=>Vu(r)}(e=t.DataType||(t.DataType={}));let n;t.codec=()=>(n==null&&(n=yo((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),t.DataType.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),o.filesize!=null&&(i.uint32(24),i.uint64(o.filesize)),o.blocksizes!=null)for(let c of o.blocksizes)i.uint32(32),i.uint64(c);o.hashType!=null&&(i.uint32(40),i.uint64(o.hashType)),o.fanout!=null&&(i.uint32(48),i.uint64(o.fanout)),o.mode!=null&&(i.uint32(56),i.uint32(o.mode)),o.mtime!=null&&(i.uint32(66),As.codec().encode(o.mtime,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let s={blocksizes:[]},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let a=o.uint32();switch(a>>>3){case 1:s.Type=t.DataType.codec().decode(o);break;case 2:s.Data=o.bytes();break;case 3:s.filesize=o.uint64();break;case 4:s.blocksizes.push(o.uint64());break;case 5:s.hashType=o.uint64();break;case 6:s.fanout=o.uint64();break;case 7:s.mode=o.uint32();break;case 8:s.mtime=As.codec().decode(o,o.uint32());break;default:o.skipType(a&7);break}}return s})),n),t.encode=o=>po(o,t.codec()),t.decode=o=>ho(o,t.codec())})(Re||(Re={}));var As;(function(t){let e;t.codec=()=>(e==null&&(e=yo((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Seconds!=null&&(n.uint32(8),n.int64(r.Seconds)),r.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(r.FractionalNanoseconds)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let o={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let s=r.uint32();switch(s>>>3){case 1:o.Seconds=r.int64();break;case 2:o.FractionalNanoseconds=r.fixed32();break;default:r.skipType(s&7);break}}return o})),e),t.encode=r=>po(r,t.codec()),t.decode=r=>ho(r,t.codec())})(As||(As={}));var ug;(function(t){let e;t.codec=()=>(e==null&&(e=yo((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.MimeType!=null&&(n.uint32(10),n.string(r.MimeType)),o.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let o={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let s=r.uint32();switch(s>>>3){case 1:o.MimeType=r.string();break;default:r.skipType(s&7);break}}return o})),e),t.encode=r=>po(r,t.codec()),t.decode=r=>ho(r,t.codec())})(ug||(ug={}));var lg={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},Q2=["directory","hamt-sharded-directory"],fg=parseInt("0644",8),dg=parseInt("0755",8),tn=class t{static unmarshal(e){let r=Re.decode(e),n=new t({type:lg[r.Type!=null?r.Type.toString():"File"],data:r.Data,blockSizes:r.blocksizes,mode:r.mode,mtime:r.mtime!=null?{secs:r.mtime.Seconds??0n,nsecs:r.mtime.FractionalNanoseconds}:void 0});return n._originalMode=r.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:r,data:n,blockSizes:o,hashType:i,fanout:s,mtime:c,mode:a}=e;if(r!=null&&!Object.values(lg).includes(r))throw(0,qu.default)(new Error("Type: "+r+" is not valid"),"ERR_INVALID_TYPE");this.type=r??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=a,this.mtime=c}set mode(e){e==null?this._mode=this.isDirectory()?dg:fg:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return Q2.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(r=>{e+=r}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=Re.DataType.Raw;break;case"directory":e=Re.DataType.Directory;break;case"file":e=Re.DataType.File;break;case"metadata":e=Re.DataType.Metadata;break;case"symlink":e=Re.DataType.Symlink;break;case"hamt-sharded-directory":e=Re.DataType.HAMTShard;break;default:throw(0,qu.default)(new Error(`Type: ${e} is not valid`),"ERR_INVALID_TYPE")}let r=this.data;(this.data==null||this.data.length===0)&&(r=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===fg&&!this.isDirectory()&&(n=void 0),n===dg&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Re.encode({Type:e,Data:r,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var Eg=V(yg(),1);var Wu={};G(Wu,{identity:()=>Z2});var Z2=lr({prefix:"\0",name:"identity",encode:t=>_l(t),decode:t=>Al(t)});var Ku={};G(Ku,{base2:()=>ev});var ev=K({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Gu={};G(Gu,{base8:()=>tv});var tv=K({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qu={};G(Qu,{base10:()=>rv});var rv=ut({prefix:"9",name:"base10",alphabet:"0123456789"});var Ju={};G(Ju,{base16:()=>nv,base16upper:()=>ov});var nv=K({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ov=K({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Xu={};G(Xu,{base36:()=>iv,base36upper:()=>sv});var iv=ut({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),sv=ut({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Yu={};G(Yu,{base64:()=>av,base64pad:()=>cv,base64url:()=>uv,base64urlpad:()=>lv});var av=K({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cv=K({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),uv=K({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lv=K({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Zu={};G(Zu,{base256emoji:()=>yv});var mg=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),fv=mg.reduce((t,e,r)=>(t[r]=e,t),[]),dv=mg.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function hv(t){return t.reduce((e,r)=>(e+=fv[r],e),"")}function pv(t){let e=[];for(let r of t){let n=dv[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var yv=lr({prefix:"\u{1F680}",name:"base256emoji",encode:hv,decode:pv});var el={};G(el,{identity:()=>wv});var gg=0,mv="identity",wg=Se,gv=t=>Tt(gg,wg(t)),wv={code:gg,name:mv,encode:wg,digest:gv};var bT=new TextEncoder,xT=new TextDecoder;var tl={...Wu,...Ku,...Gu,...Qu,...Ju,...Zs,...Xu,...Ys,...Yu,...Zu},vT={...Bc,...el};function rn(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function _s(t=0){return globalThis.Buffer?.allocUnsafe!=null?rn(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function xg(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var bg=xg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),rl=xg("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=_s(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),kv={utf8:bg,"utf-8":bg,hex:tl.base16,latin1:rl,ascii:rl,binary:rl,...tl},kg=kv;function vg(t,e="utf8"){let r=kg[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?rn(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var tr=class t{constructor(e,r,n=0){this._options=e,this._popCount=0,this._parent=r,this._posAtParent=n,this._children=new Eg.default,this.key=null}async put(e,r){let n=await this._findNewBucketAndPos(e);await n.bucket._putAt(n,e,r)}async get(e){let r=await this._findChild(e);if(r!=null)return r.value}async del(e){let r=await this._findPlace(e),n=r.bucket._at(r.pos);n!=null&&n.key===e&&r.bucket._delAt(r.pos)}leafCount(){return this._children.compactArray().reduce((r,n)=>n instanceof t?r+n.leafCount():r+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let r of e)r instanceof t?yield*r.eachLeafSeries():yield r}serialize(e,r){let n=[];return r(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof t?o.push(i.serialize(e,r)):o.push(e(i,s))),o),n))}async asyncTransform(e,r){return await Sg(this,e,r)}toJSON(){return this.serialize(Ev,Sv)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let r=await this._findPlace(e),n=r.bucket._at(r.pos);if(!(n instanceof t)&&n!=null&&n.key===e)return n}async _findPlace(e){let r=this._options.hash(typeof e=="string"?vg(e):e),n=await r.take(this._options.bits),o=this._children.get(n);return o instanceof t?await o._findPlace(r):{bucket:this,pos:n,hash:r,existingChild:o}}async _findNewBucketAndPos(e){let r=await this._findPlace(e);if(r.existingChild!=null&&r.existingChild.key!==e){let n=new t(this._options,r.bucket,r.pos);r.bucket._putObjectAt(r.pos,n);let o=await n._findPlace(r.existingChild.hash);return o.bucket._putAt(o,r.existingChild.key,r.existingChild.value),await n._findNewBucketAndPos(r.hash)}return r}_putAt(e,r,n){this._putObjectAt(e.pos,{key:r,value:n,hash:e.hash})}_putObjectAt(e,r){this._children.get(e)==null&&this._popCount++,this._children.set(e,r)}_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(vv);if(e!=null&&!(e instanceof t)){let r=e.hash;r.untake(this._options.bits);let n={pos:this._posAtParent,hash:r,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 vv(t){return!!t}function Ev(t,e){return t.key}function Sv(t){return t}async function Sg(t,e,r){let n=[];for(let o of t._children.compactArray())if(o instanceof tr)await Sg(o,e,r);else{let i=await e(o);n.push({bitField:t._children.bitField(),children:i})}return await r(n)}var Av=[255,254,252,248,240,224,192,128],_v=[1,3,7,15,31,63,127,255],Bs=class{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 r=e,n=0;for(;r>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,r),c=Bv(o,i-s,s);n=(n<<s)+c,r-=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 Bv(t,e,r){let n=Cv(e,r);return(t&n)>>>e}function Cv(t,e){return Av[t]&_v[Math.min(e+t-1,7)]}function Ag(t,e){e==null&&(e=t.reduce((o,i)=>o+i.length,0));let r=_s(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return rn(r)}function _g(t){function e(r){return r instanceof Cs?r:new Cs(r,t)}return e}var Cs=class{constructor(e,r){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=r,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let r=e;for(;this._availableBits<r;)await this._produceMoreBits();let n=0;for(;r>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),r),s=o.take(i);n=(n<<i)+s,r-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let r=e;for(;r>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),r);n.untake(o),r-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?Ag([this._value,Uint8Array.from([this._depth])]):this._value,r=await this._hashFn(e),n=new Bs(r);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Bg(t){if(t==null||t.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:t.bits??8,hash:_g(t.hashFn)};return new tr(e)}var Tv=async function(t){return(await Um.encode(t)).slice(0,8).reverse()},Iv=async(t,e,r)=>{await Promise.all(t.map(async n=>{if(n.Name==null)throw new Error("Unexpected Link without a Name");if(n.Name.length===2){let o=parseInt(n.Name,16);e._putObjectAt(o,new tr({hash:r._options.hash,bits:r._options.bits},e,o));return}await r.put(n.Name.substring(2),!0)}))},Cg=t=>t.toString(16).toUpperCase().padStart(2,"0").substring(0,2),Lv=t=>{let e=t.bucket,r=[];for(;e._parent!=null;)r.push(e),e=e._parent;return r.push(e),r.reverse()},Tg=async(t,e,r,n,o)=>{if(n==null){let l=Bg({hashFn:Tv});n={rootBucket:l,hamtDepth:1,lastBucket:l}}await Iv(t.Links,n.lastBucket,n.rootBucket);let i=await n.rootBucket._findNewBucketAndPos(e),s=Cg(i.pos),c=Lv(i);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],s=Cg(n.lastBucket._posAtParent));let a=t.Links.find(l=>{if(l.Name==null)return!1;let d=l.Name.substring(0,2),m=l.Name.substring(2);return!(d!==s||m!==""&&m!==e)});if(a==null)return;if(a.Name!=null&&a.Name.substring(2)===e)return a.Hash;n.hamtDepth++;let u=await r.get(a.Hash,o);return t=Ge(u),Tg(t,e,r,n,o)},Ig=Tg;function Dv(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[r](){return this}}}var Ts=Dv;function Nv(t){return t[Symbol.asyncIterator]!=null}function Uv(t,e){if(Nv(t))return async function*(){for await(let c of t)await e(c)&&(yield c)}();let r=Ts(t),{value:n,done:o}=r.next();if(o===!0)return function*(){}();let i=e(n);if(typeof i.then=="function")return async function*(){await i&&(yield n);for await(let c of r)await e(c)&&(yield c)}();let s=e;return function*(){i===!0&&(yield n);for(let c of r)s(c)&&(yield c)}()}var Lg=Uv;function Pv(t){return t[Symbol.asyncIterator]!=null}function Fv(t,e){if(Pv(t))return async function*(){for await(let c of t)yield e(c)}();let r=Ts(t),{value:n,done:o}=r.next();if(o===!0)return function*(){}();let i=e(n);if(typeof i.then=="function")return async function*(){yield await i;for await(let c of r)yield e(c)}();let s=e;return function*(){yield i;for(let c of r)yield s(c)}()}var nn=Fv;function at(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var Is=globalThis.CustomEvent??Event;async function*rr(t,e={}){let r=e.concurrency??1/0;r<1&&(r=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,i=[],s=at(),c=at(),a=!1,u,l=!1;o.addEventListener("task-complete",()=>{c.resolve()}),Promise.resolve().then(async()=>{try{for await(let h of t){if(i.length===r&&(s=at(),await s.promise),l)break;let p={done:!1};i.push(p),h().then(w=>{p.done=!0,p.ok=!0,p.value=w,o.dispatchEvent(new Is("task-complete"))},w=>{p.done=!0,p.err=w,o.dispatchEvent(new Is("task-complete"))})}a=!0,o.dispatchEvent(new Is("task-complete"))}catch(h){u=h,o.dispatchEvent(new Is("task-complete"))}});function d(){return n?i[0]?.done:!!i.find(h=>h.done)}function*m(){for(;i.length>0&&i[0].done;){let h=i[0];if(i.shift(),h.ok)yield h.value;else throw l=!0,s.resolve(),h.err;s.resolve()}}function*f(){for(;d();)for(let h=0;h<i.length;h++)if(i[h].done){let p=i[h];if(i.splice(h,1),h--,p.ok)yield p.value;else throw l=!0,s.resolve(),p.err;s.resolve()}}for(;;){if(d()||(c=at(),await c.promise),u!=null)throw u;if(n?yield*m():yield*f(),a&&i.length===0)break}}var Ls=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},on=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ls(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new Ls(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var nl=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function sn(t={}){return Mv(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Mv(t,e){e=e??{};let r=e.onEnd,n=new on,o,i,s,c=at(),a=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((w,g)=>{i=b=>{i=null,n.push(b);try{w(t(n))}catch(k){g(k)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=at()})}},u=w=>i!=null?i(w):(n.push(w),o),l=w=>(n=new on,i!=null?i({error:w}):(n.push({error:w}),o)),d=w=>{if(s)return o;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:w})},m=w=>s?o:(s=!0,w!=null?l(w):u({done:!0})),f=()=>(n=new on,m(),{done:!0}),h=w=>(m(w),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:a,return:f,throw:h,push:d,end:m,get readableLength(){return n.size},onEmpty:async w=>{let g=w?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let b,k;g!=null&&(b=new Promise((v,C)=>{k=()=>{C(new nl)},g.addEventListener("abort",k)}));try{await Promise.race([c.promise,b])}finally{k!=null&&g!=null&&g?.removeEventListener("abort",k)}}},r==null)return o;let p=o;return o={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(w){return p.throw(w),r!=null&&(r(w),r=void 0),{done:!0}},return(){return p.return(),r!=null&&(r(),r=void 0),{done:!0}},push:d,end(w){return p.end(w),r!=null&&(r(w),r=void 0),o},get readableLength(){return p.readableLength}},o}function Rv(t){return t[Symbol.asyncIterator]!=null}function Ov(...t){let e=[];for(let r of t)Rv(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=sn({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let o of n)r.push(o)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var Dg=Ov;function an(t,...e){if(t==null)throw new Error("Empty pipeline");if(ol(t)){let n=t;t=()=>n.source}else if(Ug(t)||Ng(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&ol(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)ol(r[n])&&(r[n]=$v(r[n]));return zv(...r)}var zv=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Ng=t=>t?.[Symbol.asyncIterator]!=null,Ug=t=>t?.[Symbol.iterator]!=null,ol=t=>t==null?!1:t.sink!=null&&t.source!=null,$v=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=sn({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let o,i=t.source;if(Ng(i))o=async function*(){yield*i,n.end()};else if(Ug(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Dg(n,o())}return t.source};var Hv=(t,e,r,n,o,i,s)=>{async function*c(a={}){let u=a.offset??0,l=a.length??e.Links.length,d=e.Links.slice(u,l);a.onProgress?.(new ae("unixfs:exporter:walk:directory",{cid:t})),yield*an(d,m=>nn(m,f=>async()=>{let h=f.Name??"",p=`${n}/${h}`;return(await o(f.Hash,h,p,[],i+1,s,a)).entry}),m=>rr(m,{ordered:!0}),m=>Lg(m,f=>f!=null))}return c},Pg=Hv;var or=V(Ye(),1);var Wg=V(Mg(),1);var go=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},sl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Rg=t=>globalThis.DOMException===void 0?new sl(t):new DOMException(t),Og=t=>{let e=t.reason===void 0?Rg("This operation was aborted."):t.reason;return e instanceof Error?e:Rg(e)};function al(t,e,r,n){let o,i=new Promise((s,c)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){s(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:a}=n;a.aborted&&c(Og(a)),a.addEventListener("abort",()=>{c(Og(a))})}o=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{s(r())}catch(l){c(l)}return}let a=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new go(a);typeof t.cancel=="function"&&t.cancel(),c(u)},e),(async()=>{try{s(await t)}catch(a){c(a)}finally{n.customTimers.clearTimeout.call(void 0,o)}})()});return i.clear=()=>{clearTimeout(o),o=void 0},i}function cl(t,e,r){let n=0,o=t.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;r(t[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var nr=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},ct,wo=class{constructor(){ct.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&nr(this,ct,"f")[this.size-1].priority>=r.priority){nr(this,ct,"f").push(n);return}let o=cl(nr(this,ct,"f"),n,(i,s)=>s.priority-i.priority);nr(this,ct,"f").splice(o,0,n)}dequeue(){let e=nr(this,ct,"f").shift();return e?.run}filter(e){return nr(this,ct,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return nr(this,ct,"f").length}};ct=new WeakMap;var W=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},I=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},X,xo,ko,Ct,Rs,vo,Ns,Oe,bo,ve,Us,Ee,Eo,Bt,Ps,zg,$g,Vg,Hg,jg,Fs,ul,ll,Os,qg,Ms,zs=class extends Error{},So=class extends Wg.default{constructor(e){var r,n,o,i;if(super(),X.add(this),xo.set(this,void 0),ko.set(this,void 0),Ct.set(this,0),Rs.set(this,void 0),vo.set(this,void 0),Ns.set(this,0),Oe.set(this,void 0),bo.set(this,void 0),ve.set(this,void 0),Us.set(this,void 0),Ee.set(this,0),Eo.set(this,void 0),Bt.set(this,void 0),Ps.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:wo,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(i=(o=e.interval)===null||o===void 0?void 0:o.toString())!==null&&i!==void 0?i:""}\` (${typeof e.interval})`);W(this,xo,e.carryoverConcurrencyCount,"f"),W(this,ko,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),W(this,Rs,e.intervalCap,"f"),W(this,vo,e.interval,"f"),W(this,ve,new e.queueClass,"f"),W(this,Us,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,W(this,Ps,e.throwOnTimeout===!0,"f"),W(this,Bt,e.autoStart===!1,"f")}get concurrency(){return I(this,Eo,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);W(this,Eo,e,"f"),I(this,X,"m",Os).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:I(this,Ps,"f"),...r},new Promise((n,o)=>{I(this,ve,"f").enqueue(async()=>{var i,s,c;W(this,Ee,(s=I(this,Ee,"f"),s++,s),"f"),W(this,Ct,(c=I(this,Ct,"f"),c++,c),"f");try{if(!((i=r.signal)===null||i===void 0)&&i.aborted)throw new zs("The task was aborted.");let a=e({signal:r.signal});r.timeout&&(a=al(Promise.resolve(a),r.timeout)),r.signal&&(a=Promise.race([a,I(this,X,"m",qg).call(this,r.signal)]));let u=await a;n(u),this.emit("completed",u)}catch(a){if(a instanceof go&&!r.throwOnTimeout){n();return}o(a),this.emit("error",a)}finally{I(this,X,"m",Vg).call(this)}},r),this.emit("add"),I(this,X,"m",Fs).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return I(this,Bt,"f")?(W(this,Bt,!1,"f"),I(this,X,"m",Os).call(this),this):this}pause(){W(this,Bt,!0,"f")}clear(){W(this,ve,new(I(this,Us,"f")),"f")}async onEmpty(){I(this,ve,"f").size!==0&&await I(this,X,"m",Ms).call(this,"empty")}async onSizeLessThan(e){I(this,ve,"f").size<e||await I(this,X,"m",Ms).call(this,"next",()=>I(this,ve,"f").size<e)}async onIdle(){I(this,Ee,"f")===0&&I(this,ve,"f").size===0||await I(this,X,"m",Ms).call(this,"idle")}get size(){return I(this,ve,"f").size}sizeBy(e){return I(this,ve,"f").filter(e).length}get pending(){return I(this,Ee,"f")}get isPaused(){return I(this,Bt,"f")}};xo=new WeakMap,ko=new WeakMap,Ct=new WeakMap,Rs=new WeakMap,vo=new WeakMap,Ns=new WeakMap,Oe=new WeakMap,bo=new WeakMap,ve=new WeakMap,Us=new WeakMap,Ee=new WeakMap,Eo=new WeakMap,Bt=new WeakMap,Ps=new WeakMap,X=new WeakSet,zg=function(){return I(this,ko,"f")||I(this,Ct,"f")<I(this,Rs,"f")},$g=function(){return I(this,Ee,"f")<I(this,Eo,"f")},Vg=function(){var e;W(this,Ee,(e=I(this,Ee,"f"),e--,e),"f"),I(this,X,"m",Fs).call(this),this.emit("next")},Hg=function(){I(this,X,"m",ll).call(this),I(this,X,"m",ul).call(this),W(this,bo,void 0,"f")},jg=function(){let e=Date.now();if(I(this,Oe,"f")===void 0){let r=I(this,Ns,"f")-e;if(r<0)W(this,Ct,I(this,xo,"f")?I(this,Ee,"f"):0,"f");else return I(this,bo,"f")===void 0&&W(this,bo,setTimeout(()=>{I(this,X,"m",Hg).call(this)},r),"f"),!0}return!1},Fs=function(){if(I(this,ve,"f").size===0)return I(this,Oe,"f")&&clearInterval(I(this,Oe,"f")),W(this,Oe,void 0,"f"),this.emit("empty"),I(this,Ee,"f")===0&&this.emit("idle"),!1;if(!I(this,Bt,"f")){let e=!I(this,X,"a",jg);if(I(this,X,"a",zg)&&I(this,X,"a",$g)){let r=I(this,ve,"f").dequeue();return r?(this.emit("active"),r(),e&&I(this,X,"m",ul).call(this),!0):!1}}return!1},ul=function(){I(this,ko,"f")||I(this,Oe,"f")!==void 0||(W(this,Oe,setInterval(()=>{I(this,X,"m",ll).call(this)},I(this,vo,"f")),"f"),W(this,Ns,Date.now()+I(this,vo,"f"),"f"))},ll=function(){I(this,Ct,"f")===0&&I(this,Ee,"f")===0&&I(this,Oe,"f")&&(clearInterval(I(this,Oe,"f")),W(this,Oe,void 0,"f")),W(this,Ct,I(this,xo,"f")?I(this,Ee,"f"):0,"f"),I(this,X,"m",Os).call(this)},Os=function(){for(;I(this,X,"m",Fs).call(this););},qg=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new zs("The task was aborted."))},{once:!0})})},Ms=async function(e,r){return new Promise(n=>{let o=()=>{r&&!r()||(this.off(e,o),n())};this.on(e,o)})};async function Kg(t,e,r,n,o,i,s){if(e instanceof Uint8Array){let u=er(e,n,o,i);r.push(u);return}if(e.Data==null)throw(0,or.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let c;try{c=tn.unmarshal(e.Data)}catch(u){throw(0,or.default)(u,"ERR_NOT_UNIXFS")}if(c.data!=null){let u=c.data,l=er(u,n,o,i);r.push(l),n+=BigInt(l.byteLength)}let a=[];if(e.Links.length!==c.blockSizes.length)throw(0,or.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let u=0;u<e.Links.length;u++){let l=e.Links[u],d=n,m=d+c.blockSizes[u];if((o>=d&&o<m||i>=d&&i<=m||o<d&&i>m)&&a.push({link:l,blockStart:n}),n=m,n>i)break}await an(a,u=>nn(u,l=>async()=>{let d=await t.get(l.link.Hash,s);return{...l,block:d}}),u=>rr(u,{ordered:!0}),async u=>{for await(let{link:l,block:d,blockStart:m}of u){let f;switch(l.Hash.code){case Jt:f=Ge(d);break;case Un:f=d;break;default:r.end((0,or.default)(new Error(`Unsupported codec: ${l.Hash.code}`),"ERR_NOT_UNIXFS"));return}let h=new So({concurrency:1});h.on("error",p=>{r.end(p)}),h.add(async()=>{s.onProgress?.(new ae("unixfs:exporter:walk:file",{cid:l.Hash})),await Kg(t,f,r,m,o,i,s)}),await h.onIdle()}}),n>=i&&r.end()}var qv=(t,e,r,n,o,i,s)=>{async function*c(a={}){let u=r.fileSize();if(u===void 0)throw new Error("File was a directory");let{start:l,end:d}=Zr(u,a.offset,a.length);if(d===0n)return;let m=0n,f=d-l,h=sn();a.onProgress?.(new ae("unixfs:exporter:walk:file",{cid:t})),Kg(s,e,h,0n,l,d,a).catch(p=>{h.end(p)});for await(let p of h)if(p!=null){if(m+=BigInt(p.byteLength),m>f)throw h.end(),(0,or.default)(new Error("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect"),"ERR_OVER_READ");m===f&&h.end(),a.onProgress?.(new ae("unixfs:exporter:progress:unixfs:file",{bytesRead:m,totalBytes:f,fileSize:u})),yield p}if(m<f)throw(0,or.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return c},fl=qv;var Wv=(t,e,r,n,o,i,s)=>{function c(a={}){return a.onProgress?.(new ae("unixfs:exporter:walk:hamt-sharded-directory",{cid:t})),Gg(e,n,o,i,s,a)}return c};async function*Gg(t,e,r,n,o,i){let s=t.Links,c=an(s,a=>nn(a,u=>async()=>{let l=u.Name!=null?u.Name.substring(2):null;if(l!=null&&l!==""){let d=await r(u.Hash,l,`${e}/${l}`,[],n+1,o,i);return{entries:d.entry==null?[]:[d.entry]}}else{let d=await o.get(u.Hash,i);return t=Ge(d),i.onProgress?.(new ae("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:Gg(t,e,r,n,o,i)}}}),a=>rr(a,{ordered:!0}));for await(let{entries:a}of c)yield*a}var Qg=Wv;var Kv=(t,e)=>t.Links.find(n=>n.Name===e)?.Hash,Gv={raw:fl,file:fl,directory:Pg,"hamt-sharded-directory":Qg,metadata:(t,e,r,n,o,i,s)=>()=>[],symlink:(t,e,r,n,o,i,s)=>()=>[]},Qv=async(t,e,r,n,o,i,s,c)=>{let a=await s.get(t,c),u=Ge(a),l,d;if(e==null&&(e=t.toString()),u.Data==null)throw(0,Ao.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{l=tn.unmarshal(u.Data)}catch(f){throw(0,Ao.default)(f,"ERR_NOT_UNIXFS")}if(r==null&&(r=e),n.length>0){let f;if(l?.type==="hamt-sharded-directory"?f=await Ig(u,n[0],s):f=Kv(u,n[0]),f==null)throw(0,Ao.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let h=n.shift(),p=`${r}/${h}`;d={cid:f,toResolve:n,name:h??"",path:p}}let m=Gv[l.type](t,u,l,r,o,i,s);if(m==null)throw(0,Ao.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return l.isDirectory()?{entry:{type:"directory",name:e,path:r,cid:t,content:m,unixfs:l,depth:i,node:u,size:l.fileSize()},next:d}:{entry:{type:"file",name:e,path:r,cid:t,content:m,unixfs:l,depth:i,node:u,size:l.fileSize()},next:d}},Jg=Qv;var Jv={[Jt]:Jg,[Un]:og,[ka]:eg,[Ym.code]:rg},Yg=async(t,e,r,n,o,i,s)=>{let c=Jv[t.code];if(c==null)throw(0,Xg.default)(new Error(`No resolver for code ${t.code}`),"ERR_NO_RESOLVER");return c(t,e,r,n,Yg,o,i,s)},Zg=Yg;var Xv=(t="")=>(t.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),Yv=t=>{if(t instanceof Uint8Array)return{cid:j.decode(t),toResolve:[]};let e=j.asCID(t);if(e!=null)return{cid:e,toResolve:[]};if(typeof t=="string"){t.indexOf("/ipfs/")===0&&(t=t.substring(6));let r=Xv(t);return{cid:j.parse(r[0]),toResolve:r.slice(1)}}throw(0,$s.default)(new Error(`Unknown path type ${t}`),"ERR_BAD_PATH")};async function*Zv(t,e,r={}){let{cid:n,toResolve:o}=Yv(t),i=n.toString(),s=i,c=o.length;for(;;){let a=await Zg(n,i,s,o,c,e,r);if(a.entry==null&&a.next==null)throw(0,$s.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");if(a.entry!=null&&(yield a.entry),a.next==null)return;o=a.next.toResolve,n=a.next.cid,i=a.next.name,s=a.next.path}}async function ew(t,e,r={}){let n=await Qm(Zv(t,e,r));if(n==null)throw(0,$s.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");return n}var eE=Wm(),tE=_t({fileChunkEncoder:gt,smallFileEncoder:gt,chunker:ku(1024*1024),fileLayout:cs(1024)});async function tw(t){let e=rE(t),r=await nE(e);return{cid:r.at(-1).cid,blocks:r}}async function rw(t,e,r){let n=await ew(e.toString(),t,{length:r.size}),o=[];for await(let i of n.content())o.push(i);return new File(o,n.name,{type:r.type,lastModified:0})}function rE(t){let{readable:e,writable:r}=new TransformStream({},eE),n=qm({writable:r,settings:tE}),o=new dl("",t);return(async()=>(await o.finalize(n),await n.close()))(),e}async function nE(t){let e=[];return await t.pipeTo(new WritableStream({write(r){e.push(r)}})),e}var dl=class{#e;name;constructor(e,r){this.name=e,this.#e=r}async finalize(e){let r=oo(e);return await this.#e.stream().pipeTo(new WritableStream({async write(n){await r.write(n)}})),await r.close()}};async function iw(t,e,r,n){let o;for(let i of r){let s=await oE(t,i);o=await yp(t,e,i.key,s,n);let c=o.root.toString();o.additions.some(u=>u.cid.toString()===c)||await t.get(o.root)||(console.error(`missing root in additions: ${o.additions.length} ${c} keys: ${r.map(l=>l.key).toString()}`),o.head=e);for(let{cid:u,bytes:l}of[...o.additions,...o.removals,o.event])t.putSync(u,l);e=o.head}return{head:e}}async function oE(t,e){let r;e.del?r={del:!0}:(await iE(t,e.value),r={doc:e.value});let n=await Ve({value:r,hasher:le,codec:q});return t.putSync(n.cid,n.bytes),n.cid}async function iE(t,e){e._files&&await nw(t,e._files),e._publicFiles&&await nw(t,e._publicFiles,!0)}async function nw(t,e,r=!1){let n=t.parent,o=new xt(n);n.transactions.add(o);let i=[],s=0;for(let c in e)if(File===e[c].constructor){let a=e[c];s+=a.size;let{cid:u,blocks:l}=await tw(a);i.push(c);for(let d of l)o.putSync(d.cid,d.bytes);e[c]={cid:u,type:a.type,size:a.size}}if(s>1024*1024*1)throw new Error("Sync limit for files in a single update is 1MB");if(i.length){let c=await n.loader?.commit(o,{files:e},{public:r});if(c)for(let a of i)e[a]={car:c,...e[a]}}}async function sw(t,e,r){if(!e.length)throw new Error("Getting from an empty database");let n=await mp(t,e,r);if(!n)throw new Error(`Missing key ${r}`);return await ml(t,n)}function yl(t,{doc:e}){e&&(e._files&&ow(t,e._files),e._publicFiles&&ow(t,e._publicFiles,!0))}function ow(t,e,r=!1){for(let n in e){let o=e[n];if(o.cid&&(r&&(o.url=`https://${o.cid.toString()}.ipfs.w3s.link/`),o.car&&t.loader)){let i=t.loader;o.file=async()=>await rw({get:async s=>{let a=await(await i.loadFileCar(o.car,r)).get(s);if(!a)throw new Error(`Missing block ${s.toString()}`);return a.bytes}},o.cid,o)}e[n]=o}}async function ml(t,e){let r=await t.get(e);if(!r)throw new Error(`Missing linked block ${e.toString()}`);let{value:n}=await mt({bytes:r.bytes,hasher:le,codec:q});return yl(t,n),n}var hl=class extends We{async get(e){try{return await super.get(e)}catch(r){return console.error("missing event",e.toString(),r),{value:null}}}};async function _o(t,e,r,n){let o=n.dirty?new hl(t):new We(t);return{result:(await pl(t,o,e,r,[],new Set,new Set,n.limit||1/0)).reverse(),head:e}}async function pl(t,e,r,n,o=[],i,s,c){if(c<=0)return o;let a=r.map(u=>u.toString());for(let u of n)if(a.includes(u.toString()))return o;for(let u of r){if(s.has(u.toString()))continue;s.add(u.toString());let{value:l}=await e.get(u);if(!l)continue;let{key:d,value:m}=l.data;if(i.has(d))l.parents&&(o=await pl(t,e,l.parents,n,o,i,s,c));else{i.add(d);let f=await ml(t,m);o.push({key:d,value:f.doc,del:f.del}),c--,l.parents&&(o=await pl(t,e,l.parents,n,o,i,s,c))}}return o}async function*aw(t,e){for await(let[r,n]of Lc(t,e)){let o=await ml(t,n);yield{key:r,value:o.doc,del:o.del}}}async function*cw(t,e){for await(let r of Cc(t,e))yield r}async function uw(t,e){let r=new Pi(t),n=new xt(t);for await(let[,i]of Lc(r,e))if(!await r.get(i))throw new Error("Missing block: "+i.toString());for await(let i of Cc(r,e));let o=await Or(r,e);for(let{cid:i,bytes:s}of[...o.additions,...o.removals])n.putSync(i,s);await _o(r,e,[],{});for(let i of r.cids){let s=await t.get(i);if(!s)throw new Error("Missing block: "+i.toString());await n.put(i,s.bytes)}await t.commitCompaction(n,e)}var Hs=class{head=[];zoomers=new Set;watchers=new Set;blocks=null;setHead(e){this.head=e}async applyHead(e,r,n,o=null){let i=this.head.sort((u,l)=>u.toString().localeCompare(l.toString()));if(r=r.sort((u,l)=>u.toString().localeCompare(l.toString())),i.toString()===r.toString()){this.watchers.forEach(u=>u(o||[]));return}let s=n.sort((u,l)=>u.toString().localeCompare(l.toString()));if(i.toString()===s.toString()){this.setHead(r),this.watchers.forEach(u=>u(o||[]));return}let c=async(u,l)=>{if(u instanceof xt)return await l(u);if(!this.blocks)throw new Error("missing blocks");return await this.blocks.transaction(l,void 0,{noLoader:!0})},{head:a}=await c(e,async u=>{let l=this.head;for(let m of r)l=await jn(u,l,m);let d=await Or(u,l);for(let{cid:m,bytes:f}of[...d.additions,...d.removals])u.putSync(m,f);return{head:l}});this.watchers.size&&!o&&(o=(await _o(this.blocks,a,n,{})).result),this.setHead(a),this.zoomers.forEach(u=>u()),this.watchers.forEach(u=>u(o||[]))}onTick(e){this.watchers.add(e)}onZoom(e){this.zoomers.add(e)}};var js=class{name;opts={};ready;blocks;indexBlocks;indexers=new Map;clock=new Hs;constructor(e,r){this.name=e||null,this.opts=r||this.opts,this.blocks=new Ui(this.name,this.clock,this.opts),this.clock.blocks=this.blocks,this.indexBlocks=new Ni(this.opts.persistIndexes&&this.name?this.name+".idx":null,this,this.opts),this.ready=Promise.all([this.blocks.ready,this.indexBlocks.ready]).then(()=>{}),this.clock.onZoom(()=>{for(let n of this.indexers.values())n._resetIndex()})}async bulk(e,r){return await this.ready,await this.blocks.transaction(async n=>{let o=[...this.clock.head],{head:i}=await iw(n,this.clock.head,e,r);return e=e.map(({key:s,value:c,del:a})=>(yl(this.blocks,{doc:c}),{key:s,value:c,del:a})),await this.clock.applyHead(n,i,o,e),{head:i}})}async allDocs(){await this.ready;let e=[];for await(let r of aw(this.blocks,this.clock.head))e.push(r);return{result:e,head:this.clock.head}}async vis(){await this.ready;let e=[];for await(let r of cw(this.blocks,this.clock.head))e.push(r);return e.join(`
4
4
  `)}async get(e){await this.ready;let r=await sw(this.blocks,this.clock.head,e);return r.del?null:r}async changes(e=[],r={}){return await this.ready,await _o(this.blocks,this.clock.head,e,r)}async compact(){if(await this.ready,!(this.blocks.loader&&this.blocks.loader.carLog.length<2))return await uw(this.blocks,this.clock.head)}};var ir=class{static databases=new Map;name;opts={};_listeners=new Set;_crdt;_writeQueue;constructor(e,r){this.name=e||null,this.opts=r||this.opts,this._crdt=new js(e,this.opts),this._crdt.clock.onTick(n=>{this._notify(n)}),this._writeQueue=xl(async n=>await this._crdt.bulk(n))}async get(e){let r=await this._crdt.get(e).catch(o=>{throw o.message=`Not found: ${e} - `+o.message,o});if(!r)throw new Error(`Not found: ${e}`);let{doc:n}=r;return{_id:e,...n}}async put(e){let{_id:r,...n}=e,o=r||bl(),i=await this._writeQueue.push({key:o,value:n});return{id:o,clock:i?.head}}async del(e){let r=await this._writeQueue.push({key:e,del:!0});return{id:e,clock:r?.head}}async changes(e=[],r={}){let{result:n,head:o}=await this._crdt.changes(e,r);return{rows:n.map(({key:s,value:c,del:a})=>({key:s,value:a?{_id:s,_deleted:!0}:{_id:s,...c}})),clock:o}}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}async query(e,r={}){return await(typeof e=="string"?Rr({_crdt:this._crdt},e):Rr({_crdt:this._crdt},aE(e.toString()),e)).query(r)}async compact(){await this._crdt.compact()}async getDashboardURL(e=!0){let r="https://dashboard.fireproof.storage/";if(!this._crdt.blocks.loader?.remoteCarStore)return new URL("/howto",r);e&&await this.compact();let n=await this._crdt.blocks.loader?.metaStore?.load();if(!n)throw new Error("Can't sync empty database: save data first");if(n.length>1)throw new Error("Can't sync database with split heads: make an update first");let o=n[0],i={car:o.car.toString()};o.key&&(i.key=o.key.toString()),this.name&&(i.name=this.name);let s=new URL("/import#"+new URLSearchParams(i).toString(),r);return console.log("Import to dashboard: "+s.toString()),s}openDashboard(){this.getDashboardURL().then(e=>{e&&window.open(e.toString(),"_blank")})}async _notify(e){if(this._listeners.size){let r=e.map(({key:n,value:o})=>({_id:n,...o}));for(let n of this._listeners)await(async()=>await n(r))().catch(o=>{console.error("subscriber error",o)})}}};function sE(t,e){return ir.databases.has(t)||ir.databases.set(t,new ir(t,e)),ir.databases.get(t)}function aE(t){let e=/\(([^,()]+,\s*[^,()]+|\[[^\]]+\],\s*[^,()]+)\)/g,r=null;return Array.from(t.matchAll(e),o=>o[1].trim()).length===0&&(r=/=>\s*(.*)/.exec(t)),r?r[1]:t}0&&(module.exports={DataStore,Database,Index,Loader,MetaStore,STORAGE_VERSION,cidListIncludes,encodeCarFile,encodeCarHeader,fireproof,index,parseCarFile,toHexString});
5
5
  /*! Bundled license information:
6
6