@fireproof/core 0.13.2 → 0.13.3-dev
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/fireproof.cjs +4 -28
- package/dist/browser/fireproof.cjs.map +4 -4
- package/dist/browser/fireproof.esm.js +4 -28
- package/dist/browser/fireproof.esm.js.map +4 -4
- package/dist/browser/fireproof.iife.js +4 -28
- package/dist/browser/fireproof.iife.js.map +4 -4
- package/dist/node/fireproof.cjs +4 -49
- package/dist/node/fireproof.cjs.map +4 -4
- package/dist/node/fireproof.esm.js +4 -49
- package/dist/node/fireproof.esm.js.map +4 -4
- package/dist/types/database.d.ts +0 -1
- package/dist/types/fireproof.d.ts +3 -2
- package/dist/types/loader.d.ts +10 -12
- package/dist/types/loaders.d.ts +3 -6
- package/dist/types/remote-wal.d.ts +25 -0
- package/dist/types/store-browser.d.ts +2 -1
- package/dist/types/store-fs.d.ts +2 -1
- package/dist/types/store.d.ts +1 -24
- package/dist/types/types.d.ts +0 -25
- package/dist/types/version.d.ts +1 -1
- package/package.json +1 -1
- package/dist/types/connect-ipfs-account.d.ts +0 -48
- package/dist/types/connect-ipfs-helpers.d.ts +0 -31
- package/dist/types/connect-ipfs.d.ts +0 -27
- package/dist/types/connect-s3.d.ts +0 -11
- package/dist/types/connect.d.ts +0 -39
- package/dist/types/connection.d.ts +0 -15
- package/dist/types/store-remote.d.ts +0 -27
@@ -1,33 +1,9 @@
|
|
1
|
-
"use strict";var Fireproof=(()=>{var u8=Object.create;var za=Object.defineProperty;var l8=Object.getOwnPropertyDescriptor;var d8=Object.getOwnPropertyNames;var f8=Object.getPrototypeOf,h8=Object.prototype.hasOwnProperty;var p8=(t,e,r)=>e in t?za(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),F=(t,e)=>{for(var r in e)za(t,r,{get:e[r],enumerable:!0})},Nk=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of d8(e))!h8.call(t,o)&&o!==r&&za(t,o,{get:()=>e[o],enumerable:!(n=l8(e,o))||n.enumerable});return t};var De=(t,e,r)=>(r=t!=null?u8(f8(t)):{},Nk(e||!t||!t.__esModule?za(r,"default",{value:t,enumerable:!0}):r,t)),m8=t=>Nk(za({},"__esModule",{value:!0}),t);var w=(t,e,r)=>(p8(t,typeof e!="symbol"?e+"":e,r),r),mm=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)};var $=(t,e,r)=>(mm(t,e,"read from private field"),r?r.call(t):e.get(t)),ke=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},fe=(t,e,r,n)=>(mm(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r);var ym=(t,e,r,n)=>({set _(o){fe(t,e,o,r)},get _(){return $(t,e,n)}}),yo=(t,e,r)=>(mm(t,e,"access private method"),r);var $k=oe((wn,Ok)=>{var kl=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global,vl=function(){function t(){this.fetch=!1,this.DOMException=kl.DOMException}return t.prototype=kl,new t}();(function(t){var e=function(r){var n=typeof t<"u"&&t||typeof self<"u"&&self||typeof n<"u"&&n,o={searchParams:"URLSearchParams"in n,iterable:"Symbol"in n&&"iterator"in Symbol,blob:"FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in n,arrayBuffer:"ArrayBuffer"in n};function s(v){return v&&DataView.prototype.isPrototypeOf(v)}if(o.arrayBuffer)var i=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],a=ArrayBuffer.isView||function(v){return v&&i.indexOf(Object.prototype.toString.call(v))>-1};function c(v){if(typeof v!="string"&&(v=String(v)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(v)||v==="")throw new TypeError('Invalid character in header field name: "'+v+'"');return v.toLowerCase()}function u(v){return typeof v!="string"&&(v=String(v)),v}function l(v){var I={next:function(){var O=v.shift();return{done:O===void 0,value:O}}};return o.iterable&&(I[Symbol.iterator]=function(){return I}),I}function d(v){this.map={},v instanceof d?v.forEach(function(I,O){this.append(O,I)},this):Array.isArray(v)?v.forEach(function(I){this.append(I[0],I[1])},this):v&&Object.getOwnPropertyNames(v).forEach(function(I){this.append(I,v[I])},this)}d.prototype.append=function(v,I){v=c(v),I=u(I);var O=this.map[v];this.map[v]=O?O+", "+I:I},d.prototype.delete=function(v){delete this.map[c(v)]},d.prototype.get=function(v){return v=c(v),this.has(v)?this.map[v]:null},d.prototype.has=function(v){return this.map.hasOwnProperty(c(v))},d.prototype.set=function(v,I){this.map[c(v)]=u(I)},d.prototype.forEach=function(v,I){for(var O in this.map)this.map.hasOwnProperty(O)&&v.call(I,this.map[O],O,this)},d.prototype.keys=function(){var v=[];return this.forEach(function(I,O){v.push(O)}),l(v)},d.prototype.values=function(){var v=[];return this.forEach(function(I){v.push(I)}),l(v)},d.prototype.entries=function(){var v=[];return this.forEach(function(I,O){v.push([O,I])}),l(v)},o.iterable&&(d.prototype[Symbol.iterator]=d.prototype.entries);function p(v){if(v.bodyUsed)return Promise.reject(new TypeError("Already read"));v.bodyUsed=!0}function f(v){return new Promise(function(I,O){v.onload=function(){I(v.result)},v.onerror=function(){O(v.error)}})}function h(v){var I=new FileReader,O=f(I);return I.readAsArrayBuffer(v),O}function m(v){var I=new FileReader,O=f(I);return I.readAsText(v),O}function b(v){for(var I=new Uint8Array(v),O=new Array(I.length),Pe=0;Pe<I.length;Pe++)O[Pe]=String.fromCharCode(I[Pe]);return O.join("")}function g(v){if(v.slice)return v.slice(0);var I=new Uint8Array(v.byteLength);return I.set(new Uint8Array(v)),I.buffer}function k(){return this.bodyUsed=!1,this._initBody=function(v){this.bodyUsed=this.bodyUsed,this._bodyInit=v,v?typeof v=="string"?this._bodyText=v:o.blob&&Blob.prototype.isPrototypeOf(v)?this._bodyBlob=v:o.formData&&FormData.prototype.isPrototypeOf(v)?this._bodyFormData=v:o.searchParams&&URLSearchParams.prototype.isPrototypeOf(v)?this._bodyText=v.toString():o.arrayBuffer&&o.blob&&s(v)?(this._bodyArrayBuffer=g(v.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(v)||a(v))?this._bodyArrayBuffer=g(v):this._bodyText=v=Object.prototype.toString.call(v):this._bodyText="",this.headers.get("content-type")||(typeof v=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):o.searchParams&&URLSearchParams.prototype.isPrototypeOf(v)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o.blob&&(this.blob=function(){var v=p(this);if(v)return v;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){if(this._bodyArrayBuffer){var v=p(this);return v||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else return this.blob().then(h)}),this.text=function(){var v=p(this);if(v)return v;if(this._bodyBlob)return m(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(b(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},o.formData&&(this.formData=function(){return this.text().then(J)}),this.json=function(){return this.text().then(JSON.parse)},this}var E=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function _(v){var I=v.toUpperCase();return E.indexOf(I)>-1?I:v}function P(v,I){if(!(this instanceof P))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');I=I||{};var O=I.body;if(v instanceof P){if(v.bodyUsed)throw new TypeError("Already read");this.url=v.url,this.credentials=v.credentials,I.headers||(this.headers=new d(v.headers)),this.method=v.method,this.mode=v.mode,this.signal=v.signal,!O&&v._bodyInit!=null&&(O=v._bodyInit,v.bodyUsed=!0)}else this.url=String(v);if(this.credentials=I.credentials||this.credentials||"same-origin",(I.headers||!this.headers)&&(this.headers=new d(I.headers)),this.method=_(I.method||this.method||"GET"),this.mode=I.mode||this.mode||null,this.signal=I.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&O)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(O),(this.method==="GET"||this.method==="HEAD")&&(I.cache==="no-store"||I.cache==="no-cache")){var Pe=/([?&])_=[^&]*/;if(Pe.test(this.url))this.url=this.url.replace(Pe,"$1_="+new Date().getTime());else{var ze=/\?/;this.url+=(ze.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}P.prototype.clone=function(){return new P(this,{body:this._bodyInit})};function J(v){var I=new FormData;return v.trim().split("&").forEach(function(O){if(O){var Pe=O.split("="),ze=Pe.shift().replace(/\+/g," "),Ee=Pe.join("=").replace(/\+/g," ");I.append(decodeURIComponent(ze),decodeURIComponent(Ee))}}),I}function L(v){var I=new d,O=v.replace(/\r?\n[\t ]+/g," ");return O.split("\r").map(function(Pe){return Pe.indexOf(`
|
2
|
-
`)===0?Pe.substr(1,Pe.length):Pe}).forEach(function(Pe){var ze=Pe.split(":"),Ee=ze.shift().trim();if(Ee){var bl=ze.join(":").trim();I.append(Ee,bl)}}),I}k.call(P.prototype);function G(v,I){if(!(this instanceof G))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');I||(I={}),this.type="default",this.status=I.status===void 0?200:I.status,this.ok=this.status>=200&&this.status<300,this.statusText=I.statusText===void 0?"":""+I.statusText,this.headers=new d(I.headers),this.url=I.url||"",this._initBody(v)}k.call(G.prototype),G.prototype.clone=function(){return new G(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},G.error=function(){var v=new G(null,{status:0,statusText:""});return v.type="error",v};var ot=[301,302,303,307,308];G.redirect=function(v,I){if(ot.indexOf(I)===-1)throw new RangeError("Invalid status code");return new G(null,{status:I,headers:{location:v}})},r.DOMException=n.DOMException;try{new r.DOMException}catch{r.DOMException=function(I,O){this.message=I,this.name=O;var Pe=Error(I);this.stack=Pe.stack},r.DOMException.prototype=Object.create(Error.prototype),r.DOMException.prototype.constructor=r.DOMException}function yn(v,I){return new Promise(function(O,Pe){var ze=new P(v,I);if(ze.signal&&ze.signal.aborted)return Pe(new r.DOMException("Aborted","AbortError"));var Ee=new XMLHttpRequest;function bl(){Ee.abort()}Ee.onload=function(){var Mt={status:Ee.status,statusText:Ee.statusText,headers:L(Ee.getAllResponseHeaders()||"")};Mt.url="responseURL"in Ee?Ee.responseURL:Mt.headers.get("X-Request-URL");var xl="response"in Ee?Ee.response:Ee.responseText;setTimeout(function(){O(new G(xl,Mt))},0)},Ee.onerror=function(){setTimeout(function(){Pe(new TypeError("Network request failed"))},0)},Ee.ontimeout=function(){setTimeout(function(){Pe(new TypeError("Network request failed"))},0)},Ee.onabort=function(){setTimeout(function(){Pe(new r.DOMException("Aborted","AbortError"))},0)};function c8(Mt){try{return Mt===""&&n.location.href?n.location.href:Mt}catch{return Mt}}Ee.open(ze.method,c8(ze.url),!0),ze.credentials==="include"?Ee.withCredentials=!0:ze.credentials==="omit"&&(Ee.withCredentials=!1),"responseType"in Ee&&(o.blob?Ee.responseType="blob":o.arrayBuffer&&ze.headers.get("Content-Type")&&ze.headers.get("Content-Type").indexOf("application/octet-stream")!==-1&&(Ee.responseType="arraybuffer")),I&&typeof I.headers=="object"&&!(I.headers instanceof d)?Object.getOwnPropertyNames(I.headers).forEach(function(Mt){Ee.setRequestHeader(Mt,u(I.headers[Mt]))}):ze.headers.forEach(function(Mt,xl){Ee.setRequestHeader(xl,Mt)}),ze.signal&&(ze.signal.addEventListener("abort",bl),Ee.onreadystatechange=function(){Ee.readyState===4&&ze.signal.removeEventListener("abort",bl)}),Ee.send(typeof ze._bodyInit>"u"?null:ze._bodyInit)})}return yn.polyfill=!0,n.fetch||(n.fetch=yn,n.Headers=d,n.Request=P,n.Response=G),r.Headers=d,r.Request=P,r.Response=G,r.fetch=yn,r}({})})(vl);vl.fetch.ponyfill=!0;delete vl.fetch.polyfill;var Ks=kl.fetch?kl:vl;wn=Ks.fetch;wn.default=Ks.fetch;wn.fetch=Ks.fetch;wn.Headers=Ks.Headers;wn.Request=Ks.Request;wn.Response=Ks.Response;Ok.exports=wn});var J1=oe((OW,Z1)=>{Z1.exports=Ey;var K1=128,b6=127,x6=~b6,k6=Math.pow(2,31);function Ey(t,e,r){if(Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw Ey.bytes=0,new RangeError("Could not encode varint");e=e||[],r=r||0;for(var n=r;t>=k6;)e[r++]=t&255|K1,t/=128;for(;t&x6;)e[r++]=t&255|K1,t>>>=7;return e[r]=t|0,Ey.bytes=r-n+1,e}});var Y1=oe(($W,X1)=>{X1.exports=_y;var v6=128,Q1=127;function _y(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a||o>49)throw _y.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&Q1)<<o:(i&Q1)*Math.pow(2,o),o+=7}while(i>=v6);return _y.bytes=s-n,r}});var tS=oe((MW,eS)=>{var S6=Math.pow(2,7),E6=Math.pow(2,14),_6=Math.pow(2,21),A6=Math.pow(2,28),D6=Math.pow(2,35),T6=Math.pow(2,42),C6=Math.pow(2,49),I6=Math.pow(2,56),B6=Math.pow(2,63);eS.exports=function(t){return t<S6?1:t<E6?2:t<_6?3:t<A6?4:t<D6?5:t<T6?6:t<C6?7:t<I6?8:t<B6?9:10}});var Ql=oe((FW,rS)=>{rS.exports={encode:J1(),decode:Y1(),encodingLength:tS()}});var NE=oe(()=>{});var P2=oe((wZ,B2)=>{function Zt(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}B2.exports=Zt;Zt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Zt.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Zt.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0};Zt.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Zt.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};Zt.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};Zt.prototype.start=Zt.prototype.try;Zt.prototype.errors=function(){return this._errors};Zt.prototype.attempts=function(){return this._attempts};Zt.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,r=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(t[s]||0)+1;t[s]=i,i>=r&&(e=o,r=i)}return e}});var L2=oe(as=>{var dN=P2();as.operation=function(t){var e=as.timeouts(t);return new dN(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};as.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var r in t)e[r]=t[r];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<e.retries;o++)n.push(this.createTimeout(o,e));return t&&t.forever&&!n.length&&n.push(this.createTimeout(o,e)),n.sort(function(s,i){return s-i}),n};as.createTimeout=function(t,e){var r=e.randomize?Math.random()+1:1,n=Math.round(r*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return n=Math.min(n,e.maxTimeout),n};as.wrap=function(t,e,r){if(e instanceof Array&&(r=e,e=null),!r){r=[];for(var n in t)typeof t[n]=="function"&&r.push(n)}for(var o=0;o<r.length;o++){var s=r[o],i=t[s];t[s]=function(c){var u=as.operation(e),l=Array.prototype.slice.call(arguments,1),d=l.pop();l.push(function(p){u.retry(p)||(p&&(arguments[0]=u.mainError()),d.apply(this,arguments))}),u.attempt(function(){c.apply(t,l)})}.bind(t,i),t[s].options=e}}});var R2=oe((xZ,U2)=>{U2.exports=L2()});var $2=oe(Nf=>{"use strict";var Yw=class extends Error{constructor(e="Request timed out"){super(e),this.name="TimeoutError"}};Nf.TimeoutError=Yw;var eb=class extends Error{constructor(e="The operation was aborted."){super(e),this.name="AbortError"}};Nf.AbortError=eb;var tb=class extends Error{constructor(e){super(e.statusText),this.name="HTTPError",this.response=e}};Nf.HTTPError=tb});var Qc=oe((Hi,M2)=>{"use strict";var yN=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},cs=yN();M2.exports=Hi=cs.fetch;cs.fetch&&(Hi.default=cs.fetch.bind(cs));Hi.Headers=cs.Headers;Hi.Request=cs.Request;Hi.Response=cs.Response});var F2=oe((DZ,rb)=>{"use strict";globalThis.fetch&&globalThis.Headers&&globalThis.Request&&globalThis.Response?rb.exports={default:globalThis.fetch,Headers:globalThis.Headers,Request:globalThis.Request,Response:globalThis.Response}:rb.exports={default:Qc().default,Headers:Qc().Headers,Request:Qc().Request,Response:Qc().Response}});var j2=oe((TZ,z2)=>{"use strict";z2.exports=F2()});var q2=oe((CZ,H2)=>{"use strict";var{TimeoutError:gN,AbortError:wN}=$2(),{Response:W2,Request:bN,Headers:ob,default:xN}=j2(),kN=(t,e={})=>{let r=new XMLHttpRequest;r.open(e.method||"GET",t.toString(),!0);let{timeout:n,headers:o}=e;if(n&&n>0&&n<1/0&&(r.timeout=n),e.overrideMimeType!=null&&r.overrideMimeType(e.overrideMimeType),o)for(let[s,i]of new ob(o))r.setRequestHeader(s,i);return e.signal&&(e.signal.onabort=()=>r.abort()),e.onUploadProgress&&(r.upload.onprogress=e.onUploadProgress),r.responseType="arraybuffer",new Promise((s,i)=>{let a=c=>{switch(c.type){case"error":{s(W2.error());break}case"load":{s(new nb(r.responseURL,r.response,{status:r.status,statusText:r.statusText,headers:EN(r.getAllResponseHeaders())}));break}case"timeout":{i(new gN);break}case"abort":{i(new wN);break}default:break}};r.onerror=a,r.onload=a,r.ontimeout=a,r.onabort=a,r.send(e.body)})},vN=xN,SN=(t,e={})=>e.onUploadProgress!=null?kN(t,e):vN(t,e),EN=t=>{let e=new ob;for(let r of t.trim().split(/[\r\n]+/)){let n=r.indexOf(": ");n>0&&e.set(r.slice(0,n),r.slice(n+1))}return e},nb=class extends W2{constructor(e,r,n){super(r,n),Object.defineProperty(this,"url",{value:e})}};H2.exports={fetch:SN,Request:bN,Headers:ob}});var nA=oe((XZ,rA)=>{"use strict";rA.exports=HN;function HN(t,e){for(var r=new Array(arguments.length-1),n=0,o=2,s=!0;o<arguments.length;)r[n++]=arguments[o++];return new Promise(function(a,c){r[n]=function(l){if(s)if(s=!1,l)c(l);else{for(var d=new Array(arguments.length-1),p=0;p<d.length;)d[p++]=arguments[p];a.apply(null,d)}};try{t.apply(e||null,r)}catch(u){s&&(s=!1,c(u))}})}});var aA=oe(iA=>{"use strict";var Wf=iA;Wf.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 Ki=new Array(64),sA=new Array(123);for(lr=0;lr<64;)sA[Ki[lr]=lr<26?lr+65:lr<52?lr+71:lr<62?lr-4:lr-59|43]=lr++;var lr;Wf.encode=function(e,r,n){for(var o=null,s=[],i=0,a=0,c;r<n;){var u=e[r++];switch(a){case 0:s[i++]=Ki[u>>2],c=(u&3)<<4,a=1;break;case 1:s[i++]=Ki[c|u>>4],c=(u&15)<<2,a=2;break;case 2:s[i++]=Ki[c|u>>6],s[i++]=Ki[u&63],a=0;break}i>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),i=0)}return a&&(s[i++]=Ki[c],s[i++]=61,a===1&&(s[i++]=61)),o?(i&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))};var oA="invalid encoding";Wf.decode=function(e,r,n){for(var o=n,s=0,i,a=0;a<e.length;){var c=e.charCodeAt(a++);if(c===61&&s>1)break;if((c=sA[c])===void 0)throw Error(oA);switch(s){case 0:i=c,s=1;break;case 1:r[n++]=i<<2|(c&48)>>4,i=c,s=2;break;case 2:r[n++]=(i&15)<<4|(c&60)>>2,i=c,s=3;break;case 3:r[n++]=(i&3)<<6|c,s=0;break}}if(s===1)throw Error(oA);return n-o};Wf.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var uA=oe((eJ,cA)=>{"use strict";cA.exports=Hf;function Hf(){this._listeners={}}Hf.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};Hf.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};Hf.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 yA=oe((tJ,mA)=>{"use strict";mA.exports=lA(lA);function lA(t){return typeof Float32Array<"u"?function(){var e=new Float32Array([-0]),r=new Uint8Array(e.buffer),n=r[3]===128;function o(c,u,l){e[0]=c,u[l]=r[0],u[l+1]=r[1],u[l+2]=r[2],u[l+3]=r[3]}function s(c,u,l){e[0]=c,u[l]=r[3],u[l+1]=r[2],u[l+2]=r[1],u[l+3]=r[0]}t.writeFloatLE=n?o:s,t.writeFloatBE=n?s:o;function i(c,u){return r[0]=c[u],r[1]=c[u+1],r[2]=c[u+2],r[3]=c[u+3],e[0]}function a(c,u){return r[3]=c[u],r[2]=c[u+1],r[1]=c[u+2],r[0]=c[u+3],e[0]}t.readFloatLE=n?i:a,t.readFloatBE=n?a:i}():function(){function e(n,o,s,i){var a=o<0?1:0;if(a&&(o=-o),o===0)n(1/o>0?0:2147483648,s,i);else if(isNaN(o))n(2143289344,s,i);else if(o>34028234663852886e22)n((a<<31|2139095040)>>>0,s,i);else if(o<11754943508222875e-54)n((a<<31|Math.round(o/1401298464324817e-60))>>>0,s,i);else{var c=Math.floor(Math.log(o)/Math.LN2),u=Math.round(o*Math.pow(2,-c)*8388608)&8388607;n((a<<31|c+127<<23|u)>>>0,s,i)}}t.writeFloatLE=e.bind(null,dA),t.writeFloatBE=e.bind(null,fA);function r(n,o,s){var i=n(o,s),a=(i>>31)*2+1,c=i>>>23&255,u=i&8388607;return c===255?u?NaN:a*(1/0):c===0?a*1401298464324817e-60*u:a*Math.pow(2,c-150)*(u+8388608)}t.readFloatLE=r.bind(null,hA),t.readFloatBE=r.bind(null,pA)}(),typeof Float64Array<"u"?function(){var e=new Float64Array([-0]),r=new Uint8Array(e.buffer),n=r[7]===128;function o(c,u,l){e[0]=c,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 s(c,u,l){e[0]=c,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:s,t.writeDoubleBE=n?s:o;function i(c,u){return r[0]=c[u],r[1]=c[u+1],r[2]=c[u+2],r[3]=c[u+3],r[4]=c[u+4],r[5]=c[u+5],r[6]=c[u+6],r[7]=c[u+7],e[0]}function a(c,u){return r[7]=c[u],r[6]=c[u+1],r[5]=c[u+2],r[4]=c[u+3],r[3]=c[u+4],r[2]=c[u+5],r[1]=c[u+6],r[0]=c[u+7],e[0]}t.readDoubleLE=n?i:a,t.readDoubleBE=n?a:i}():function(){function e(n,o,s,i,a,c){var u=i<0?1:0;if(u&&(i=-i),i===0)n(0,a,c+o),n(1/i>0?0:2147483648,a,c+s);else if(isNaN(i))n(0,a,c+o),n(2146959360,a,c+s);else if(i>17976931348623157e292)n(0,a,c+o),n((u<<31|2146435072)>>>0,a,c+s);else{var l;if(i<22250738585072014e-324)l=i/5e-324,n(l>>>0,a,c+o),n((u<<31|l/4294967296)>>>0,a,c+s);else{var d=Math.floor(Math.log(i)/Math.LN2);d===1024&&(d=1023),l=i*Math.pow(2,-d),n(l*4503599627370496>>>0,a,c+o),n((u<<31|d+1023<<20|l*1048576&1048575)>>>0,a,c+s)}}}t.writeDoubleLE=e.bind(null,dA,0,4),t.writeDoubleBE=e.bind(null,fA,4,0);function r(n,o,s,i,a){var c=n(i,a+o),u=n(i,a+s),l=(u>>31)*2+1,d=u>>>20&2047,p=4294967296*(u&1048575)+c;return d===2047?p?NaN:l*(1/0):d===0?l*5e-324*p:l*Math.pow(2,d-1075)*(p+4503599627370496)}t.readDoubleLE=r.bind(null,hA,0,4),t.readDoubleBE=r.bind(null,pA,4,0)}(),t}function dA(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 fA(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 hA(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function pA(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var gA=oe((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 bA=oe(wA=>{"use strict";var lb=wA;lb.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};lb.read=function(e,r,n){var o=n-r;if(o<1)return"";for(var s=null,i=[],a=0,c;r<n;)c=e[r++],c<128?i[a++]=c:c>191&&c<224?i[a++]=(c&31)<<6|e[r++]&63:c>239&&c<365?(c=((c&7)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,i[a++]=55296+(c>>10),i[a++]=56320+(c&1023)):i[a++]=(c&15)<<12|(e[r++]&63)<<6|e[r++]&63,a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,i)),a=0);return s?(a&&s.push(String.fromCharCode.apply(String,i.slice(0,a))),s.join("")):String.fromCharCode.apply(String,i.slice(0,a))};lb.write=function(e,r,n){for(var o=n,s,i,a=0;a<e.length;++a)s=e.charCodeAt(a),s<128?r[n++]=s:s<2048?(r[n++]=s>>6|192,r[n++]=s&63|128):(s&64512)===55296&&((i=e.charCodeAt(a+1))&64512)===56320?(s=65536+((s&1023)<<10)+(i&1023),++a,r[n++]=s>>18|240,r[n++]=s>>12&63|128,r[n++]=s>>6&63|128,r[n++]=s&63|128):(r[n++]=s>>12|224,r[n++]=s>>6&63|128,r[n++]=s&63|128);return n-o}});var kA=oe((nJ,xA)=>{"use strict";xA.exports=qN;function qN(t,e,r){var n=r||8192,o=n>>>1,s=null,i=n;return function(c){if(c<1||c>o)return t(c);i+c>n&&(s=t(n),i=0);var u=e.call(s,i,i+=c);return i&7&&(i=(i|7)+1),u}}});var SA=oe((oJ,vA)=>{"use strict";vA.exports=Ye;var Yc=sn();function Ye(t,e){this.lo=t>>>0,this.hi=e>>>0}var us=Ye.zero=new Ye(0,0);us.toNumber=function(){return 0};us.zzEncode=us.zzDecode=function(){return this};us.length=function(){return 1};var VN=Ye.zeroHash="\0\0\0\0\0\0\0\0";Ye.fromNumber=function(e){if(e===0)return us;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 Ye(n,o)};Ye.from=function(e){if(typeof e=="number")return Ye.fromNumber(e);if(Yc.isString(e))if(Yc.Long)e=Yc.Long.fromString(e);else return Ye.fromNumber(parseInt(e,10));return e.low||e.high?new Ye(e.low>>>0,e.high>>>0):us};Ye.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};Ye.prototype.toLong=function(e){return Yc.Long?new Yc.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Xn=String.prototype.charCodeAt;Ye.fromHash=function(e){return e===VN?us:new Ye((Xn.call(e,0)|Xn.call(e,1)<<8|Xn.call(e,2)<<16|Xn.call(e,3)<<24)>>>0,(Xn.call(e,4)|Xn.call(e,5)<<8|Xn.call(e,6)<<16|Xn.call(e,7)<<24)>>>0)};Ye.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)};Ye.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};Ye.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};Ye.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 sn=oe(db=>{"use strict";var H=db;H.asPromise=nA();H.base64=aA();H.EventEmitter=uA();H.float=yA();H.inquire=gA();H.utf8=bA();H.pool=kA();H.LongBits=SA();H.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);H.global=H.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||db;H.emptyArray=Object.freeze?Object.freeze([]):[];H.emptyObject=Object.freeze?Object.freeze({}):{};H.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};H.isString=function(e){return typeof e=="string"||e instanceof String};H.isObject=function(e){return e&&typeof e=="object"};H.isset=H.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};H.Buffer=function(){try{var t=H.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();H._Buffer_from=null;H._Buffer_allocUnsafe=null;H.newBuffer=function(e){return typeof e=="number"?H.Buffer?H._Buffer_allocUnsafe(e):new H.Array(e):H.Buffer?H._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};H.Array=typeof Uint8Array<"u"?Uint8Array:Array;H.Long=H.global.dcodeIO&&H.global.dcodeIO.Long||H.global.Long||H.inquire("long");H.key2Re=/^true|false|0|1$/;H.key32Re=/^-?(?:0|[1-9][0-9]*)$/;H.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;H.longToHash=function(e){return e?H.LongBits.from(e).toHash():H.LongBits.zeroHash};H.longFromHash=function(e,r){var n=H.LongBits.fromHash(e);return H.Long?H.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function EA(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}H.merge=EA;H.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function _A(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&&EA(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}H.newError=_A;H.ProtocolError=_A("ProtocolError");H.oneOfGetter=function(e){for(var r={},n=0;n<e.length;++n)r[e[n]]=1;return function(){for(var o=Object.keys(this),s=o.length-1;s>-1;--s)if(r[o[s]]===1&&this[o[s]]!==void 0&&this[o[s]]!==null)return o[s]}};H.oneOfSetter=function(e){return function(r){for(var n=0;n<e.length;++n)e[n]!==r&&delete this[e[n]]}};H.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};H._configure=function(){var t=H.Buffer;if(!t){H._Buffer_from=H._Buffer_allocUnsafe=null;return}H._Buffer_from=t.from!==Uint8Array.from&&t.from||function(r,n){return new t(r,n)},H._Buffer_allocUnsafe=t.allocUnsafe||function(r){return new t(r)}}});var Vf=oe((iJ,CA)=>{"use strict";CA.exports=me;var Jt=sn(),fb,qf=Jt.LongBits,AA=Jt.base64,DA=Jt.utf8;function eu(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function pb(){}function GN(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function me(){this.len=0,this.head=new eu(pb,0,0),this.tail=this.head,this.states=null}var TA=function(){return Jt.Buffer?function(){return(me.create=function(){return new fb})()}:function(){return new me}};me.create=TA();me.alloc=function(e){return new Jt.Array(e)};Jt.Array!==Array&&(me.alloc=Jt.pool(me.alloc,Jt.Array.prototype.subarray));me.prototype._push=function(e,r,n){return this.tail=this.tail.next=new eu(e,r,n),this.len+=r,this};function mb(t,e,r){e[r]=t&255}function KN(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function yb(t,e){this.len=t,this.next=void 0,this.val=e}yb.prototype=Object.create(eu.prototype);yb.prototype.fn=KN;me.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new yb((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};me.prototype.int32=function(e){return e<0?this._push(gb,10,qf.fromNumber(e)):this.uint32(e)};me.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function gb(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}me.prototype.uint64=function(e){var r=qf.from(e);return this._push(gb,r.length(),r)};me.prototype.int64=me.prototype.uint64;me.prototype.sint64=function(e){var r=qf.from(e).zzEncode();return this._push(gb,r.length(),r)};me.prototype.bool=function(e){return this._push(mb,1,e?1:0)};function hb(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}me.prototype.fixed32=function(e){return this._push(hb,4,e>>>0)};me.prototype.sfixed32=me.prototype.fixed32;me.prototype.fixed64=function(e){var r=qf.from(e);return this._push(hb,4,r.lo)._push(hb,4,r.hi)};me.prototype.sfixed64=me.prototype.fixed64;me.prototype.float=function(e){return this._push(Jt.float.writeFloatLE,4,e)};me.prototype.double=function(e){return this._push(Jt.float.writeDoubleLE,8,e)};var ZN=Jt.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]};me.prototype.bytes=function(e){var r=e.length>>>0;if(!r)return this._push(mb,1,0);if(Jt.isString(e)){var n=me.alloc(r=AA.length(e));AA.decode(e,n,0),e=n}return this.uint32(r)._push(ZN,r,e)};me.prototype.string=function(e){var r=DA.length(e);return r?this.uint32(r)._push(DA.write,r,e):this._push(mb,1,0)};me.prototype.fork=function(){return this.states=new GN(this),this.head=this.tail=new eu(pb,0,0),this.len=0,this};me.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 eu(pb,0,0),this.len=0),this};me.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};me.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};me._configure=function(t){fb=t,me.create=TA(),fb._configure()}});var wb=oe((aJ,BA)=>{"use strict";BA.exports=Ir;var IA=Vf();(Ir.prototype=Object.create(IA.prototype)).constructor=Ir;var Yn=sn();function Ir(){IA.call(this)}Ir._configure=function(){Ir.alloc=Yn._Buffer_allocUnsafe,Ir.writeBytesBuffer=Yn.Buffer&&Yn.Buffer.prototype instanceof Uint8Array&&Yn.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++]}};Ir.prototype.bytes=function(e){Yn.isString(e)&&(e=Yn._Buffer_from(e,"base64"));var r=e.length>>>0;return this.uint32(r),r&&this._push(Ir.writeBytesBuffer,r,e),this};function JN(t,e,r){t.length<40?Yn.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}Ir.prototype.string=function(e){var r=Yn.Buffer.byteLength(e);return this.uint32(r),r&&this._push(JN,r,e),this};Ir._configure()});var Kf=oe((cJ,NA)=>{"use strict";NA.exports=We;var Br=sn(),xb,UA=Br.LongBits,QN=Br.utf8;function dr(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function We(t){this.buf=t,this.pos=0,this.len=t.length}var PA=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new We(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new We(e);throw Error("illegal buffer")},RA=function(){return Br.Buffer?function(r){return(We.create=function(o){return Br.Buffer.isBuffer(o)?new xb(o):PA(o)})(r)}:PA};We.create=RA();We.prototype._slice=Br.Array.prototype.subarray||Br.Array.prototype.slice;We.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,dr(this,10);return e}}();We.prototype.int32=function(){return this.uint32()|0};We.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function bb(){var t=new UA(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 dr(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 dr(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")}We.prototype.bool=function(){return this.uint32()!==0};function Gf(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}We.prototype.fixed32=function(){if(this.pos+4>this.len)throw dr(this,4);return Gf(this.buf,this.pos+=4)};We.prototype.sfixed32=function(){if(this.pos+4>this.len)throw dr(this,4);return Gf(this.buf,this.pos+=4)|0};function LA(){if(this.pos+8>this.len)throw dr(this,8);return new UA(Gf(this.buf,this.pos+=4),Gf(this.buf,this.pos+=4))}We.prototype.float=function(){if(this.pos+4>this.len)throw dr(this,4);var e=Br.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};We.prototype.double=function(){if(this.pos+8>this.len)throw dr(this,4);var e=Br.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};We.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw dr(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)};We.prototype.string=function(){var e=this.bytes();return QN.read(e,0,e.length)};We.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw dr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw dr(this);while(this.buf[this.pos++]&128);return this};We.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};We._configure=function(t){xb=t,We.create=RA(),xb._configure();var e=Br.Long?"toLong":"toNumber";Br.merge(We.prototype,{int64:function(){return bb.call(this)[e](!1)},uint64:function(){return bb.call(this)[e](!0)},sint64:function(){return bb.call(this).zzDecode()[e](!1)},fixed64:function(){return LA.call(this)[e](!0)},sfixed64:function(){return LA.call(this)[e](!1)}})}});var kb=oe((uJ,MA)=>{"use strict";MA.exports=ls;var $A=Kf();(ls.prototype=Object.create($A.prototype)).constructor=ls;var OA=sn();function ls(t){$A.call(this,t)}ls._configure=function(){OA.Buffer&&(ls.prototype._slice=OA.Buffer.prototype.slice)};ls.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))};ls._configure()});var zA=oe((lJ,FA)=>{"use strict";FA.exports=tu;var vb=sn();(tu.prototype=Object.create(vb.EventEmitter.prototype)).constructor=tu;function tu(t,e,r){if(typeof t!="function")throw TypeError("rpcImpl must be a function");vb.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!r}tu.prototype.rpcCall=function t(e,r,n,o,s){if(!o)throw TypeError("request must be specified");var i=this;if(!s)return vb.asPromise(t,i,e,r,n,o);if(!i.rpcImpl){setTimeout(function(){s(Error("already ended"))},0);return}try{return i.rpcImpl(e,r[i.requestDelimited?"encodeDelimited":"encode"](o).finish(),function(c,u){if(c)return i.emit("error",c,e),s(c);if(u===null){i.end(!0);return}if(!(u instanceof n))try{u=n[i.responseDelimited?"decodeDelimited":"decode"](u)}catch(l){return i.emit("error",l,e),s(l)}return i.emit("data",u,e),s(null,u)})}catch(a){i.emit("error",a,e),setTimeout(function(){s(a)},0);return}};tu.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var WA=oe(jA=>{"use strict";var XN=jA;XN.Service=zA()});var qA=oe((fJ,HA)=>{"use strict";HA.exports={}});var KA=oe(GA=>{"use strict";var bt=GA;bt.build="minimal";bt.Writer=Vf();bt.BufferWriter=wb();bt.Reader=Kf();bt.BufferReader=kb();bt.util=sn();bt.rpc=WA();bt.roots=qA();bt.configure=VA;function VA(){bt.util._configure(),bt.Writer._configure(bt.BufferWriter),bt.Reader._configure(bt.BufferReader)}VA()});var JA=oe((pJ,ZA)=>{"use strict";ZA.exports=KA()});var VD=oe((mu,hh)=>{(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 s(f,h){return f<<h|f>>>32-h}function i(f){return f^=f>>>16,f=o(f,2246822507),f^=f>>>13,f=o(f,3266489909),f^=f>>>16,f}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 m=[0,0,0,0];return m[3]+=f[3]+h[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=f[2]+h[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=f[1]+h[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=f[0]+h[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}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 m=[0,0,0,0];return m[3]+=f[3]*h[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=f[2]*h[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=f[3]*h[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=f[1]*h[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=f[2]*h[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=f[3]*h[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=f[0]*h[3]+f[1]*h[2]+f[2]*h[1]+f[3]*h[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[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 p(f){return f=d(f,[0,f[0]>>>1]),f=c(f,[4283543511,3981806797]),f=d(f,[0,f[0]>>>1]),f=c(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 m=f.length%4,b=f.length-m,g=h,k=0,E=3432918353,_=461845907,P=0;P<b;P=P+4)k=f[P]|f[P+1]<<8|f[P+2]<<16|f[P+3]<<24,k=o(k,E),k=s(k,15),k=o(k,_),g^=k,g=s(g,13),g=o(g,5)+3864292196;switch(k=0,m){case 3:k^=f[P+2]<<16;case 2:k^=f[P+1]<<8;case 1:k^=f[P],k=o(k,E),k=s(k,15),k=o(k,_),g^=k}return g^=f.length,g=i(g),g>>>0},r.x86.hash128=function(f,h){if(r.inputValidation&&!n(f))return e;h=h||0;for(var m=f.length%16,b=f.length-m,g=h,k=h,E=h,_=h,P=0,J=0,L=0,G=0,ot=597399067,yn=2869860233,v=951274213,I=2716044179,O=0;O<b;O=O+16)P=f[O]|f[O+1]<<8|f[O+2]<<16|f[O+3]<<24,J=f[O+4]|f[O+5]<<8|f[O+6]<<16|f[O+7]<<24,L=f[O+8]|f[O+9]<<8|f[O+10]<<16|f[O+11]<<24,G=f[O+12]|f[O+13]<<8|f[O+14]<<16|f[O+15]<<24,P=o(P,ot),P=s(P,15),P=o(P,yn),g^=P,g=s(g,19),g+=k,g=o(g,5)+1444728091,J=o(J,yn),J=s(J,16),J=o(J,v),k^=J,k=s(k,17),k+=E,k=o(k,5)+197830471,L=o(L,v),L=s(L,17),L=o(L,I),E^=L,E=s(E,15),E+=_,E=o(E,5)+2530024501,G=o(G,I),G=s(G,18),G=o(G,ot),_^=G,_=s(_,13),_+=g,_=o(_,5)+850148119;switch(P=0,J=0,L=0,G=0,m){case 15:G^=f[O+14]<<16;case 14:G^=f[O+13]<<8;case 13:G^=f[O+12],G=o(G,I),G=s(G,18),G=o(G,ot),_^=G;case 12:L^=f[O+11]<<24;case 11:L^=f[O+10]<<16;case 10:L^=f[O+9]<<8;case 9:L^=f[O+8],L=o(L,v),L=s(L,17),L=o(L,I),E^=L;case 8:J^=f[O+7]<<24;case 7:J^=f[O+6]<<16;case 6:J^=f[O+5]<<8;case 5:J^=f[O+4],J=o(J,yn),J=s(J,16),J=o(J,v),k^=J;case 4:P^=f[O+3]<<24;case 3:P^=f[O+2]<<16;case 2:P^=f[O+1]<<8;case 1:P^=f[O],P=o(P,ot),P=s(P,15),P=o(P,yn),g^=P}return g^=f.length,k^=f.length,E^=f.length,_^=f.length,g+=k,g+=E,g+=_,k+=g,E+=g,_+=g,g=i(g),k=i(k),E=i(E),_=i(_),g+=k,g+=E,g+=_,k+=g,E+=g,_+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(k>>>0).toString(16)).slice(-8)+("00000000"+(E>>>0).toString(16)).slice(-8)+("00000000"+(_>>>0).toString(16)).slice(-8)},r.x64.hash128=function(f,h){if(r.inputValidation&&!n(f))return e;h=h||0;for(var m=f.length%16,b=f.length-m,g=[0,h],k=[0,h],E=[0,0],_=[0,0],P=[2277735313,289559509],J=[1291169091,658871167],L=0;L<b;L=L+16)E=[f[L+4]|f[L+5]<<8|f[L+6]<<16|f[L+7]<<24,f[L]|f[L+1]<<8|f[L+2]<<16|f[L+3]<<24],_=[f[L+12]|f[L+13]<<8|f[L+14]<<16|f[L+15]<<24,f[L+8]|f[L+9]<<8|f[L+10]<<16|f[L+11]<<24],E=c(E,P),E=u(E,31),E=c(E,J),g=d(g,E),g=u(g,27),g=a(g,k),g=a(c(g,[0,5]),[0,1390208809]),_=c(_,J),_=u(_,33),_=c(_,P),k=d(k,_),k=u(k,31),k=a(k,g),k=a(c(k,[0,5]),[0,944331445]);switch(E=[0,0],_=[0,0],m){case 15:_=d(_,l([0,f[L+14]],48));case 14:_=d(_,l([0,f[L+13]],40));case 13:_=d(_,l([0,f[L+12]],32));case 12:_=d(_,l([0,f[L+11]],24));case 11:_=d(_,l([0,f[L+10]],16));case 10:_=d(_,l([0,f[L+9]],8));case 9:_=d(_,[0,f[L+8]]),_=c(_,J),_=u(_,33),_=c(_,P),k=d(k,_);case 8:E=d(E,l([0,f[L+7]],56));case 7:E=d(E,l([0,f[L+6]],48));case 6:E=d(E,l([0,f[L+5]],40));case 5:E=d(E,l([0,f[L+4]],32));case 4:E=d(E,l([0,f[L+3]],24));case 3:E=d(E,l([0,f[L+2]],16));case 2:E=d(E,l([0,f[L+1]],8));case 1:E=d(E,[0,f[L]]),E=c(E,P),E=u(E,31),E=c(E,J),g=d(g,E)}return g=d(g,[0,f.length]),k=d(k,[0,f.length]),g=a(g,k),k=a(k,g),g=p(g),k=p(k),g=a(g,k),k=a(k,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(k[0]>>>0).toString(16)).slice(-8)+("00000000"+(k[1]>>>0).toString(16)).slice(-8)},typeof mu<"u"?(typeof hh<"u"&&hh.exports&&(mu=hh.exports=r),mu.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)})(mu)});var tx=oe((FJ,GD)=>{GD.exports=VD()});var FT=oe((eX,bx)=>{"use strict";var t$=Object.prototype.hasOwnProperty,ht="~";function Iu(){}Object.create&&(Iu.prototype=Object.create(null),new Iu().__proto__||(ht=!1));function r$(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function MT(t,e,r,n,o){if(typeof r!="function")throw new TypeError("The listener must be a function");var s=new r$(r,n||t,o),i=ht?ht+e:e;return t._events[i]?t._events[i].fn?t._events[i]=[t._events[i],s]:t._events[i].push(s):(t._events[i]=s,t._eventsCount++),t}function Bh(t,e){--t._eventsCount===0?t._events=new Iu:delete t._events[e]}function at(){this._events=new Iu,this._eventsCount=0}at.prototype.eventNames=function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)t$.call(r,n)&&e.push(ht?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};at.prototype.listeners=function(e){var r=ht?ht+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};at.prototype.listenerCount=function(e){var r=ht?ht+e:e,n=this._events[r];return n?n.fn?1:n.length:0};at.prototype.emit=function(e,r,n,o,s,i){var a=ht?ht+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,l,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,r),!0;case 3:return c.fn.call(c.context,r,n),!0;case 4:return c.fn.call(c.context,r,n,o),!0;case 5:return c.fn.call(c.context,r,n,o,s),!0;case 6:return c.fn.call(c.context,r,n,o,s,i),!0}for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c.fn.apply(c.context,l)}else{var p=c.length,f;for(d=0;d<p;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),u){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,r);break;case 3:c[d].fn.call(c[d].context,r,n);break;case 4:c[d].fn.call(c[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];c[d].fn.apply(c[d].context,l)}}return!0};at.prototype.on=function(e,r,n){return MT(this,e,r,n,!1)};at.prototype.once=function(e,r,n){return MT(this,e,r,n,!0)};at.prototype.removeListener=function(e,r,n,o){var s=ht?ht+e:e;if(!this._events[s])return this;if(!r)return Bh(this,s),this;var i=this._events[s];if(i.fn)i.fn===r&&(!o||i.once)&&(!n||i.context===n)&&Bh(this,s);else{for(var a=0,c=[],u=i.length;a<u;a++)(i[a].fn!==r||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Bh(this,s)}return this};at.prototype.removeAllListeners=function(e){var r;return e?(r=ht?ht+e:e,this._events[r]&&Bh(this,r)):(this._events=new Iu,this._eventsCount=0),this};at.prototype.off=at.prototype.removeListener;at.prototype.addListener=at.prototype.on;at.prefixed=ht;at.EventEmitter=at;typeof bx<"u"&&(bx.exports=at)});var nI=oe(Gx=>{Gx.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"+_M(String(r),3)+"M"+String(n);return t>0?"F"+o:"D"+rI(o)};Gx.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?rI(t):t).slice(2).split("M");return+((e?"-":"")+r[1]+"e"+String(Number(r[0])-500))};function rI(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 _M(t,e){return" ".repeat(e-t.length).substr(0,e)+t}});var sI=oe(oI=>{var AM={"?":"?@","!":"??",'"':"?%"};function DM(t){return/[!"]/.test(t)?t.replace(/[\?!"]/g,function(e){return AM[e]}):t}var TM={"?@":"?","??":"!","?%":'"'};function CM(t){return/\?[%\?@]/.test(t)?t.replace(/\?[%\?@]/g,function(e){return TM[e]}):t}oI.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 s=o.length;if(s==0)return"K!";for(var i=r(o[0]),a=1;a<s;a++)i+='"'+r(o[a]);return"K"+i+"!"}function r(o){return typeof o=="object"?e(o):DM(t.encode(o))}function n(o){if(o==="A")return null;if(o==="K!")return[];for(var s=o.split('"'),i=[[]],a,c=0,u=s.length,l=0;l<u;l++){for(var d=s[l],p=d.length,f=0;d[f]=="K";)f++;for(var h=0;d[p-h-1]=="!";)h++;for(var m=d.slice(f,p-h),g=c+f,b=c;b<g;b++)i[b+1]=[],i[b].push(i[b+1]),c=g,a=i[c];m.length!==0&&a.push(t.decode(CM(m)));for(var g=c-h,b=g;b<c;b++)i[b+1]=[],c=g,a=i[c]}return i[0][0]}}});var aI=oe(qe=>{var IM=nI(),BM=sI(),fte=qe.flip=function(t){var e=t.toString(),r="";for(var n in e)r+=e[n]=="."?".":9-+e[n];return r};qe.number=IM;qe.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)}};qe.encode=function(t){return qe[typeof t].encode(t)};qe.decode=function(t){if(t==="")return t;if(!iI[t[0]])throw new Error("no decoder for:"+JSON.stringify(t));return iI[t[0]](t)};qe.object=BM.factory(qe);qe.boolean={encode:function(t){return t?"C":"B"},decode:function(t){return t==="C"}};qe.undefined={encode:function(t){return"L"},decode:function(){}};var iI={A:qe.object.decode,B:qe.boolean.decode,C:qe.boolean.decode,D:qe.number.decode,F:qe.number.decode,J:qe.string.decode,K:qe.object.decode,L:qe.undefined.decode};qe.buffer=!1;qe.type="charwise"});var Fr=oe((Kte,CI)=>{"use strict";function TI(t,e){for(let r in e)Object.defineProperty(t,r,{value:e[r],enumerable:!0,configurable:!0});return t}function KM(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 TI(t,r)}catch{r.message=t.message,r.stack=t.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(t)),TI(new o,r)}}CI.exports=KM});var JI=oe((Lre,ZI)=>{"use strict";ZI.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 s=this.get(n);o=e(o,s,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],s=e-n*7;if(!((o&1<<s)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(lF,0),c=~(4294967295<<s+1),u=KI(o&c);return a+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 s=this._data,i=[r,n];if(o)this._sortData(),s[e]=i;else{if(s.length)if(s[s.length-1][0]>=r)s.push(i);else if(s[0][0]<=r)s.unshift(i);else{let a=Math.round(s.length/2);this._data=s.slice(0,a).concat(i).concat(s.slice(a))}else this._data.push(i);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(dF),this._changedData=!1}bitField(){let e=[],r=8,n=0,o=0,s,i=this._bitArrays.slice();for(;i.length||n;){n===0&&(s=i.shift(),n=7);let c=Math.min(n,r),u=~(255<<c),l=s&u;o|=l<<8-r,s=s>>>c,n-=c,r-=c,(!r||!n&&!i.length)&&(e.push(o),o=0,r=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(fF)}};function lF(t,e){return t+KI(e)}function KI(t){let e=t;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function dF(t,e){return t[0]-e[0]}function fF(t){return t[1]}});var Aj={};F(Aj,{Database:()=>fo,Index:()=>hp,connect:()=>Up,fireproof:()=>E0,index:()=>Da});var gn=class{constructor(){w(this,"ready");w(this,"loaded");w(this,"loader");this.ready=Promise.resolve(),this.loaded=Promise.resolve()}async refresh(){await this.loader.remoteMetaStore.load("main"),await this.loader.remoteWAL?._process()}};var go=De($k(),1);var ja=class extends gn{constructor(r,n){super();w(this,"uploadUrl");w(this,"downloadUrl");this.uploadUrl=new URL(r),this.downloadUrl=new URL(n)}async dataUpload(r,n){Zs(n);let o=new URL(`${this.uploadUrl.toString()}?${new URLSearchParams({cache:Math.random().toString(),...n}).toString()}`),s=await(0,go.default)(o);if(!s.ok)throw console.log("failed to get upload url for data",n,s),new Error("failed to get upload url for data "+new Date().toISOString()+" "+s.statusText);let{uploadURL:i}=await s.json(),a=await(0,go.default)(i,{method:"PUT",body:r});if(!a.ok)throw new Error("failed to upload data "+a.statusText)}async metaUpload(r,n){gm(n);let o=new URL(`${this.uploadUrl.toString()}?${new URLSearchParams({type:"meta",...n}).toString()}`),s=await(0,go.default)(o);if(!s.ok)throw console.log("failed to get upload url for meta",n,s),new Error("failed to get upload url for meta");let{uploadURL:i}=await s.json();if(!i)throw new Error("missing uploadURL");let a=await(0,go.default)(i,{method:"PUT",body:r});if(!a.ok)throw new Error("failed to upload data "+a.statusText);return null}async dataDownload(r){Zs(r);let{type:n,name:o,car:s}=r,i=new URL(`${n}/${o}/${s}.car`,this.downloadUrl),a=await(0,go.default)(i);return a.ok?new Uint8Array(await a.arrayBuffer()):null}async metaDownload(r){gm(r);let{name:n,branch:o}=r,s=new URL(`meta/${n}/${o+".json?cache="+Math.floor(Math.random()*1e6)}`,this.downloadUrl),i=await(0,go.default)(s);return i.ok?[new Uint8Array(await i.arrayBuffer())]:null}};var sr={};F(sr,{ArchiveSchema:()=>CE,Delegation:()=>Gt,View:()=>Gt,allows:()=>G3,archive:()=>TE,create:()=>Sg,delegate:()=>Lt,exportDAG:()=>kg,extract:()=>Z3,importDAG:()=>vg,isDelegation:()=>Ro,isLink:()=>V3,view:()=>Cd});var Te={};F(Te,{code:()=>Tt,decode:()=>Ge,encode:()=>tr,name:()=>rc});var y8=["string","number","bigint","symbol"],g8=["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 Mk(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(y8.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(w8(t))return"Buffer";let r=b8(t);return r||"Object"}function w8(t){return t&&t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer.call(null,t)}function b8(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(g8.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 D=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 Js=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",x8=new TextDecoder,k8=new TextEncoder;function Sl(t){return Js&&globalThis.Buffer.isBuffer(t)}function Wa(t){return t instanceof Uint8Array?Sl(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var Wk=Js?(t,e,r)=>r-e>64?globalThis.Buffer.from(t.subarray(e,r)).toString("utf8"):zk(t,e,r):(t,e,r)=>r-e>64?x8.decode(t.subarray(e,r)):zk(t,e,r),El=Js?t=>t.length>64?globalThis.Buffer.from(t):Fk(t):t=>t.length>64?k8.encode(t):Fk(t),gr=t=>Uint8Array.from(t),Qs=Js?(t,e,r)=>Sl(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),Hk=Js?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),Wa(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},qk=Js?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function Vk(t,e){if(Sl(t)&&Sl(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 Fk(t,e=1/0){let r,n=t.length,o=null,s=[];for(let i=0;i<n;++i){if(r=t.charCodeAt(i),r>55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(i+1===n){(e-=3)>-1&&s.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),o=r;continue}r=(o-55296<<10|r-56320)+65536}else o&&(e-=3)>-1&&s.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function zk(t,e,r){let n=[];for(;e<r;){let o=t[e],s=null,i=o>239?4:o>223?3:o>191?2:1;if(e+i<=r){let a,c,u,l;switch(i){case 1:o<128&&(s=o);break;case 2:a=t[e+1],(a&192)===128&&(l=(o&31)<<6|a&63,l>127&&(s=l));break;case 3:a=t[e+1],c=t[e+2],(a&192)===128&&(c&192)===128&&(l=(o&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(s=l));break;case 4:a=t[e+1],c=t[e+2],u=t[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(o&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(s=l))}}s===null?(s=65533,i=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=i}return wm(n)}var jk=4096;function wm(t){let e=t.length;if(e<=jk)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=jk));return r}var v8=256,Ha=class{constructor(e=v8){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=qk(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=Qs(n,0,this.cursor)}else r=Hk(this.chunks,this.cursor);return e&&this.reset(),r}};var j="CBOR decode error:",jr="CBOR encode error:",qa=[];qa[23]=1;qa[24]=2;qa[25]=3;qa[26]=5;qa[27]=9;function Wr(t,e,r){if(t.length-e<r)throw new Error(`${j} not enough data for type`)}var Ze=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Et(t,e,r){Wr(t,e,1);let n=t[e];if(r.strict===!0&&n<Ze[0])throw new Error(`${j} integer encoded in more bytes than necessary (strict decode)`);return n}function _t(t,e,r){Wr(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<Ze[1])throw new Error(`${j} integer encoded in more bytes than necessary (strict decode)`);return n}function At(t,e,r){Wr(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<Ze[2])throw new Error(`${j} integer encoded in more bytes than necessary (strict decode)`);return n}function Dt(t,e,r){Wr(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],s=(BigInt(n)<<BigInt(32))+BigInt(o);if(r.strict===!0&&s<Ze[3])throw new Error(`${j} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(r.allowBigInt===!0)return s;throw new Error(`${j} integers outside of the safe integer range are not supported`)}function Gk(t,e,r,n){return new D(y.uint,Et(t,e+1,n),2)}function Kk(t,e,r,n){return new D(y.uint,_t(t,e+1,n),3)}function Zk(t,e,r,n){return new D(y.uint,At(t,e+1,n),5)}function Jk(t,e,r,n){return new D(y.uint,Dt(t,e+1,n),9)}function Ft(t,e){return et(t,0,e.value)}function et(t,e,r){if(r<Ze[0]){let n=Number(r);t.push([e|n])}else if(r<Ze[1]){let n=Number(r);t.push([e|24,n])}else if(r<Ze[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<Ze[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<Ze[4]){let o=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=s&255,s=s>>8,o[7]=s&255,s=s>>8,o[6]=s&255,s=s>>8,o[5]=s&255,o[4]=i&255,i=i>>8,o[3]=i&255,i=i>>8,o[2]=i&255,i=i>>8,o[1]=i&255,t.push(o)}else throw new Error(`${j} encountered BigInt larger than allowable range`)}}Ft.encodedSize=function(e){return et.encodedSize(e.value)};et.encodedSize=function(e){return e<Ze[0]?1:e<Ze[1]?2:e<Ze[2]?3:e<Ze[3]?5:9};Ft.compareTokens=function(e,r){return e.value<r.value?-1:e.value>r.value?1:0};function Qk(t,e,r,n){return new D(y.negint,-1-Et(t,e+1,n),2)}function Xk(t,e,r,n){return new D(y.negint,-1-_t(t,e+1,n),3)}function Yk(t,e,r,n){return new D(y.negint,-1-At(t,e+1,n),5)}var bm=BigInt(-1),ev=BigInt(1);function tv(t,e,r,n){let o=Dt(t,e+1,n);if(typeof o!="bigint"){let s=-1-o;if(s>=Number.MIN_SAFE_INTEGER)return new D(y.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${j} integers outside of the safe integer range are not supported`);return new D(y.negint,bm-BigInt(o),9)}function _l(t,e){let r=e.value,n=typeof r=="bigint"?r*bm-ev:r*-1-1;et(t,e.type.majorEncoded,n)}_l.encodedSize=function(e){let r=e.value,n=typeof r=="bigint"?r*bm-ev:r*-1-1;return n<Ze[0]?1:n<Ze[1]?2:n<Ze[2]?3:n<Ze[3]?5:9};_l.compareTokens=function(e,r){return e.value<r.value?1:e.value>r.value?-1:0};function Va(t,e,r,n){Wr(t,e,r+n);let o=Qs(t,e+r,e+r+n);return new D(y.bytes,o,r+n)}function rv(t,e,r,n){return Va(t,e,1,r)}function nv(t,e,r,n){return Va(t,e,2,Et(t,e+1,n))}function ov(t,e,r,n){return Va(t,e,3,_t(t,e+1,n))}function sv(t,e,r,n){return Va(t,e,5,At(t,e+1,n))}function iv(t,e,r,n){let o=Dt(t,e+1,n);if(typeof o=="bigint")throw new Error(`${j} 64-bit integer bytes lengths not supported`);return Va(t,e,9,o)}function Al(t){return t.encodedBytes===void 0&&(t.encodedBytes=t.type===y.string?El(t.value):t.value),t.encodedBytes}function Xs(t,e){let r=Al(e);et(t,e.type.majorEncoded,r.length),t.push(r)}Xs.encodedSize=function(e){let r=Al(e);return et.encodedSize(r.length)+r.length};Xs.compareTokens=function(e,r){return E8(Al(e),Al(r))};function E8(t,e){return t.length<e.length?-1:t.length>e.length?1:Vk(t,e)}function Ga(t,e,r,n,o){let s=r+n;Wr(t,e,s);let i=new D(y.string,Wk(t,e+r,e+s),s);return o.retainStringBytes===!0&&(i.byteValue=Qs(t,e+r,e+s)),i}function av(t,e,r,n){return Ga(t,e,1,r,n)}function cv(t,e,r,n){return Ga(t,e,2,Et(t,e+1,n),n)}function uv(t,e,r,n){return Ga(t,e,3,_t(t,e+1,n),n)}function lv(t,e,r,n){return Ga(t,e,5,At(t,e+1,n),n)}function dv(t,e,r,n){let o=Dt(t,e+1,n);if(typeof o=="bigint")throw new Error(`${j} 64-bit integer string lengths not supported`);return Ga(t,e,9,o,n)}var fv=Xs;function Ys(t,e,r,n){return new D(y.array,n,r)}function hv(t,e,r,n){return Ys(t,e,1,r)}function pv(t,e,r,n){return Ys(t,e,2,Et(t,e+1,n))}function mv(t,e,r,n){return Ys(t,e,3,_t(t,e+1,n))}function yv(t,e,r,n){return Ys(t,e,5,At(t,e+1,n))}function gv(t,e,r,n){let o=Dt(t,e+1,n);if(typeof o=="bigint")throw new Error(`${j} 64-bit integer array lengths not supported`);return Ys(t,e,9,o)}function wv(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${j} indefinite length items not allowed`);return Ys(t,e,1,1/0)}function Dl(t,e){et(t,y.array.majorEncoded,e.value)}Dl.compareTokens=Ft.compareTokens;Dl.encodedSize=function(e){return et.encodedSize(e.value)};function ei(t,e,r,n){return new D(y.map,n,r)}function bv(t,e,r,n){return ei(t,e,1,r)}function xv(t,e,r,n){return ei(t,e,2,Et(t,e+1,n))}function kv(t,e,r,n){return ei(t,e,3,_t(t,e+1,n))}function vv(t,e,r,n){return ei(t,e,5,At(t,e+1,n))}function Sv(t,e,r,n){let o=Dt(t,e+1,n);if(typeof o=="bigint")throw new Error(`${j} 64-bit integer map lengths not supported`);return ei(t,e,9,o)}function Ev(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${j} indefinite length items not allowed`);return ei(t,e,1,1/0)}function Tl(t,e){et(t,y.map.majorEncoded,e.value)}Tl.compareTokens=Ft.compareTokens;Tl.encodedSize=function(e){return et.encodedSize(e.value)};function _v(t,e,r,n){return new D(y.tag,r,1)}function Av(t,e,r,n){return new D(y.tag,Et(t,e+1,n),2)}function Dv(t,e,r,n){return new D(y.tag,_t(t,e+1,n),3)}function Tv(t,e,r,n){return new D(y.tag,At(t,e+1,n),5)}function Cv(t,e,r,n){return new D(y.tag,Dt(t,e+1,n),9)}function Cl(t,e){et(t,y.tag.majorEncoded,e.value)}Cl.compareTokens=Ft.compareTokens;Cl.encodedSize=function(e){return et.encodedSize(e.value)};var I8=20,B8=21,P8=22,L8=23;function Iv(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${j} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new D(y.null,null,1):new D(y.undefined,void 0,1)}function Bv(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${j} indefinite length items not allowed`);return new D(y.break,void 0,1)}function xm(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${j} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${j} Infinity values are not supported`)}return new D(y.float,t,e)}function Pv(t,e,r,n){return xm(km(t,e+1),3,n)}function Lv(t,e,r,n){return xm(vm(t,e+1),5,n)}function Uv(t,e,r,n){return xm($v(t,e+1),9,n)}function Il(t,e,r){let n=e.value;if(n===!1)t.push([y.float.majorEncoded|I8]);else if(n===!0)t.push([y.float.majorEncoded|B8]);else if(n===null)t.push([y.float.majorEncoded|P8]);else if(n===void 0)t.push([y.float.majorEncoded|L8]);else{let o,s=!1;(!r||r.float64!==!0)&&(Nv(n),o=km(Yt,1),n===o||Number.isNaN(n)?(Yt[0]=249,t.push(Yt.slice(0,3)),s=!0):(Ov(n),o=vm(Yt,1),n===o&&(Yt[0]=250,t.push(Yt.slice(0,5)),s=!0))),s||(U8(n),o=$v(Yt,1),Yt[0]=251,t.push(Yt.slice(0,9)))}}Il.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){Nv(n);let o=km(Yt,1);if(n===o||Number.isNaN(n))return 3;if(Ov(n),o=vm(Yt,1),n===o)return 5}return 9};var Rv=new ArrayBuffer(9),zt=new DataView(Rv,1),Yt=new Uint8Array(Rv,0);function Nv(t){if(t===1/0)zt.setUint16(0,31744,!1);else if(t===-1/0)zt.setUint16(0,64512,!1);else if(Number.isNaN(t))zt.setUint16(0,32256,!1);else{zt.setFloat32(0,t);let e=zt.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)zt.setUint16(0,31744,!1);else if(r===0)zt.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let o=r-127;o<-24?zt.setUint16(0,0):o<-14?zt.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):zt.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function km(t,e){if(t.length-e<2)throw new Error(`${j} 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,s;return n===0?s=o*2**-24:n!==31?s=(o+1024)*2**(n-25):s=o===0?1/0:NaN,r&32768?-s:s}function Ov(t){zt.setFloat32(0,t,!1)}function vm(t,e){if(t.length-e<4)throw new Error(`${j} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function U8(t){zt.setFloat64(0,t,!1)}function $v(t,e){if(t.length-e<8)throw new Error(`${j} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}Il.compareTokens=Ft.compareTokens;function ge(t,e,r){throw new Error(`${j} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function Bl(t){return()=>{throw new Error(`${j} ${t}`)}}var U=[];for(let t=0;t<=23;t++)U[t]=ge;U[24]=Gk;U[25]=Kk;U[26]=Zk;U[27]=Jk;U[28]=ge;U[29]=ge;U[30]=ge;U[31]=ge;for(let t=32;t<=55;t++)U[t]=ge;U[56]=Qk;U[57]=Xk;U[58]=Yk;U[59]=tv;U[60]=ge;U[61]=ge;U[62]=ge;U[63]=ge;for(let t=64;t<=87;t++)U[t]=rv;U[88]=nv;U[89]=ov;U[90]=sv;U[91]=iv;U[92]=ge;U[93]=ge;U[94]=ge;U[95]=Bl("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)U[t]=av;U[120]=cv;U[121]=uv;U[122]=lv;U[123]=dv;U[124]=ge;U[125]=ge;U[126]=ge;U[127]=Bl("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)U[t]=hv;U[152]=pv;U[153]=mv;U[154]=yv;U[155]=gv;U[156]=ge;U[157]=ge;U[158]=ge;U[159]=wv;for(let t=160;t<=183;t++)U[t]=bv;U[184]=xv;U[185]=kv;U[186]=vv;U[187]=Sv;U[188]=ge;U[189]=ge;U[190]=ge;U[191]=Ev;for(let t=192;t<=215;t++)U[t]=_v;U[216]=Av;U[217]=Dv;U[218]=Tv;U[219]=Cv;U[220]=ge;U[221]=ge;U[222]=ge;U[223]=ge;for(let t=224;t<=243;t++)U[t]=Bl("simple values are not supported");U[244]=ge;U[245]=ge;U[246]=ge;U[247]=Iv;U[248]=Bl("simple values are not supported");U[249]=Pv;U[250]=Lv;U[251]=Uv;U[252]=ge;U[253]=ge;U[254]=ge;U[255]=Bv;var er=[];for(let t=0;t<24;t++)er[t]=new D(y.uint,t,1);for(let t=-1;t>=-24;t--)er[31-t]=new D(y.negint,t,1);er[64]=new D(y.bytes,new Uint8Array(0),1);er[96]=new D(y.string,"",1);er[128]=new D(y.array,0,1);er[160]=new D(y.map,0,1);er[244]=new D(y.false,!1,1);er[245]=new D(y.true,!0,1);er[246]=new D(y.null,null,1);function Mv(t){switch(t.type){case y.false:return gr([244]);case y.true:return gr([245]);case y.null:return gr([246]);case y.bytes:return t.value.length?void 0:gr([64]);case y.string:return t.value===""?gr([96]):void 0;case y.array:return t.value===0?gr([128]):void 0;case y.map:return t.value===0?gr([160]):void 0;case y.uint:return t.value<24?gr([Number(t.value)]):void 0;case y.negint:if(t.value>=-24)return gr([31-Number(t.value)])}}var N8={float64:!1,mapSorter:M8,quickEncodeToken:Mv};function O8(){let t=[];return t[y.uint.major]=Ft,t[y.negint.major]=_l,t[y.bytes.major]=Xs,t[y.string.major]=fv,t[y.array.major]=Dl,t[y.map.major]=Tl,t[y.tag.major]=Cl,t[y.float.major]=Il,t}var Fv=O8(),Sm=new Ha,Ll=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(`${jr} object contains circular references`);return new t(r,e)}},bn={null:new D(y.null,null),undefined:new D(y.undefined,void 0),true:new D(y.true,!0),false:new D(y.false,!1),emptyArray:new D(y.array,0),emptyMap:new D(y.map,0)},xn={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new D(y.float,t):t>=0?new D(y.uint,t):new D(y.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new D(y.uint,t):new D(y.negint,t)},Uint8Array(t,e,r,n){return new D(y.bytes,t)},string(t,e,r,n){return new D(y.string,t)},boolean(t,e,r,n){return t?bn.true:bn.false},null(t,e,r,n){return bn.null},undefined(t,e,r,n){return bn.undefined},ArrayBuffer(t,e,r,n){return new D(y.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new D(y.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[bn.emptyArray,new D(y.break)]:bn.emptyArray;n=Ll.createCheck(n,t);let o=[],s=0;for(let i of t)o[s++]=Pl(i,r,n);return r.addBreakTokens?[new D(y.array,t.length),o,new D(y.break)]:[new D(y.array,t.length),o]},Object(t,e,r,n){let o=e!=="Object",s=o?t.keys():Object.keys(t),i=o?t.size:s.length;if(!i)return r.addBreakTokens===!0?[bn.emptyMap,new D(y.break)]:bn.emptyMap;n=Ll.createCheck(n,t);let a=[],c=0;for(let u of s)a[c++]=[Pl(u,r,n),Pl(o?t.get(u):t[u],r,n)];return $8(a,r),r.addBreakTokens?[new D(y.map,i),a,new D(y.break)]:[new D(y.map,i),a]}};xn.Map=xn.Object;xn.Buffer=xn.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))xn[`${t}Array`]=xn.DataView;function Pl(t,e={},r){let n=Mk(t),o=e&&e.typeEncoders&&e.typeEncoders[n]||xn[n];if(typeof o=="function"){let i=o(t,n,e,r);if(i!=null)return i}let s=xn[n];if(!s)throw new Error(`${jr} unsupported type: ${n}`);return s(t,n,e,r)}function $8(t,e){e.mapSorter&&t.sort(e.mapSorter)}function M8(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,s=Fv[o].compareTokens(r,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function zv(t,e,r,n){if(Array.isArray(e))for(let o of e)zv(t,o,r,n);else r[e.type.major](t,e,n)}function Em(t,e,r){let n=Pl(t,r);if(!Array.isArray(n)&&r.quickEncodeToken){let o=r.quickEncodeToken(n);if(o)return o;let s=e[n.type.major];if(s.encodedSize){let i=s.encodedSize(n,r),a=new Ha(i);if(s(a,n,r),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return Wa(a.chunks[0])}}return Sm.reset(),zv(Sm,n,e,r),Sm.toBytes(!0)}function _m(t,e){return e=Object.assign({},N8,e),Em(t,Fv,e)}var F8={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Am=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=er[e];if(r===void 0){let n=U[e];if(!n)throw new Error(`${j} 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}},Ka=Symbol.for("DONE"),Ul=Symbol.for("BREAK");function z8(t,e,r){let n=[];for(let o=0;o<t.value;o++){let s=Za(e,r);if(s===Ul){if(t.value===1/0)break;throw new Error(`${j} got unexpected break to lengthed array`)}if(s===Ka)throw new Error(`${j} found array but not enough entries (got ${o}, expected ${t.value})`);n[o]=s}return n}function j8(t,e,r){let n=r.useMaps===!0,o=n?void 0:{},s=n?new Map:void 0;for(let i=0;i<t.value;i++){let a=Za(e,r);if(a===Ul){if(t.value===1/0)break;throw new Error(`${j} got unexpected break to lengthed map`)}if(a===Ka)throw new Error(`${j} found map but not enough entries (got ${i} [no key], expected ${t.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${j} non-string keys not supported (got ${typeof a})`);if(r.rejectDuplicateMapKeys===!0&&(n&&s.has(a)||!n&&a in o))throw new Error(`${j} found repeat map key "${a}"`);let c=Za(e,r);if(c===Ka)throw new Error(`${j} found map but not enough entries (got ${i} [no value], expected ${t.value})`);n?s.set(a,c):o[a]=c}return n?s:o}function Za(t,e){if(t.done())return Ka;let r=t.next();if(r.type===y.break)return Ul;if(r.type.terminal)return r.value;if(r.type===y.array)return z8(r,t,e);if(r.type===y.map)return j8(r,t,e);if(r.type===y.tag){if(e.tags&&typeof e.tags[r.value]=="function"){let n=Za(t,e);return e.tags[r.value](n)}throw new Error(`${j} tag not supported (${r.value})`)}throw new Error("unsupported")}function Ja(t,e){if(!(t instanceof Uint8Array))throw new Error(`${j} data to decode must be a Uint8Array`);e=Object.assign({},F8,e);let r=e.tokenizer||new Am(t,e),n=Za(r,e);if(n===Ka)throw new Error(`${j} did not find any content to decode`);if(n===Ul)throw new Error(`${j} got unexpected break`);if(!r.done())throw new Error(`${j} too many terminals, data makes no sense`);return n}var H8=Hv,jv=128,q8=127,V8=~q8,G8=Math.pow(2,31);function Hv(t,e,r){e=e||[],r=r||0;for(var n=r;t>=G8;)e[r++]=t&255|jv,t/=128;for(;t&V8;)e[r++]=t&255|jv,t>>>=7;return e[r]=t|0,Hv.bytes=r-n+1,e}var K8=Dm,Z8=128,Wv=127;function Dm(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw Dm.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&Wv)<<o:(i&Wv)*Math.pow(2,o),o+=7}while(i>=Z8);return Dm.bytes=s-n,r}var J8=Math.pow(2,7),Q8=Math.pow(2,14),X8=Math.pow(2,21),Y8=Math.pow(2,28),eP=Math.pow(2,35),tP=Math.pow(2,42),rP=Math.pow(2,49),nP=Math.pow(2,56),oP=Math.pow(2,63),sP=function(t){return t<J8?1:t<Q8?2:t<X8?3:t<Y8?4:t<eP?5:t<tP?6:t<rP?7:t<nP?8:t<oP?9:10},iP={encode:H8,decode:K8,encodingLength:sP},aP=iP,Qa=aP;var Xa=(t,e=0)=>[Qa.decode(t,e),Qa.decode.bytes],ti=(t,e,r=0)=>(Qa.encode(t,e,r),e),ri=t=>Qa.encodingLength(t);var bo={};F(bo,{coerce:()=>jt,empty:()=>qv,equals:()=>Cm,fromHex:()=>uP,fromString:()=>dP,isBinary:()=>lP,toHex:()=>cP,toString:()=>fP});var qv=new Uint8Array(0),cP=t=>t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),""),uP=t=>{let e=t.match(/../g);return e?new Uint8Array(e.map(r=>parseInt(r,16))):qv},Cm=(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},jt=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")},lP=t=>t instanceof ArrayBuffer||ArrayBuffer.isView(t),dP=t=>new TextEncoder().encode(t),fP=t=>new TextDecoder().decode(t);var xo=(t,e)=>{let r=e.byteLength,n=ri(t),o=n+ri(r),s=new Uint8Array(o+r);return ti(t,s,0),ti(r,s,n),s.set(e,o),new ni(t,r,e,s)},Rl=t=>{let e=jt(t),[r,n]=Xa(e),[o,s]=Xa(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ni(r,o,i,e)},Vv=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Cm(t.bytes,r.bytes)}},ni=class{constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};function hP(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 s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);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 m=0,b=0,g=0,k=h.length;g!==k&&h[g]===0;)g++,m++;for(var E=(k-g)*l+1>>>0,_=new Uint8Array(E);g!==k;){for(var P=h[g],J=0,L=E-1;(P!==0||J<b)&&L!==-1;L--,J++)P+=256*_[L]>>>0,_[L]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");b=J,g++}for(var G=E-b;G!==E&&_[G]===0;)G++;for(var ot=c.repeat(m);G<E;++G)ot+=t.charAt(_[G]);return ot}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var b=0,g=0;h[m]===c;)b++,m++;for(var k=(h.length-m)*u+1>>>0,E=new Uint8Array(k);h[m];){var _=r[h.charCodeAt(m)];if(_===255)return;for(var P=0,J=k-1;(_!==0||P<g)&&J!==-1;J--,P++)_+=a*E[J]>>>0,E[J]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");g=P,m++}if(h[m]!==" "){for(var L=k-g;L!==k&&E[L]===0;)L++;for(var G=new Uint8Array(b+(k-L)),ot=b;L!==k;)G[ot++]=E[L++];return G}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var pP=hP,mP=pP,Gv=mP;var Im=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")}},Bm=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 Kv(this,e)}},Pm=class{constructor(e){this.decoders=e}or(e){return Kv(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`)}},Kv=(t,e)=>new Pm({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Lm=class{constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Im(e,r,n),this.decoder=new Bm(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Zv=({name:t,prefix:e,encode:r,decode:n})=>new Lm(t,e,r,n),Um=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:o}=Gv(r,e);return Zv({prefix:t,name:e,encode:n,decode:s=>jt(o(s))})},yP=(t,e,r,n)=>{let o={};for(let l=0;l<e.length;++l)o[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;let i=new Uint8Array(s*r/8|0),a=0,c=0,u=0;for(let l=0;l<s;++l){let d=o[t[l]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|d,a+=r,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},gP=(t,e,r)=>{let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i&&(s+=e[o&a<<r-i]),n)for(;s.length*r&7;)s+="=";return s},lt=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Zv({prefix:e,name:t,encode(o){return gP(o,n,r)},decode(o){return yP(o,n,r,t)}});var Hr=Um({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),M7=Um({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ec=lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),j7=lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),W7=lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),H7=lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),q7=lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),V7=lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),G7=lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),K7=lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Z7=lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Jv=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return bP(r,Rm(t),e||Hr.encoder);default:return xP(r,Rm(t),e||ec.encoder)}};var Qv=new WeakMap,Rm=t=>{let e=Qv.get(t);if(e==null){let r=new Map;return Qv.set(t,r),r}return e},ve=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!==tc)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==kP)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=xo(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&&Vv(e.multihash,n.multihash)}toString(e){return Jv(this,e)}toJSON(){return{"/":Jv(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:s,bytes:i}=r;return new t(n,o,s,i||Xv(n,o,s.bytes))}else if(r[vP]===!0){let{version:n,multihash:o,code:s}=r,i=Rl(o);return t.create(n,s,i)}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!==tc)throw new Error(`Version 0 CID must use dag-pb (code: ${tc}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=Xv(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,tc,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=jt(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new ni(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[d,p]=Xa(e.subarray(r));return r+=p,d},o=n(),s=tc;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),u=r+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,r){let[n,o]=wP(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Rm(s).set(n,e),s}},wP=(t,e)=>{switch(t[0]){case"Q":{let r=e||Hr;return[Hr.prefix,r.decode(`${Hr.prefix}${t}`)]}case Hr.prefix:{let r=e||Hr;return[Hr.prefix,r.decode(t)]}case ec.prefix:{let r=e||ec;return[ec.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)]}}},bP=(t,e,r)=>{let{prefix:n}=r;if(n!==Hr.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o},xP=(t,e,r)=>{let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o},tc=112,kP=18,Xv=(t,e,r)=>{let n=ri(t),o=n+ri(e),s=new Uint8Array(o+r.byteLength);return ti(t,s,0),ti(e,s,n),s.set(r,o),s},vP=Symbol.for("@ipld/js-cid/CID");var Yv=42;function SP(t){if(t.asCID!==t&&t["/"]!==t.bytes)return null;let e=ve.asCID(t);if(!e)return null;let r=new Uint8Array(e.bytes.byteLength+1);return r.set(e.bytes,1),[new D(y.tag,Yv),new D(y.bytes,r)]}function EP(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function _P(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 AP={float64:!0,typeEncoders:{Object:SP,undefined:EP,number:_P}};function DP(t){if(t[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return ve.decode(t.subarray(1))}var e1={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};e1.tags[Yv]=DP;var rc="dag-cbor",Tt=113,tr=t=>_m(t,AP),Ge=t=>Ja(t,e1);var TP=new TextEncoder,CP=new TextDecoder,wr=t=>TP.encode(t),kn=t=>CP.decode(t);var Y={};F(Y,{decode:()=>oi,encodeTo:()=>ko,encodingLength:()=>vo});var IP=n1,t1=128,BP=127,PP=~BP,LP=Math.pow(2,31);function n1(t,e,r){e=e||[],r=r||0;for(var n=r;t>=LP;)e[r++]=t&255|t1,t/=128;for(;t&PP;)e[r++]=t&255|t1,t>>>=7;return e[r]=t|0,n1.bytes=r-n+1,e}var UP=Nm,RP=128,r1=127;function Nm(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw Nm.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&r1)<<o:(i&r1)*Math.pow(2,o),o+=7}while(i>=RP);return Nm.bytes=s-n,r}var NP=Math.pow(2,7),OP=Math.pow(2,14),$P=Math.pow(2,21),MP=Math.pow(2,28),FP=Math.pow(2,35),zP=Math.pow(2,42),jP=Math.pow(2,49),WP=Math.pow(2,56),HP=Math.pow(2,63),qP=function(t){return t<NP?1:t<OP?2:t<$P?3:t<MP?4:t<FP?5:t<zP?6:t<jP?7:t<WP?8:t<HP?9:10},VP={encode:IP,decode:UP,encodingLength:qP},GP=VP,oc=GP;var oi=(t,e=0)=>[oc.decode(t,e),oc.decode.bytes],ko=(t,e,r=0)=>(oc.encode(t,e,r),e),vo=t=>oc.encodingLength(t);var s9=new Uint8Array(0);var o1=(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},rr=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 s1=t=>new TextEncoder().encode(t),i1=t=>new TextDecoder().decode(t);var So=(t,e)=>{let r=e.byteLength,n=vo(t),o=n+vo(r),s=new Uint8Array(o+r);return ko(t,s,0),ko(r,s,n),s.set(e,o),new si(t,r,e,s)},vn=t=>{let e=rr(t),[r,n]=oi(e),[o,s]=oi(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new si(r,o,i,e)},a1=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&o1(t.bytes,r.bytes)}},si=class{constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};var jm={};F(jm,{base58btc:()=>Le,base58flickr:()=>YP});function KP(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 s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);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 m=0,b=0,g=0,k=h.length;g!==k&&h[g]===0;)g++,m++;for(var E=(k-g)*l+1>>>0,_=new Uint8Array(E);g!==k;){for(var P=h[g],J=0,L=E-1;(P!==0||J<b)&&L!==-1;L--,J++)P+=256*_[L]>>>0,_[L]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");b=J,g++}for(var G=E-b;G!==E&&_[G]===0;)G++;for(var ot=c.repeat(m);G<E;++G)ot+=t.charAt(_[G]);return ot}function p(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var m=0;if(h[m]!==" "){for(var b=0,g=0;h[m]===c;)b++,m++;for(var k=(h.length-m)*u+1>>>0,E=new Uint8Array(k);h[m];){var _=r[h.charCodeAt(m)];if(_===255)return;for(var P=0,J=k-1;(_!==0||P<g)&&J!==-1;J--,P++)_+=a*E[J]>>>0,E[J]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");g=P,m++}if(h[m]!==" "){for(var L=k-g;L!==k&&E[L]===0;)L++;for(var G=new Uint8Array(b+(k-L)),ot=b;L!==k;)G[ot++]=E[L++];return G}}}function f(h){var m=p(h);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:p,decode:f}}var ZP=KP,JP=ZP,c1=JP;var $m=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")}},Mm=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 u1(this,e)}},Fm=class{constructor(e){this.decoders=e}or(e){return u1(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`)}},u1=(t,e)=>new Fm({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),zm=class{constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new $m(e,r,n),this.decoder=new Mm(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},ii=({name:t,prefix:e,encode:r,decode:n})=>new zm(t,e,r,n),Sn=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:o}=c1(r,e);return ii({prefix:t,name:e,encode:n,decode:s=>rr(o(s))})},QP=(t,e,r,n)=>{let o={};for(let l=0;l<e.length;++l)o[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;let i=new Uint8Array(s*r/8|0),a=0,c=0,u=0;for(let l=0;l<s;++l){let d=o[t[l]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|d,a+=r,a>=8&&(a-=8,i[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},XP=(t,e,r)=>{let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i&&(s+=e[o&a<<r-i]),n)for(;s.length*r&7;)s+="=";return s},Me=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>ii({prefix:e,name:t,encode(o){return XP(o,n,r)},decode(o){return QP(o,n,r,t)}});var Le=Sn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),YP=Sn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Wm={};F(Wm,{base32:()=>Ve,base32hex:()=>nL,base32hexpad:()=>sL,base32hexpadupper:()=>iL,base32hexupper:()=>oL,base32pad:()=>tL,base32padupper:()=>rL,base32upper:()=>eL,base32z:()=>aL});var Ve=Me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),eL=Me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),tL=Me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rL=Me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),nL=Me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),oL=Me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sL=Me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),iL=Me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),aL=Me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Hm=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return uL(r,qm(t),e||Le.encoder);default:return lL(r,qm(t),e||Ve.encoder)}};var l1=new WeakMap,qm=t=>{let e=l1.get(t);if(e==null){let r=new Map;return l1.set(t,r),r}return e},se=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!==sc)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==dL)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=So(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&&a1(e.multihash,n.multihash)}toString(e){return Hm(this,e)}toJSON(){return{"/":Hm(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:s,bytes:i}=r;return new t(n,o,s,i||d1(n,o,s.bytes))}else if(r[fL]===!0){let{version:n,multihash:o,code:s}=r,i=vn(o);return t.create(n,s,i)}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!==sc)throw new Error(`Version 0 CID must use dag-pb (code: ${sc}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=d1(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,sc,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=rr(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new si(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[d,p]=oi(e.subarray(r));return r+=p,d},o=n(),s=sc;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),u=r+c,l=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,r){let[n,o]=cL(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return qm(s).set(n,e),s}},cL=(t,e)=>{switch(t[0]){case"Q":{let r=e||Le;return[Le.prefix,r.decode(`${Le.prefix}${t}`)]}case Le.prefix:{let r=e||Le;return[Le.prefix,r.decode(t)]}case Ve.prefix:{let r=e||Ve;return[Ve.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)]}}},uL=(t,e,r)=>{let{prefix:n}=r;if(n!==Le.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o},lL=(t,e,r)=>{let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o},sc=112,dL=18,d1=(t,e,r)=>{let n=vo(t),o=n+vo(e),s=new Uint8Array(o+r.byteLength);return ko(t,s,0),ko(e,s,n),s.set(r,o),s},fL=Symbol.for("@ipld/js-cid/CID");var hL=112;var ai=t=>se.create(0,hL,t),Fe=(t,e)=>se.create(1,t,e),Se=t=>{if(t==null)return!1;let e=t;return e["/"]!=null&&e["/"]===e.bytes||t.asCID===t},br=(t,e)=>se.parse(t,e);var Vm={};F(Vm,{identity:()=>_o});var f1=0,mL="identity",h1=rr,yL=t=>So(f1,h1(t)),_o={code:f1,name:mL,encode:h1,digest:yL};var yt={};F(yt,{BLS12381G1:()=>S1,BLS12381G2:()=>E1,DID_CORE:()=>Nl,ED25519:()=>g1,P256:()=>b1,P384:()=>x1,P521:()=>k1,RSA:()=>w1,SECP256K1:()=>v1,decode:()=>ic,encode:()=>Qm,format:()=>Ao,from:()=>Ol,parse:()=>Ue});var Km=({name:t,code:e,encode:r})=>new Gm(t,e,r),Gm=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?So(this.code,r):r.then(n=>So(this.code,n))}else throw Error("Unknown type, must be binary type")}};var m1="did:",gL=m1.length,y1="did:key:",wL=y1.length,g1=237,w1=4613,b1=4608,x1=4609,k1=4610,v1=231,S1=234,E1=235,Nl=3357,Zm=Y.encodingLength(Nl),Ue=t=>{if(t.startsWith(m1))if(t.startsWith(y1)){let e=Le.decode(t.slice(wL));return ic(e)}else{let e=wr(t.slice(gL)),r=new Uint8Array(e.byteLength+Zm);return Y.encodeTo(Nl,r),r.set(e,Zm),new ci(r)}else throw new RangeError(`Invalid DID "${t}", must start with 'did:'`)},Ao=t=>t.did(),Ol=t=>t instanceof ci?t:t instanceof Uint8Array?ic(t):Ue(typeof t=="string"?t:t.did()),ic=t=>{let[e]=Y.decode(t),{buffer:r,byteOffset:n,byteLength:o}=t;switch(e){case b1:if(t.length>35)throw new RangeError("Only p256-pub compressed is supported.");case g1:case w1:case x1:case k1:case S1:case E1:case v1:return new Jm(r,n,o);case Nl:return new ci(r,n,o);default:throw new RangeError(`Unsupported DID encoding, unknown multicode 0x${e.toString(16)}.`)}},Qm=t=>Ue(t.did()),ci=class extends Uint8Array{did(){let e=new Uint8Array(this.buffer,this.byteOffset+Zm);return`did:${kn(e)}`}toJSON(){return this.did()}},Jm=class extends ci{did(){return`did:key:${Le.encode(this)}`}};var ui={};F(ui,{code:()=>Do,decode:()=>kL,encode:()=>xL,name:()=>bL});var bL="raw",Do=85,xL=t=>rr(t),kL=t=>rr(t);var st={};F(st,{BLS12381G1:()=>ey,BLS12381G2:()=>ty,EIP191:()=>sy,ES256:()=>ry,ES256K:()=>Ym,ES384:()=>ny,ES512:()=>oy,EdDSA:()=>To,NON_STANDARD:()=>di,RS256:()=>ac,Signature:()=>li,create:()=>fi,createNamed:()=>iy,createNonStandard:()=>ay,decode:()=>En,encode:()=>cy,format:()=>_L,fromJSON:()=>DL,nameCode:()=>A1,parse:()=>AL,toJSON:()=>D1,view:()=>hi});var Xm={};F(Xm,{base64:()=>$l,base64pad:()=>Ml,base64url:()=>gt,base64urlpad:()=>vL});var $l=Me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ml=Me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),gt=Me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),vL=Me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var di=53248,Ym=53479,ey=53482,ty=53483,To=53485,ry=13636096,ny=13636097,oy=13636098,ac=13636101,sy=53649,_1=t=>{switch(t){case Ym:return"ES256K";case ey:return"BLS12381G1";case ty:return"BLS12381G2";case To:return"EdDSA";case ry:return"ES256";case ny:return"ES384";case oy:return"ES512";case ac:return"RS256";case sy:return"EIP191";default:throw new RangeError(`Unknown signature algorithm code 0x${t.toString(16)}`)}},A1=t=>{switch(t){case"ES256K":return Ym;case"BLS12381G1":return ey;case"BLS12381G2":return ty;case"EdDSA":return To;case"ES256":return ry;case"ES384":return ny;case"ES512":return oy;case"RS256":return ac;case"EIP191":return sy;default:return di}},li=class extends Uint8Array{get code(){let[e]=Y.decode(this);return Object.defineProperties(this,{code:{value:e}}),e}get size(){let e=EL(this);return Object.defineProperties(this,{size:{value:e}}),e}get algorithm(){let e=SL(this);return Object.defineProperties(this,{algorithm:{value:e}}),e}get raw(){let{buffer:e,byteOffset:r,size:n,code:o}=this,s=Y.encodingLength(o),i=Y.encodingLength(n),a=new Uint8Array(e,r+s+i,n);return Object.defineProperties(this,{raw:{value:a}}),a}async verify(e,r){try{if(await e.verify(r,this)===!0)return{ok:{}};throw new Error("Invalid signature")}catch(n){return{error:n}}}toJSON(){return D1(this)}},SL=t=>{let{code:e,raw:r,buffer:n,byteOffset:o}=t;if(e===di){let s=r.byteLength+Y.encodingLength(e)+Y.encodingLength(r.byteLength),i=new Uint8Array(n,o+s);return kn(i)}else return _1(e)},EL=t=>{let e=Y.encodingLength(t.code),[r]=Y.decode(new Uint8Array(t.buffer,t.byteOffset+e));return r},fi=(t,e)=>{let r=_1(t),n=Y.encodingLength(t),o=Y.encodingLength(e.byteLength),s=new li(n+o+e.byteLength);return Y.encodeTo(t,s),Y.encodeTo(e.byteLength,s,n),s.set(e,n+o),Object.defineProperties(s,{code:{value:t},size:{value:e.byteLength}}),s},iy=(t,e)=>{let r=A1(t);return r===di?ay(t,e):fi(r,e)},ay=(t,e)=>{let r=di,n=Y.encodingLength(r),o=Y.encodingLength(e.byteLength),s=wr(t),i=new li(n+o+e.byteLength+s.byteLength);return Y.encodeTo(r,i),Y.encodeTo(e.byteLength,i,n),i.set(e,n+o),i.set(s,n+o+e.byteLength),i},hi=t=>new li(t.buffer,t.byteOffset,t.byteLength),En=t=>{if(!(t instanceof Uint8Array))throw new TypeError(`Can only decode Uint8Array into a Signature, instead got ${JSON.stringify(t)}`);let e=hi(t),{code:r,algorithm:n,raw:o}=e;return e},cy=t=>En(t),_L=(t,e)=>(e||gt).encode(t),AL=(t,e)=>En((e||gt).decode(t)),D1=t=>({"/":{bytes:$l.baseEncode(t)}}),DL=t=>En($l.baseDecode(t["/"].bytes));var cc=t=>P1(t,{readPrincipal:$L,readProof:RL}),B1=t=>P1(t,{readPrincipal:ML,readProof:NL}),P1=(t,{readPrincipal:e,readProof:r})=>({iss:e(t.iss,"iss"),aud:e(t.aud,"aud"),att:CL(t.att,"att"),prf:C1(t.prf,r,"prf")||[],exp:FL(t.exp===1/0?null:t.exp,T1,"exp"),nbf:I1(t.nbf,T1,"nbf"),fct:C1(t.fct,UL,"fct")||[],nnc:I1(t.nnc,uc,"nnc")}),L1=t=>{if(t instanceof Uint8Array)return En(t);throw new TypeError(`Can only decode Uint8Array into a Signature, instead got ${JSON.stringify(t)}`)},T1=(t,e)=>Number.isInteger(t)?t:Wt.throw(`Expected ${e} to be integer, instead got ${JSON.stringify(t)}`),TL=(t,e)=>R1(t,IL,e),CL=(t,e)=>U1(t,TL,e),IL=t=>({...t,can:BL(t.can),with:PL(t.with)}),BL=t=>typeof t!="string"?Wt.throw(`Capability has invalid 'can: ${JSON.stringify(t)}', value must be a string`):t.slice(1,-1).includes("/")?t.toLocaleLowerCase():t==="*"?t:Wt.throw(`Capability has invalid 'can: "${t}"', value must have at least one path segment`),PL=t=>typeof t!="string"?Wt.throw(`Capability has invalid 'with: ${JSON.stringify(t)}', value must be a string`):LL(t)||Wt.throw(`Capability has invalid 'with: "${t}"', value must be a valid URI string`),LL=t=>{try{return new URL(t),t}catch{return null}},U1=(t,e,r)=>Array.isArray(t)?t.map((n,o)=>e(n,`${r}[${o}]`)):Wt.throw(`${r} must be an array`),C1=(t,e,r)=>t===void 0?t:U1(t,e,r),R1=(t,e,r)=>t!=null&&typeof t=="object"?e(t):Wt.throw(`${r} must be of type object, instead got ${t}`),UL=(t,e)=>R1(t,Object,e),RL=(t,e)=>Se(t)?t:dc(`Expected ${e} to be IPLD link, instead got ${JSON.stringify(t)}`),NL=(t,e)=>OL(uc(t,e)),OL=t=>{try{return br(t)}catch{return Fe(Do,_o.digest(wr(t)))}},$L=(t,e)=>ic(zL(t,e)),ML=(t,e)=>Ue(uc(t,e)),I1=(t,e,r="Field")=>t!==void 0?e(t,r):void 0,FL=(t,e,r)=>t===null?null:e(t,r),uc=(t,e="Field")=>typeof t=="string"?t:dc(`${e} has invalid value ${t}`),zL=(t,e)=>t instanceof Uint8Array?t:dc(`Expected ${e} to be Uint8Array, instead got ${JSON.stringify(t)}`),lc=(t,e)=>/\d+\.\d+\.\d+/.test(t)?t:Wt.throw(`Invalid version '${e}: ${JSON.stringify(t)}'`),N1=(t,e,r)=>t===e?e:Wt.throw(`Expected ${r} to be a ${JSON.stringify(e)} instead got ${JSON.stringify(t)}`),Wt=class extends TypeError{get name(){return"ParseError"}static throw(e){throw new this(e)}},dc=t=>Wt.throw(t);var uy=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 s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[y.negint.major](e,r){this[y.uint.major](e,r)}[y.bytes.major](e,r){throw new Error(`${jr} unsupported type: Uint8Array`)}[y.string.major](e,r){this.prefix(e);let n=El(JSON.stringify(r.value));e.push(n.length>32?Wa(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 i=this.inRecursive.pop();if(i){if(i.type===y.array)e.push([93]);else if(i.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(`${jr} 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=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};function WL(t,e){if(Array.isArray(t[0])||Array.isArray(e[0]))throw new Error(`${jr} 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(`${jr} non-string map keys are not supported`);if(r<n)return-1;if(r>n)return 1;throw new Error(`${jr} unexpected duplicate map keys, this is not supported`)}var HL={addBreakTokens:!0,mapSorter:WL};function ly(t,e){return e=Object.assign({},HL,e),Em(t,new uy,e)}var pi=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(`${j} 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(`${j} unexpected token at position ${this.pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this.pos,r=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))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 D(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(`${j} unexpected token at position ${this.pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${j} 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 s=String.fromCharCode.apply(null,this.data.subarray(e,this.pos)),i=parseFloat(s);return n?new D(y.float,i,this.pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new D(i>=0?y.uint:y.negint,i,this.pos-e):new D(i>=0?y.uint:y.negint,BigInt(s),this.pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${j} unexpected character at position ${this.pos}; this shouldn't happen`);this.pos++;for(let s=this.pos,i=0;s<this.data.length&&i<65536;s++,i++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this.pos,s));return this.pos=s+1,new D(y.string,c,i)}}let e=this.pos,r=[],n=()=>{if(this.pos+4>=this.data.length)throw new Error(`${j} unexpected end of unicode escape sequence at position ${this.pos}`);let s=0;for(let i=0;i<4;i++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${j} unexpected unicode escape character at position ${this.pos}`);s=s*16+a,this.pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this.pos+a>this.data.length)throw new Error(`${j} unexpected unicode sequence at position ${this.pos}`);let c,u,l,d;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this.pos+1],(c&192)===128&&(d=(s&31)<<6|c&63,d>127&&(i=d));break;case 3:c=this.data[this.pos+1],u=this.data[this.pos+2],(c&192)===128&&(u&192)===128&&(d=(s&15)<<12|(c&63)<<6|u&63,d>2047&&(d<55296||d>57343)&&(i=d));break;case 4:c=this.data[this.pos+1],u=this.data[this.pos+2],l=this.data[this.pos+3],(c&192)===128&&(u&192)===128&&(l&192)===128&&(d=(s&15)<<18|(c&63)<<12|(u&63)<<6|l&63,d>65535&&d<1114112&&(i=d))}i===null?(i=65533,a=1):i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|i&1023),r.push(i),this.pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this.pos++,this.done())throw new Error(`${j} unexpected string termination at position ${this.pos}`);switch(i=this.ch(),this.pos++,i){case 34:case 39:case 92:case 47:r.push(i);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(`${j} unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new D(y.string,wm(r),this.pos-e);default:if(s<32)throw new Error(`${j} invalid control character at position ${this.pos}`);s<128?(r.push(s),this.pos++):o()}}throw new Error(`${j} unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new D(y.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new D(y.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new D(y.null,null,4);case 102:return this.expect([102,97,108,115,101]),new D(y.false,!1,5);case 116:return this.expect([116,114,117,101]),new D(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(`${j} 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 D(y.break,void 0,1);if(this.ch()!==44)throw new Error(`${j} 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 D(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 D(y.break,void 0,1);if(this.ch()!==44)throw new Error(`${j} 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 D(y.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${j} 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(`${j} unexpected parse state at position ${this.pos}; this shouldn't happen`)}}};function dy(t,e){return e=Object.assign({tokenizer:new pi(t,e)},e),Ja(t,e)}var Co=({name:t,code:e,encode:r})=>new fy(t,e,r),fy=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?xo(this.code,r):r.then(n=>xo(this.code,n))}else throw Error("Unknown type, must be binary type")}};var hy=lt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Z9=lt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),J9=lt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Q9=lt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function GL(t){if(t.asCID!==t&&t["/"]!==t.bytes)return null;let e=ve.asCID(t);if(!e)return null;let r=e.toString();return[new D(y.map,1/0,1),new D(y.string,"/",1),new D(y.string,r,r.length),new D(y.break,void 0,1)]}function Fl(t){let e=hy.encode(t).slice(1);return[new D(y.map,1/0,1),new D(y.string,"/",1),new D(y.map,1/0,1),new D(y.string,"bytes",5),new D(y.string,e,e.length),new D(y.break,void 0,1),new D(y.break,void 0,1)]}function nr(t){return Fl(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function KL(t){return Fl(new Uint8Array(t))}function ZL(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function JL(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 QL={typeEncoders:{Object:GL,Buffer:Fl,Uint8Array:Fl,Int8Array:nr,Uint16Array:nr,Int16Array:nr,Uint32Array:nr,Int32Array:nr,Float32Array:nr,Float64Array:nr,Uint8ClampedArray:nr,BigInt64Array:nr,BigUint64Array:nr,DataView:nr,ArrayBuffer:KL,undefined:ZL,number:JL}},py=class extends pi{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 D(y.tag,42,0)}if(n.type===y.map){let o=this._next();if(o.type===y.string&&o.value==="bytes"){let s=this._next();if(s.type===y.string){for(let a=0;a<2;a++)if(this._next().type!==y.break)throw new Error("Invalid encoded Bytes form");let i=hy.decode(`m${s.value}`);return new D(y.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(r)}return e}},my={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};my.tags[42]=ve.parse;var mi=t=>ly(t,QL),zl=t=>{let e=Object.assign(my,{tokenizer:new py(t,my)});return dy(t,e)},jl=t=>XL.decode(mi(t));var XL=new TextDecoder,Wl=t=>zl(YL.encode(t)),YL=new TextEncoder;var yy=t=>{let e=M1(t.v,t.s.algorithm),r=F1(t),n=e6(t.s);return`${e}.${r}.${n}`},$1=(t,e,r)=>`${M1(e,r)}.${F1(t)}`,M1=(t,e)=>gt.baseEncode(t6(t,e)),F1=t=>gt.baseEncode(r6(t)),e6=t=>gt.baseEncode(t.raw),t6=(t,e)=>mi({alg:e,ucv:t,typ:"JWT"}),r6=t=>mi({iss:Ao(t.iss),aud:Ao(t.aud),att:t.att,exp:t.exp,prf:t.prf.map(n6),...t.fct.length>0&&{fct:t.fct},...t.nnc&&{nnc:t.nnc},...t.nbf&&{nbf:t.nbf}}),n6=t=>t.toString();var o6=t=>JSON.parse(kn(mi(t))),yi=class{constructor(e){this.model=e}get version(){return this.model.v}get issuer(){return Ol(this.model.iss)}get audience(){return Ol(this.model.aud)}get capabilities(){return this.model.att}get expiration(){let{exp:e}=this.model;return e===null?1/0:e}get notBefore(){return this.model.nbf}get nonce(){return this.model.nnc}get facts(){return this.model.fct}get proofs(){return this.model.prf}get signature(){return this.model.s}get jwt(){return this.model.jwt}get s(){return this.model.s}get v(){return this.model.v}get iss(){return this.model.iss}get aud(){return this.model.aud}get att(){return this.model.att}get exp(){return this.model.exp}get nbf(){return this.model.nbf}get nnc(){return this.model.nnc}get fct(){return this.model.fct}get prf(){return this.model.prf}toJSON(){let{v:e,iss:r,aud:n,s:o,att:s,prf:i,exp:a,fct:c,nnc:u,nbf:l}=this.model;return{iss:r,aud:n,v:e,s:o,exp:a,...o6({att:s,prf:i,...c.length>0&&{fct:c}}),...u!=null&&{nnc:u},...l&&{nbf:l}}}};var gy=Tt,z1=t=>new Hl(t),wy=t=>{let{fct:e,nnc:r,nbf:n,...o}=cc(t);return tr({...e.length>0&&{fct:e},...r!=null&&{nnc:r},...n&&{nbf:n},...o,v:lc(t.v,"v"),s:s6(t.s,"s")})},s6=(t,e)=>{try{return cy(t)}catch(r){throw new Error(`Expected signature ${e}, instead got ${JSON.stringify(t)}`,{cause:r})}},j1=t=>{let e=Ge(t);return new Hl({...cc(e),v:lc(e.v,"v"),s:L1(e.s)})};var Hl=class extends yi{get code(){return gy}format(){return yy(this.model)}encode(){return wy(this.model)}};var by=t=>{let e=t.split("."),[r,n,o]=e.length===3?e:dc(`Can't parse UCAN: ${t}: Expected JWT format: 3 dot-separated base64url-encoded values.`),{ucv:s,alg:i}=a6(r);return{...c6(n),v:s,s:iy(i,gt.baseDecode(o))}},a6=t=>{let{ucv:e,alg:r,typ:n}=zl(gt.baseDecode(t));return{typ:N1(n,"JWT","typ"),ucv:lc(e,"ucv"),alg:uc(r,"alg")}},c6=t=>{let e=zl(gt.baseDecode(t));return B1(e)};var W1=t=>{let e=kn(t);return new xy({...by(e),jwt:e})},ky=({jwt:t})=>wr(t),H1=({jwt:t})=>t,xy=class extends yi{constructor(e){super(e),this.model=e}get code(){return Do}format(){return H1(this.model)}encode(){return ky(this.model)}};var vy={};F(vy,{sha256:()=>ue,sha512:()=>l6});var q1=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),ue=Km({name:"sha2-256",code:18,encode:q1("SHA-256")}),l6=Km({name:"sha2-512",code:19,encode:q1("SHA-512")});var d6="0.9.1";var f6=ue;var ql=t=>{try{return j1(t)}catch{return W1(t)}};var Vl=async(t,{hasher:e=f6}={})=>{let[r,n]=t.jwt?[Do,ky(t)]:[gy,wy(t)],o=await e.digest(n);return{bytes:n,cid:Fe(r,o),data:t}};var gi=async({issuer:t,audience:e,capabilities:r,lifetimeInSeconds:n=30,expiration:o=p6()+n,notBefore:s,facts:i=[],proofs:a=[],nonce:c})=>{let u=d6,l=cc({iss:Ue(t.did()),aud:Ue(e.did()),att:r,fct:i,exp:o,nbf:s,prf:a,nnc:c}),d=h6(l,u,t.signatureAlgorithm);return z1({...l,v:u,s:await t.sign(d)})},h6=(t,e,r)=>wr($1(t,e,r));var p6=()=>Math.floor(Date.now()/1e3);var xr={};F(xr,{code:()=>Tt,contentType:()=>y6,decode:()=>Ge,encode:()=>Bo,link:()=>V1,name:()=>rc,write:()=>Sy});var y6="application/vnd.ipld.dag-cbor",Gl=(t,e)=>{if(e.has(t))throw new TypeError("Can not encode circular structure");if(t===void 0&&e.size===0||t===null||typeof t=="symbol"&&e.size===0)return null;if(Se(t)||ArrayBuffer.isView(t))return t;if(Array.isArray(t)){e.add(t);let r=[];for(let n of t)r.push(n===void 0||typeof n=="symbol"?null:Gl(n,e));return r}if(typeof t.toJSON=="function"){e.add(t);let r=t.toJSON();return Gl(r,e)}if(typeof t=="object"){e.add(t);let r={};for(let[n,o]of Object.entries(t))o!==void 0&&typeof o!="symbol"&&(r[n]=Gl(o,e));return r}return t},Bo=t=>tr(Gl(t,new Set)),V1=async(t,{hasher:e=ue}={})=>Fe(Tt,await e.digest(t)),Sy=async(t,e)=>{let r=Bo(t);return{cid:await V1(r,e),bytes:r}};var Po=function*(t){t&&typeof t=="object"&&"iterateIPLDBlocks"in t&&typeof t.iterateIPLDBlocks=="function"&&(yield*t.iterateIPLDBlocks())},G1=(t=[])=>{let e=new Map;return Zl(t,e),e},g6=_o.code,_n=(t,e,r)=>{if(t.multihash.code===g6)return{cid:t,bytes:t.multihash.digest};let n=e.get(`${t}`);return n||(r===void 0?qr(t):r)};var qr=t=>{throw new Error(`Block for the ${t} is not found`)},Kl=async(t,e,r={})=>{let n=r.codec||xr,o=r.hasher||ue,s=n.encode(t),i=await o.digest(s),a=Fe(n.code,i);return e.set(a.toString(),{bytes:s,cid:a}),{bytes:s,cid:a,data:t}},w6=({cid:t,bytes:e},r)=>(r.set(t.toString(),{bytes:e,cid:t}),{bytes:e,cid:t}),Zl=(t,e)=>{for(let r of t)w6(r,e)};var Re={};F(Re,{code:()=>dE,contentType:()=>f3,createWriter:()=>p3,decode:()=>gc,encode:()=>hd,link:()=>fE,name:()=>h3,write:()=>m3});var An={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=>!An.Null(t)&&typeof t=="object"&&t.asCID===t,List:t=>Array.isArray(t),Map:t=>!An.Null(t)&&typeof t=="object"&&t.asCID!==t&&!An.List(t)&&!An.Bytes(t)},bi={Int:An.Int,"CarHeader > version":t=>bi.Int(t),"CarHeader > roots (anon) > valueType (anon)":An.Link,"CarHeader > roots (anon)":t=>An.List(t)&&Array.prototype.every.call(t,bi["CarHeader > roots (anon) > valueType (anon)"]),"CarHeader > roots":t=>bi["CarHeader > roots (anon)"](t),CarHeader:t=>{let e=t&&Object.keys(t);return An.Map(t)&&["version"].every(r=>e.includes(r))&&Object.entries(t).every(([r,n])=>bi["CarHeader > "+r]&&bi["CarHeader > "+r](n))}},Jl=bi.CarHeader;var Dn=De(Ql(),1),Tn={SHA2_256:18,LENGTH:32,DAG_PB:112},Xl=16+8+8+8;function kr(t,e){if(!t.length)throw new Error("Unexpected end of data");let r=Dn.default.decode(t);return e.seek(Dn.default.decode.bytes),r}function Yl(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 ed(t){Dn.default.decode(t);let e=Dn.default.decode.bytes,r=Dn.default.decode(t.subarray(Dn.default.decode.bytes)),n=Dn.default.decode.bytes;return e+n+r}function nS(t,e){let r=kr(t.upTo(8),t);if(r===0)throw new Error("Invalid CAR header (zero length)");let n=t.exactly(r,!0),o=Ge(n);if(!Jl(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 s=Array.isArray(o.roots);if(o.version===1&&!s||o.version===2&&s)throw new Error("Invalid CAR header format");if(o.version===1)return o;let i=Yl(t.exactly(Xl,!0));t.seek(i.dataOffset-t.pos);let a=nS(t,1);return Object.assign(a,i)}function P6(t){let e=t.exactly(2,!1);if(e[0]===Tn.SHA2_256&&e[1]===Tn.LENGTH){let i=t.exactly(34,!0),a=vn(i);return se.create(0,Tn.DAG_PB,a)}let r=kr(t.upTo(8),t);if(r!==1)throw new Error(`Unexpected CID version (${r})`);let n=kr(t.upTo(8),t),o=t.exactly(ed(t.upTo(8)),!0),s=vn(o);return se.create(r,n,s)}function L6(t){let e=t.pos,r=kr(t.upTo(8),t);if(r===0)throw new Error("Invalid CAR section (zero length)");r+=t.pos-e;let n=P6(t),o=r-Number(t.pos-e);return{cid:n,length:r,blockLength:o}}function oS(t){let e=U6(t),r=nS(e);if(r.version===2){let o=e.pos-r.dataOffset;e=R6(e,r.dataSize-o)}let n=[];for(;e.upTo(8).length>0;){let{cid:o,blockLength:s}=L6(e);n.push({cid:o,bytes:e.exactly(s,!0)})}return{header:r,blocks:n}}function U6(t){let e=0;return{upTo(r){return t.subarray(e,e+Math.min(r,t.length-e))},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 R6(t,e){let r=0;return{upTo(n){let o=t.upTo(n);return o.length+r>e&&(o=o.subarray(0,e-r)),o},exactly(n,o=!1){let s=t.exactly(n,o);if(s.length+r>e)throw new Error("Unexpected end of data");return o&&(r+=n),s},seek(n){r+=n,t.seek(n)},get pos(){return t.pos}}}var Vr=class t{constructor(e,r){this._header=e,this._blocks=r,this._cids=void 0}get version(){return this._header.version}getRoots(){return this._header.roots}has(e){return this._blocks.some(r=>r.cid.equals(e))}get(e){return this._blocks.find(r=>r.cid.equals(e))}blocks(){return this._blocks}cids(){return this._cids||(this._cids=this._blocks.map(e=>e.cid)),this._cids}static fromBytes(e){if(!(e instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");let{header:r,blocks:n}=oS(e);return new t(r,n)}};var mc=De(Ql(),1);var O6=["string","number","bigint","symbol"],$6=["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 sS(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(O6.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(M6(t))return"Buffer";let r=F6(t);return r||"Object"}function M6(t){return t&&t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer.call(null,t)}function F6(t){let e=Object.prototype.toString.call(t).slice(8,-1);if($6.includes(e))return e}var S=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}};S.uint=new S(0,"uint",!0);S.negint=new S(1,"negint",!0);S.bytes=new S(2,"bytes",!0);S.string=new S(3,"string",!0);S.array=new S(4,"array",!1);S.map=new S(5,"map",!1);S.tag=new S(6,"tag",!1);S.float=new S(7,"float",!0);S.false=new S(7,"false",!0);S.true=new S(7,"true",!0);S.null=new S(7,"null",!0);S.undefined=new S(7,"undefined",!0);S.break=new S(7,"break",!0);var N=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 xi=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",z6=new TextDecoder,j6=new TextEncoder;function td(t){return xi&&globalThis.Buffer.isBuffer(t)}function uS(t){return t instanceof Uint8Array?td(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var lS=xi?(t,e,r)=>r-e>64?globalThis.Buffer.from(t.subarray(e,r)).toString("utf8"):aS(t,e,r):(t,e,r)=>r-e>64?z6.decode(t.subarray(e,r)):aS(t,e,r),dS=xi?t=>t.length>64?globalThis.Buffer.from(t):iS(t):t=>t.length>64?j6.encode(t):iS(t),vr=t=>Uint8Array.from(t),ki=xi?(t,e,r)=>td(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),fS=xi?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),uS(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},hS=xi?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function pS(t,e){if(td(t)&&td(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 iS(t,e=1/0){let r,n=t.length,o=null,s=[];for(let i=0;i<n;++i){if(r=t.charCodeAt(i),r>55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(i+1===n){(e-=3)>-1&&s.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),o=r;continue}r=(o-55296<<10|r-56320)+65536}else o&&(e-=3)>-1&&s.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function aS(t,e,r){let n=[];for(;e<r;){let o=t[e],s=null,i=o>239?4:o>223?3:o>191?2:1;if(e+i<=r){let a,c,u,l;switch(i){case 1:o<128&&(s=o);break;case 2:a=t[e+1],(a&192)===128&&(l=(o&31)<<6|a&63,l>127&&(s=l));break;case 3:a=t[e+1],c=t[e+2],(a&192)===128&&(c&192)===128&&(l=(o&15)<<12|(a&63)<<6|c&63,l>2047&&(l<55296||l>57343)&&(s=l));break;case 4:a=t[e+1],c=t[e+2],u=t[e+3],(a&192)===128&&(c&192)===128&&(u&192)===128&&(l=(o&15)<<18|(a&63)<<12|(c&63)<<6|u&63,l>65535&&l<1114112&&(s=l))}}s===null?(s=65533,i=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=i}return W6(n)}var cS=4096;function W6(t){let e=t.length;if(e<=cS)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=cS));return r}var H6=256,rd=class{constructor(e=H6){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=hS(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=ki(n,0,this.cursor)}else r=fS(this.chunks,this.cursor);return e&&this.reset(),r}};var we="CBOR decode error:",Ay="CBOR encode error:",fc=[];fc[23]=1;fc[24]=2;fc[25]=3;fc[26]=5;fc[27]=9;function Gr(t,e,r){if(t.length-e<r)throw new Error(`${we} not enough data for type`)}var Je=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Ct(t,e,r){Gr(t,e,1);let n=t[e];if(r.strict===!0&&n<Je[0])throw new Error(`${we} integer encoded in more bytes than necessary (strict decode)`);return n}function It(t,e,r){Gr(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<Je[1])throw new Error(`${we} integer encoded in more bytes than necessary (strict decode)`);return n}function Bt(t,e,r){Gr(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<Je[2])throw new Error(`${we} integer encoded in more bytes than necessary (strict decode)`);return n}function Pt(t,e,r){Gr(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],s=(BigInt(n)<<BigInt(32))+BigInt(o);if(r.strict===!0&&s<Je[3])throw new Error(`${we} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(r.allowBigInt===!0)return s;throw new Error(`${we} integers outside of the safe integer range are not supported`)}function mS(t,e,r,n){return new N(S.uint,Ct(t,e+1,n),2)}function yS(t,e,r,n){return new N(S.uint,It(t,e+1,n),3)}function gS(t,e,r,n){return new N(S.uint,Bt(t,e+1,n),5)}function wS(t,e,r,n){return new N(S.uint,Pt(t,e+1,n),9)}function Ht(t,e){return tt(t,0,e.value)}function tt(t,e,r){if(r<Je[0]){let n=Number(r);t.push([e|n])}else if(r<Je[1]){let n=Number(r);t.push([e|24,n])}else if(r<Je[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<Je[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<Je[4]){let o=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=s&255,s=s>>8,o[7]=s&255,s=s>>8,o[6]=s&255,s=s>>8,o[5]=s&255,o[4]=i&255,i=i>>8,o[3]=i&255,i=i>>8,o[2]=i&255,i=i>>8,o[1]=i&255,t.push(o)}else throw new Error(`${we} encountered BigInt larger than allowable range`)}}Ht.encodedSize=function(e){return tt.encodedSize(e.value)};tt.encodedSize=function(e){return e<Je[0]?1:e<Je[1]?2:e<Je[2]?3:e<Je[3]?5:9};Ht.compareTokens=function(e,r){return e.value<r.value?-1:e.value>r.value?1:0};function bS(t,e,r,n){return new N(S.negint,-1-Ct(t,e+1,n),2)}function xS(t,e,r,n){return new N(S.negint,-1-It(t,e+1,n),3)}function kS(t,e,r,n){return new N(S.negint,-1-Bt(t,e+1,n),5)}var Dy=BigInt(-1),vS=BigInt(1);function SS(t,e,r,n){let o=Pt(t,e+1,n);if(typeof o!="bigint"){let s=-1-o;if(s>=Number.MIN_SAFE_INTEGER)return new N(S.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${we} integers outside of the safe integer range are not supported`);return new N(S.negint,Dy-BigInt(o),9)}function nd(t,e){let r=e.value,n=typeof r=="bigint"?r*Dy-vS:r*-1-1;tt(t,e.type.majorEncoded,n)}nd.encodedSize=function(e){let r=e.value,n=typeof r=="bigint"?r*Dy-vS:r*-1-1;return n<Je[0]?1:n<Je[1]?2:n<Je[2]?3:n<Je[3]?5:9};nd.compareTokens=function(e,r){return e.value<r.value?1:e.value>r.value?-1:0};function hc(t,e,r,n){Gr(t,e,r+n);let o=ki(t,e+r,e+r+n);return new N(S.bytes,o,r+n)}function ES(t,e,r,n){return hc(t,e,1,r)}function _S(t,e,r,n){return hc(t,e,2,Ct(t,e+1,n))}function AS(t,e,r,n){return hc(t,e,3,It(t,e+1,n))}function DS(t,e,r,n){return hc(t,e,5,Bt(t,e+1,n))}function TS(t,e,r,n){let o=Pt(t,e+1,n);if(typeof o=="bigint")throw new Error(`${we} 64-bit integer bytes lengths not supported`);return hc(t,e,9,o)}function od(t){return t.encodedBytes===void 0&&(t.encodedBytes=t.type===S.string?dS(t.value):t.value),t.encodedBytes}function vi(t,e){let r=od(e);tt(t,e.type.majorEncoded,r.length),t.push(r)}vi.encodedSize=function(e){let r=od(e);return tt.encodedSize(r.length)+r.length};vi.compareTokens=function(e,r){return V6(od(e),od(r))};function V6(t,e){return t.length<e.length?-1:t.length>e.length?1:pS(t,e)}function pc(t,e,r,n,o){let s=r+n;Gr(t,e,s);let i=new N(S.string,lS(t,e+r,e+s),s);return o.retainStringBytes===!0&&(i.byteValue=ki(t,e+r,e+s)),i}function CS(t,e,r,n){return pc(t,e,1,r,n)}function IS(t,e,r,n){return pc(t,e,2,Ct(t,e+1,n),n)}function BS(t,e,r,n){return pc(t,e,3,It(t,e+1,n),n)}function PS(t,e,r,n){return pc(t,e,5,Bt(t,e+1,n),n)}function LS(t,e,r,n){let o=Pt(t,e+1,n);if(typeof o=="bigint")throw new Error(`${we} 64-bit integer string lengths not supported`);return pc(t,e,9,o,n)}var US=vi;function Si(t,e,r,n){return new N(S.array,n,r)}function RS(t,e,r,n){return Si(t,e,1,r)}function NS(t,e,r,n){return Si(t,e,2,Ct(t,e+1,n))}function OS(t,e,r,n){return Si(t,e,3,It(t,e+1,n))}function $S(t,e,r,n){return Si(t,e,5,Bt(t,e+1,n))}function MS(t,e,r,n){let o=Pt(t,e+1,n);if(typeof o=="bigint")throw new Error(`${we} 64-bit integer array lengths not supported`);return Si(t,e,9,o)}function FS(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${we} indefinite length items not allowed`);return Si(t,e,1,1/0)}function sd(t,e){tt(t,S.array.majorEncoded,e.value)}sd.compareTokens=Ht.compareTokens;sd.encodedSize=function(e){return tt.encodedSize(e.value)};function Ei(t,e,r,n){return new N(S.map,n,r)}function zS(t,e,r,n){return Ei(t,e,1,r)}function jS(t,e,r,n){return Ei(t,e,2,Ct(t,e+1,n))}function WS(t,e,r,n){return Ei(t,e,3,It(t,e+1,n))}function HS(t,e,r,n){return Ei(t,e,5,Bt(t,e+1,n))}function qS(t,e,r,n){let o=Pt(t,e+1,n);if(typeof o=="bigint")throw new Error(`${we} 64-bit integer map lengths not supported`);return Ei(t,e,9,o)}function VS(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${we} indefinite length items not allowed`);return Ei(t,e,1,1/0)}function id(t,e){tt(t,S.map.majorEncoded,e.value)}id.compareTokens=Ht.compareTokens;id.encodedSize=function(e){return tt.encodedSize(e.value)};function GS(t,e,r,n){return new N(S.tag,r,1)}function KS(t,e,r,n){return new N(S.tag,Ct(t,e+1,n),2)}function ZS(t,e,r,n){return new N(S.tag,It(t,e+1,n),3)}function JS(t,e,r,n){return new N(S.tag,Bt(t,e+1,n),5)}function QS(t,e,r,n){return new N(S.tag,Pt(t,e+1,n),9)}function ad(t,e){tt(t,S.tag.majorEncoded,e.value)}ad.compareTokens=Ht.compareTokens;ad.encodedSize=function(e){return tt.encodedSize(e.value)};var X6=20,Y6=21,e3=22,t3=23;function XS(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${we} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new N(S.null,null,1):new N(S.undefined,void 0,1)}function YS(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${we} indefinite length items not allowed`);return new N(S.break,void 0,1)}function Ty(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${we} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${we} Infinity values are not supported`)}return new N(S.float,t,e)}function eE(t,e,r,n){return Ty(Cy(t,e+1),3,n)}function tE(t,e,r,n){return Ty(Iy(t,e+1),5,n)}function rE(t,e,r,n){return Ty(iE(t,e+1),9,n)}function cd(t,e,r){let n=e.value;if(n===!1)t.push([S.float.majorEncoded|X6]);else if(n===!0)t.push([S.float.majorEncoded|Y6]);else if(n===null)t.push([S.float.majorEncoded|e3]);else if(n===void 0)t.push([S.float.majorEncoded|t3]);else{let o,s=!1;(!r||r.float64!==!0)&&(oE(n),o=Cy(or,1),n===o||Number.isNaN(n)?(or[0]=249,t.push(or.slice(0,3)),s=!0):(sE(n),o=Iy(or,1),n===o&&(or[0]=250,t.push(or.slice(0,5)),s=!0))),s||(r3(n),o=iE(or,1),or[0]=251,t.push(or.slice(0,9)))}}cd.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){oE(n);let o=Cy(or,1);if(n===o||Number.isNaN(n))return 3;if(sE(n),o=Iy(or,1),n===o)return 5}return 9};var nE=new ArrayBuffer(9),qt=new DataView(nE,1),or=new Uint8Array(nE,0);function oE(t){if(t===1/0)qt.setUint16(0,31744,!1);else if(t===-1/0)qt.setUint16(0,64512,!1);else if(Number.isNaN(t))qt.setUint16(0,32256,!1);else{qt.setFloat32(0,t);let e=qt.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)qt.setUint16(0,31744,!1);else if(r===0)qt.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let o=r-127;o<-24?qt.setUint16(0,0):o<-14?qt.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):qt.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function Cy(t,e){if(t.length-e<2)throw new Error(`${we} 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,s;return n===0?s=o*2**-24:n!==31?s=(o+1024)*2**(n-25):s=o===0?1/0:NaN,r&32768?-s:s}function sE(t){qt.setFloat32(0,t,!1)}function Iy(t,e){if(t.length-e<4)throw new Error(`${we} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function r3(t){qt.setFloat64(0,t,!1)}function iE(t,e){if(t.length-e<8)throw new Error(`${we} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}cd.compareTokens=Ht.compareTokens;function be(t,e,r){throw new Error(`${we} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function ud(t){return()=>{throw new Error(`${we} ${t}`)}}var R=[];for(let t=0;t<=23;t++)R[t]=be;R[24]=mS;R[25]=yS;R[26]=gS;R[27]=wS;R[28]=be;R[29]=be;R[30]=be;R[31]=be;for(let t=32;t<=55;t++)R[t]=be;R[56]=bS;R[57]=xS;R[58]=kS;R[59]=SS;R[60]=be;R[61]=be;R[62]=be;R[63]=be;for(let t=64;t<=87;t++)R[t]=ES;R[88]=_S;R[89]=AS;R[90]=DS;R[91]=TS;R[92]=be;R[93]=be;R[94]=be;R[95]=ud("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)R[t]=CS;R[120]=IS;R[121]=BS;R[122]=PS;R[123]=LS;R[124]=be;R[125]=be;R[126]=be;R[127]=ud("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)R[t]=RS;R[152]=NS;R[153]=OS;R[154]=$S;R[155]=MS;R[156]=be;R[157]=be;R[158]=be;R[159]=FS;for(let t=160;t<=183;t++)R[t]=zS;R[184]=jS;R[185]=WS;R[186]=HS;R[187]=qS;R[188]=be;R[189]=be;R[190]=be;R[191]=VS;for(let t=192;t<=215;t++)R[t]=GS;R[216]=KS;R[217]=ZS;R[218]=JS;R[219]=QS;R[220]=be;R[221]=be;R[222]=be;R[223]=be;for(let t=224;t<=243;t++)R[t]=ud("simple values are not supported");R[244]=be;R[245]=be;R[246]=be;R[247]=XS;R[248]=ud("simple values are not supported");R[249]=eE;R[250]=tE;R[251]=rE;R[252]=be;R[253]=be;R[254]=be;R[255]=YS;var Sr=[];for(let t=0;t<24;t++)Sr[t]=new N(S.uint,t,1);for(let t=-1;t>=-24;t--)Sr[31-t]=new N(S.negint,t,1);Sr[64]=new N(S.bytes,new Uint8Array(0),1);Sr[96]=new N(S.string,"",1);Sr[128]=new N(S.array,0,1);Sr[160]=new N(S.map,0,1);Sr[244]=new N(S.false,!1,1);Sr[245]=new N(S.true,!0,1);Sr[246]=new N(S.null,null,1);function By(t){switch(t.type){case S.false:return vr([244]);case S.true:return vr([245]);case S.null:return vr([246]);case S.bytes:return t.value.length?void 0:vr([64]);case S.string:return t.value===""?vr([96]):void 0;case S.array:return t.value===0?vr([128]):void 0;case S.map:return t.value===0?vr([160]):void 0;case S.uint:return t.value<24?vr([Number(t.value)]):void 0;case S.negint:if(t.value>=-24)return vr([31-Number(t.value)])}}function Py(){let t=[];return t[S.uint.major]=Ht,t[S.negint.major]=nd,t[S.bytes.major]=vi,t[S.string.major]=US,t[S.array.major]=sd,t[S.map.major]=id,t[S.tag.major]=ad,t[S.float.major]=cd,t}var NH=Py(),OH=new rd,dd=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(`${Ay} object contains circular references`);return new t(r,e)}},Cn={null:new N(S.null,null),undefined:new N(S.undefined,void 0),true:new N(S.true,!0),false:new N(S.false,!1),emptyArray:new N(S.array,0),emptyMap:new N(S.map,0)},In={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new N(S.float,t):t>=0?new N(S.uint,t):new N(S.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new N(S.uint,t):new N(S.negint,t)},Uint8Array(t,e,r,n){return new N(S.bytes,t)},string(t,e,r,n){return new N(S.string,t)},boolean(t,e,r,n){return t?Cn.true:Cn.false},null(t,e,r,n){return Cn.null},undefined(t,e,r,n){return Cn.undefined},ArrayBuffer(t,e,r,n){return new N(S.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new N(S.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[Cn.emptyArray,new N(S.break)]:Cn.emptyArray;n=dd.createCheck(n,t);let o=[],s=0;for(let i of t)o[s++]=ld(i,r,n);return r.addBreakTokens?[new N(S.array,t.length),o,new N(S.break)]:[new N(S.array,t.length),o]},Object(t,e,r,n){let o=e!=="Object",s=o?t.keys():Object.keys(t),i=o?t.size:s.length;if(!i)return r.addBreakTokens===!0?[Cn.emptyMap,new N(S.break)]:Cn.emptyMap;n=dd.createCheck(n,t);let a=[],c=0;for(let u of s)a[c++]=[ld(u,r,n),ld(o?t.get(u):t[u],r,n)];return o3(a,r),r.addBreakTokens?[new N(S.map,i),a,new N(S.break)]:[new N(S.map,i),a]}};In.Map=In.Object;In.Buffer=In.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))In[`${t}Array`]=In.DataView;function ld(t,e={},r){let n=sS(t),o=e&&e.typeEncoders&&e.typeEncoders[n]||In[n];if(typeof o=="function"){let i=o(t,n,e,r);if(i!=null)return i}let s=In[n];if(!s)throw new Error(`${Ay} unsupported type: ${n}`);return s(t,n,e,r)}function o3(t,e){e.mapSorter&&t.sort(e.mapSorter)}var jH=Symbol.for("DONE"),WH=Symbol.for("BREAK");var s3=Py(),i3={float64:!1,quickEncodeToken:By};function Ly(t,e=s3,r=i3){if(Array.isArray(t)){let n=0;for(let o of t)n+=Ly(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 Ry=class{constructor(e,r){this.bytes=e,this.byteOffset=r,this.roots=[],this.headerSize=r}addRoot(e,r){return a3(this,e,r),this}write(e){return c3(this,e),this}close(e){return u3(this,e)}},a3=(t,e,r={})=>{let{resize:n=!1}=r,{bytes:o,headerSize:s,byteOffset:i,roots:a}=t;t.roots.push(e);let c=Bn(t);if(c>s)if(c-s+i<o.byteLength)if(n)cE(t,c);else throw a.pop(),new RangeError(`Header of size ${s} has no capacity for new root ${e}.
|
3
|
-
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 a.pop(),new RangeError(`Buffer has no capacity for a new root ${e}`)},Er=({cid:t,bytes:e})=>{let r=t.bytes.byteLength+e.byteLength;return mc.default.encodingLength(r)+r},c3=(t,{cid:e,bytes:r})=>{let n=e.bytes.byteLength+r.byteLength,o=mc.default.encode(n);if(t.byteOffset+o.length+n>t.bytes.byteLength)throw new RangeError("Buffer has no capacity for this block");Uy(t,o),Uy(t,e.bytes),Uy(t,r)},u3=(t,e={})=>{let{resize:r=!1}=e,{roots:n,bytes:o,byteOffset:s,headerSize:i}=t,a=tr({version:1,roots:n}),c=mc.default.encode(a.length),u=c.length+a.byteLength;if(i-u===0)return aE(t,c,a),o.subarray(0,s);if(r)return cE(t,u),aE(t,c,a),o.subarray(0,t.byteOffset);throw new RangeError(`Header size was overestimated.
|
4
|
-
You can use close({ resize: true }) to resize header`)},cE=(t,e)=>{let{bytes:r,headerSize:n}=t;r.set(r.subarray(n,t.byteOffset),e),t.byteOffset+=e-n,t.headerSize=e},Uy=(t,e)=>{t.bytes.set(e,t.byteOffset),t.byteOffset+=e.length},aE=({bytes:t},e,r)=>{t.set(e),t.set(r,e.length)},l3=[new N(S.map,2),new N(S.string,"version"),new N(S.uint,1),new N(S.string,"roots")],d3=new N(S.tag,42),uE=t=>{let e=[...l3];e.push(new N(S.array,t.length));for(let n of t)e.push(d3),e.push(new N(S.bytes,{length:n+1}));let r=Ly(e);return mc.default.encodingLength(r)+r},Bn=({roots:t})=>uE(t.map(e=>e.bytes.byteLength)),lE=(t,e=36)=>uE(new Array(t).fill(e)),Pn=(t,e={})=>{let{roots:r=[],byteOffset:n=0,byteLength:o=t.byteLength,headerSize:s=Bn({roots:r})}=e,i=new Uint8Array(t,n,o),a=new Ry(i,s);for(let c of r)a.addRoot(c);return a};var f3="application/vnd.ipld.car",h3="CAR",dE=514,fd=class{constructor(e=[],r=0){this.written=new Set,this.blocks=e,this.byteLength=r}write(...e){for(let r of e){let n=r.cid.toString(Ve);this.written.has(n)||(this.blocks.push(r),this.byteLength+=Er(r),this.written.add(n))}return this}flush(...e){let r=[];for(let s of e.reverse()){let i=s.cid.toString(Ve);this.written.has(i)||(this.blocks.unshift(s),this.byteLength+=Er({cid:s.cid,bytes:s.bytes}),this.written.add(i)),r.unshift(s.cid)}this.byteLength+=Bn({roots:r});let n=new ArrayBuffer(this.byteLength),o=Pn(n,{roots:r});for(let s of this.blocks)o.write(s);return o.close()}},p3=()=>new fd,hd=({roots:t=[],blocks:e})=>{let r=new fd;return e&&r.write(...e.values()),r.flush(...t)},gc=t=>{let e=Vr.fromBytes(t),r=[],n=new Map;for(let o of e.getRoots()){let s=e.get(o);s&&r.push(s)}for(let o of e.blocks())n.set(o.cid.toString(),o);return{roots:r,blocks:n}},fE=async(t,{hasher:e=ue}={})=>Fe(dE,await e.digest(t)),m3=async(t,e)=>{let r=hd(t),n=await fE(r,e);return{bytes:r,cid:n}};var x={};F(x,{API:()=>le,Bytes:()=>vE,DID:()=>ee,Link:()=>pe,Text:()=>bg,URI:()=>V,and:()=>bE,array:()=>yE,boolean:()=>v3,bytes:()=>L3,dictionary:()=>hg,did:()=>Ad,endsWith:()=>EE,enum:()=>b3,error:()=>Ae,float:()=>B3,greaterThan:()=>kE,integer:()=>A3,intersection:()=>wE,lessThan:()=>xE,link:()=>Jr,literal:()=>gd,memberError:()=>Uo,never:()=>y3,nullable:()=>mE,number:()=>S3,ok:()=>C,optional:()=>bd,or:()=>gE,refine:()=>_E,startsWith:()=>SE,string:()=>Zr,struct:()=>Ne,text:()=>Dd,toString:()=>wc,tuple:()=>w3,typeError:()=>rt,uint64:()=>T3,unknown:()=>g3,uri:()=>yg,variant:()=>bc});var V={};F(V,{from:()=>O3,match:()=>yg,read:()=>N3,uri:()=>R3});var C=t=>{if(t==null)throw new TypeError(`ok(${t}) is not allowed, consider ok({}) instead`);return{ok:t}},pd=t=>{if(t==null)throw new TypeError(`error(${t}) is not allowed, consider passing an error instead`);return{error:t}},hE=t=>{throw new Vt(t)},ie=t=>({error:new Vt(t)}),Vt=class extends Error{describe(){return this.toString()}get message(){return this.describe()}toJSON(){let{name:e,message:r,stack:n}=this;return{name:e,message:r,stack:n}}};var le=class{constructor(e){this.settings=e}toString(){return`new ${this.constructor.name}()`}readWith(e,r){throw new Error("Abstract method readWith must be implemented by subclass")}read(e){return this.readWith(e,this.settings)}is(e){return!this.read(e)?.error}from(e){let r=this.read(e);if(r.error)throw r.error;return r.ok}optional(){return bd(this)}nullable(){return mE(this)}array(){return yE(this)}or(e){return gE(this,e)}and(e){return bE(this,e)}refine(e){return _E(this,e)}brand(e){return this}default(e){let r=this.from(e);if(r===void 0)throw new Error("Value of type undefined is not a valid default");return new Fy({reader:this,value:r})}},Ny=class extends le{toString(){return"never()"}read(e){return rt({expect:"never",actual:e})}},y3=()=>new Ny,Oy=class extends le{read(e){return{ok:e}}toString(){return"unknown()"}},g3=()=>new Oy,$y=class extends le{readWith(e,r){let n=r.read(e);return n.error?e===null?{ok:null}:{error:new wd({causes:[n.error,rt({expect:"null",actual:e}).error]})}:n}toString(){return`${this.settings}.nullable()`}},mE=t=>new $y(t),My=class extends le{optional(){return this}readWith(e,r){let n=r.read(e);return n.error&&e===void 0?{ok:void 0}:n}toString(){return`${this.settings}.optional()`}},Fy=class extends le{optional(){return this}readWith(e,{reader:r,value:n}){if(e===void 0)return{ok:n};{let o=r.read(e);return o.error||o.ok!==void 0?o:{ok:n}}}toString(){return`${this.settings.reader}.default(${JSON.stringify(this.settings.value)})`}get value(){return this.settings.value}},bd=t=>new My(t),zy=class extends le{readWith(e,r){if(!Array.isArray(e))return rt({expect:"array",actual:e});let n=[];for(let[o,s]of e.entries()){let i=r.read(s);if(i.error)return Uo({at:o,cause:i.error});n.push(i.ok)}return{ok:n}}get element(){return this.settings}toString(){return`array(${this.element})`}},yE=t=>new zy(t),jy=class extends le{readWith(e,r){if(!Array.isArray(e))return rt({expect:"array",actual:e});if(e.length!==this.shape.length)return Ae(`Array must contain exactly ${this.shape.length} elements`);let n=[];for(let[o,s]of r.entries()){let i=s.read(e[o]);if(i.error)return Uo({at:o,cause:i.error});n[o]=i.ok}return{ok:n}}get shape(){return this.settings}toString(){return`tuple([${this.shape.map(e=>e.toString()).join(", ")}])`}},w3=t=>new jy(t),Wy=class t extends le{readWith(e,{key:r,value:n}){if(typeof e!="object"||e===null||Array.isArray(e))return rt({expect:"dictionary",actual:e});let o={};for(let[s,i]of Object.entries(e)){let a=r.read(s);if(a.error)return Uo({at:s,cause:a.error});let c=n.read(i);if(c.error)return Uo({at:s,cause:c.error});c.ok!==void 0&&(o[a.ok]=c.ok)}return{ok:o}}get key(){return this.settings.key}get value(){return this.settings.value}partial(){let{key:e,value:r}=this.settings;return new t({key:e,value:bd(r)})}toString(){return`dictionary(${this.settings})`}},hg=({value:t,key:e})=>new Wy({value:t,key:e||Zr()}),Hy=class extends le{readWith(e,{variants:r,type:n}){return r.has(e)?{ok:e}:rt({expect:n,actual:e})}toString(){return this.settings.type}},b3=t=>new Hy({type:t.join("|"),variants:new Set(t)});var qy=class extends le{readWith(e,r){let n=[];for(let o of r){let s=o.read(e);if(s.error)n.push(s.error);else return s}return{error:new wd({causes:n})}}get variants(){return this.settings}toString(){return`union([${this.variants.map(e=>e.toString()).join(", ")}])`}},x3=t=>new qy(t),gE=(t,e)=>x3([t,e]),Vy=class extends le{readWith(e,r){let n=[];for(let o of r){let s=o.read(e);s.error&&n.push(s.error)}return n.length>0?{error:new fg({causes:n})}:{ok:e}}toString(){return`intersection([${this.settings.map(e=>e.toString()).join(",")}])`}},wE=t=>new Vy(t),bE=(t,e)=>wE([t,e]),Gy=class extends le{readWith(e){switch(e){case!0:case!1:return{ok:e};default:return rt({expect:"boolean",actual:e})}}toString(){return"boolean()"}},k3=new Gy,v3=()=>k3,md=class extends le{greaterThan(e){return this.refine(kE(e))}lessThan(e){return this.refine(xE(e))}refine(e){return new Zy({base:this,schema:e})}},Ky=class extends md{readWith(e){return typeof e=="number"?{ok:e}:rt({expect:"number",actual:e})}toString(){return"number()"}},pg=new Ky,S3=()=>pg,Zy=class extends md{readWith(e,{base:r,schema:n}){let o=r.read(e);return o.error?o:n.read(o.ok)}toString(){return`${this.settings.base}.refine(${this.settings.schema})`}},Jy=class extends le{readWith(e,r){return e<r?{ok:e}:Ae(`Expected ${e} < ${r}`)}toString(){return`lessThan(${this.settings})`}},xE=t=>new Jy(t),Qy=class extends le{readWith(e,r){return e>r?{ok:e}:Ae(`Expected ${e} > ${r}`)}toString(){return`greaterThan(${this.settings})`}},kE=t=>new Qy(t),E3={read(t){return Number.isInteger(t)?{ok:t}:rt({expect:"integer",actual:t})},toString(){return"Integer"}},_3=pg.refine(E3),A3=()=>_3,pE=2n**64n-1n,Xy=class extends le{read(e){switch(typeof e){case"bigint":return e>pE?Ae(`Integer is too big for uint64, ${e} > ${pE}`):e<0?Ae(`Negative integer can not be represented as uint64, ${e} < 0`):{ok:e};case"number":return Number.isInteger(e)?e<0?Ae(`Negative integer can not be represented as uint64, ${e} < 0`):{ok:BigInt(e)}:rt({expect:"uint64",actual:e});default:return rt({expect:"uint64",actual:e})}}toString(){return"uint64"}},D3=new Xy,T3=()=>D3,C3={read(t){return Number.isFinite(t)?{ok:t}:rt({expect:"Float",actual:t})},toString(){return"Float"}},I3=pg.refine(C3),B3=()=>I3,yd=class extends le{refine(e){let r=e;return new Yy({base:this,schema:r})}startsWith(e){return this.refine(SE(e))}endsWith(e){return this.refine(EE(e))}toString(){return"string()"}},Yy=class extends yd{readWith(e,{base:r,schema:n}){let o=r.read(e);return o.error?o:n.read(o.ok)}toString(){return`${this.settings.base}.refine(${this.settings.schema})`}},eg=class extends yd{readWith(e){return typeof e=="string"?{ok:e}:rt({expect:"string",actual:e})}},P3=new eg,Zr=()=>P3,tg=class extends le{readWith(e){return e instanceof Uint8Array?{ok:e}:rt({expect:"Uint8Array",actual:e})}},vE=new tg,L3=()=>vE,rg=class extends le{readWith(e,r){return e.startsWith(r)?{ok:e}:Ae(`Expect string to start with "${r}" instead got "${e}"`)}get prefix(){return this.settings}toString(){return`startsWith("${this.prefix}")`}},SE=t=>new rg(t),ng=class extends le{readWith(e,r){return e.endsWith(r)?{ok:e}:Ae(`Expect string to end with "${r}" instead got "${e}"`)}get suffix(){return this.settings}toString(){return`endsWith("${this.suffix}")`}},EE=t=>new ng(t),og=class extends le{readWith(e,{base:r,schema:n}){let o=r.read(e);return o.error?o:n.read(o.ok)}toString(){return`${this.settings.base}.refine(${this.settings.schema})`}},_E=(t,e)=>new og({base:t,schema:e}),sg=class extends le{readWith(e,r){return e!==r?{error:new ug({expect:r,actual:e})}:{ok:r}}get value(){return this.settings}default(e=this.value){return super.default(e)}toString(){return`literal(${wc(this.value)})`}},gd=t=>new sg(t),ig=class t extends le{readWith(e,r){if(typeof e!="object"||e===null||Array.isArray(e))return rt({expect:"object",actual:e});let n=e,o={},s=Object.entries(r);for(let[i,a]of s){let c=a.read(n[i]);if(c.error)return Uo({at:i,cause:c.error});c.ok!==void 0&&(o[i]=c.ok)}return{ok:o}}partial(){return new t(Object.fromEntries(Object.entries(this.shape).map(([e,r])=>[e,bd(r)])))}get shape(){return this.settings}toString(){return["struct({ ",...Object.entries(this.shape).map(([e,r])=>`${e}: ${r}`).join(", ")," })"].join("")}create(e){return this.from(e||{})}extend(e){return new t({...this.shape,...e})}},Ne=t=>{let e={},r=Object.entries(t);for(let[n,o]of r)switch(typeof o){case"number":case"string":case"boolean":e[n]=gd(o);break;case"object":e[n]=o===null?gd(null):o;break;default:throw new Error(`Invalid struct field "${n}", expected schema or literal, instead got ${typeof o}`)}return new ig(e)},ag=class extends le{readWith(e,r){if(typeof e!="object"||e===null||Array.isArray(e))return rt({expect:"object",actual:e});let n=Object.keys(e),[o]=n.length===1?n:[],s=o?r[o]:void 0;if(s){let i=s.read(e[o]);return i.error?Uo({at:o,cause:i.error}):{ok:{[o]:i.ok}}}else if(r._){let i=r._.read(e);return i.error?i:{ok:{_:i.ok}}}else return Ae(o?`Expected an object with one of the these keys: ${Object.keys(r).sort().join(", ")} instead got object with key ${o}`:"Expected an object with a single key instead got object with keys "+n.sort().join(", "))}match(e,r){let n=this.read(e);if(n.error){if(r!==void 0)return[null,r];throw n.error}else{let[o]=Object.keys(n.ok),s=n.ok[o];return[o,s]}}create(e){return this.from(e)}},bc=t=>new ag(t),Ae=t=>({error:new Kr(t)}),Kr=class extends Vt{get name(){return"SchemaError"}describe(){return this.name}},cg=class extends Kr{constructor({expect:e,actual:r}){super(),this.expect=e,this.actual=r}get name(){return"TypeError"}describe(){return`Expected value of type ${this.expect} instead got ${wc(this.actual)}`}},rt=t=>({error:new cg(t)}),wc=t=>{let e=typeof t;switch(e){case"boolean":case"string":return JSON.stringify(t);case"bigint":return`${t}n`;case"number":case"symbol":case"undefined":return String(t);case"object":return t===null?"null":Array.isArray(t)?"array":Symbol.toStringTag in t?t[Symbol.toStringTag]:"object";default:return e}},ug=class extends Kr{constructor({expect:e,actual:r}){super(),this.expect=e,this.actual=r}get name(){return"LiteralError"}describe(){return`Expected literal ${wc(this.expect)} instead got ${wc(this.actual)}`}},lg=class extends Kr{constructor({at:e,cause:r}){super(),this.at=e,this.cause=r}get name(){return"ElementError"}describe(){return[`Array contains invalid element at ${this.at}:`,xd(this.cause.message)].join(`
|
5
|
-
`)}},dg=class extends Kr{constructor({at:e,cause:r}){super(),this.at=e,this.cause=r}get name(){return"FieldError"}describe(){return[`Object contains invalid field "${this.at}":`,xd(this.cause.message)].join(`
|
6
|
-
`)}},Uo=({at:t,cause:e})=>typeof t=="string"?{error:new dg({at:t,cause:e})}:{error:new lg({at:t,cause:e})},wd=class extends Kr{constructor({causes:e}){super(),this.causes=e}get name(){return"UnionError"}describe(){let{causes:e}=this;return["Value does not match any type of the union:",...e.map(r=>xd(r.message))].join(`
|
7
|
-
`)}},fg=class extends Kr{constructor({causes:e}){super(),this.causes=e}get name(){return"IntersectionError"}describe(){let{causes:e}=this;return["Value does not match following types of the intersection:",...e.map(r=>xd(r.message))].join(`
|
8
|
-
`)}},U3=(t,e=" ")=>`${e}${t.split(`
|
9
|
-
`).join(`
|
10
|
-
${e}`)}`,xd=t=>U3(`- ${t}`);var vd=class extends le{readWith(e,{protocol:r}={}){if(typeof e!="string"&&!(e instanceof URL))return Ae(`Expected URI but got ${e===null?"null":typeof e}`);try{let n=new URL(String(e));return r!=null&&n.protocol!==r?Ae(`Expected ${r} URI instead got ${n.href}`):{ok:n.href}}catch{return Ae("Invalid URI")}}},mg=new vd({}),R3=()=>mg,N3=t=>mg.read(t),yg=t=>new vd(t),O3=t=>mg.from(t);var pe={};F(pe,{create:()=>Fe,createLegacy:()=>ai,isLink:()=>Se,link:()=>$3,match:()=>Jr,optional:()=>F3,parse:()=>br,read:()=>M3,schema:()=>Ed});var Sd=class extends le{readWith(e,{code:r,multihash:n={},version:o}){if(e==null)return Ae(`Expected link but got ${e} instead`);if(Se(e)){if(r!=null&&e.code!==r)return Ae(`Expected link to be CID with 0x${r.toString(16)} codec`);if(n.code!=null&&e.multihash.code!==n.code)return Ae(`Expected link to be CID with 0x${n.code.toString(16)} hashing algorithm`);if(o!=null&&e.version!==o)return Ae(`Expected link to be CID version ${o} instead of ${e.version}`);let[s,i]=n.digest!=null?[Ve.baseEncode(n.digest),Ve.baseEncode(e.multihash.digest)]:["",""];return s!==i?Ae(`Expected link with "${s}" hash digest instead of "${i}"`):{ok:e}}else return Ae(`Expected link to be a CID instead of ${e}`)}},Ed=new Sd({}),$3=()=>Ed,Jr=(t={})=>new Sd(t),M3=t=>Ed.read(t),F3=()=>Ed.optional();var ee={};F(ee,{did:()=>z3,from:()=>W3,match:()=>Ad,read:()=>j3});var _d=class extends le{readWith(e,r){let n=r?`did:${r}:`:"did:";return e.startsWith(n)?{ok:e}:Ae(`Expected a ${n} but got "${e}" instead`)}},AE=Zr().refine(new _d),z3=()=>AE,j3=t=>AE.read(t),Ad=(t={})=>Zr().refine(new _d(t.method)),W3=t=>Ad({}).from(t);var bg={};F(bg,{match:()=>Dd,read:()=>q3,text:()=>H3});var gg=Zr(),Dd=t=>t?gg.refine(new wg(t.pattern)):gg,H3=Dd,q3=t=>gg.read(t),wg=class extends le{readWith(e,r){return r.test(e)?{ok:e}:Ae(`Expected to match ${r} but got "${e}" instead`)}};var V3=Se,Ro=t=>!Se(t),G3=(...t)=>{let e={};for(let r of t)for(let{with:n,can:o,nb:s}of DE(r)){let i=e[n]||(e[n]={});(i[o]||(i[o]=[])).push({...s})}return e},DE=function*({issuer:t,capabilities:e,proofs:r}){for(let n of e)if(n.with==="ucan:*"){yield{...n,with:t.did()};for(let o of r)if(Ro(o))for(let s of DE(o)){let i=K3(s.can,n.can);i&&(yield{...s,can:i,nb:{...s.nb,...Object(n.nb)}})}}else yield n},K3=(t,e)=>t==="*"?e:e==="*"||e.endsWith("/*")&&t.startsWith(e.slice(0,-1))?t:t.endsWith("/*")&&e.startsWith(t.slice(0,-1))?e:t===e?t:null,Gt=class{constructor(e,r=new Map){this.root=e,this.blocks=r,Object.defineProperties(this,{blocks:{enumerable:!1}})}get attachedLinks(){let e=new Set,r=this.data;for(let n of r.capabilities){let o=Q3(n);for(let s of o)e.add(`${s}`)}for(let n of r.facts)if(Se(n))e.add(`${n}`);else{let o=Object.values(n).filter(s=>Se(s));for(let s of o)e.add(`${s}`)}return e}get version(){return this.data.version}get signature(){return this.data.signature}get cid(){return this.root.cid}link(){return this.root.cid}get asCID(){return this.cid}get bytes(){return this.root.bytes}get data(){let e=Td(this.root);return Object.defineProperties(this,{data:{value:e,enumerable:!1}}),e}attach(e){if(!this.attachedLinks.has(`${e.cid.link()}`))throw new Error(`given block with ${e.cid} is not an attached link`);this.blocks.set(`${e.cid}`,e)}export(){return kg(this.root,this.blocks,this.attachedLinks)}archive(){return TE(this)}iterateIPLDBlocks(){return kg(this.root,this.blocks,this.attachedLinks)}get proofs(){return J3(this)}get issuer(){return this.data.issuer}get audience(){return this.data.audience}get capabilities(){return this.data.capabilities}get expiration(){return this.data.expiration}get notBefore(){return this.data.notBefore}get nonce(){return this.data.nonce}get facts(){return this.data.facts}iterate(){return IE(this)}delegate(){return this}buildIPLDView(){return this}toJSON(){return{...this.data.toJSON(),"/":this.cid.toString(),prf:this.proofs.map(e=>Ro(e)?e:{"/":e.toString()})}}},TE=async t=>{try{let e=new Map;for(let o of t.iterateIPLDBlocks())e.set(`${o.cid}`,o);let r=await Sy({[`ucan@${t.version}`]:t.root.cid});e.set(`${r.cid}`,r);let n=hd({roots:[r],blocks:e});return C(n)}catch(e){return pd(e)}},CE=bc({"ucan@0.9.1":Jr({version:1})}),Z3=async t=>{try{let{roots:e,blocks:r}=gc(t),[n]=e;if(n==null)return Ae("CAR archive does not contain a root block");let{bytes:o}=n,s=Ge(o),[,i]=CE.match(s);return C(Cd({root:i,blocks:r}))}catch(e){return pd(e)}},IE=function*(t){for(let e of t.proofs)Ro(e)&&(yield*IE(e),yield e)},xg=new WeakMap,Td=({bytes:t})=>{let e=xg.get(t);if(!e){let r=ql(t);return xg.set(t,r),r}return e},Lt=async({issuer:t,audience:e,proofs:r=[],attachedBlocks:n=new Map,...o},s)=>{let i=[],a=new Map;for(let p of r)if(!Ro(p))i.push(p);else{i.push(p.cid);for(let f of p.export())a.set(f.cid.toString(),f)}let c=await gi({...o,issuer:t,audience:e,proofs:i}),{cid:u,bytes:l}=await Vl(c,s);xg.set(u,c);let d=new Gt({cid:u,bytes:l},a);Object.defineProperties(d,{proofs:{value:r}});for(let p of n.values())d.attach(p);return d},kg=function*(t,e,r){for(let n of Td(t).proofs){let o=e.get(`${n}`);o&&(yield*BE(o,e))}for(let n of r.values()){let o=e.get(n);o&&(yield o)}yield t},BE=function*(t,e){for(let r of Td(t).proofs){let n=e.get(`${r}`);n&&(yield*BE(n,e))}yield t},vg=t=>{let e=[];for(let n of t)e.push([n.cid.toString(),n]);let r=e.pop();if(r){let[,n]=r;return new Gt(n,new Map(e))}else throw new RangeError("Empty DAG can not be turned into a delegation")},Sg=({root:t,blocks:e})=>new Gt(t,e),Cd=({root:t,blocks:e},r)=>{let n=_n(t,e,null);return n==null?r!==void 0?r:qr(t):Sg({root:n,blocks:e})},J3=t=>{let e=[],{root:r,blocks:n}=t;for(let o of Td(r).proofs){let s=n.get(o.toString());e.push(s?Sg({root:s,blocks:n}):o)}return Object.defineProperty(t,"proofs",{value:e}),e};function Q3(t){let e=[];function r(n){for(let o in n){let s=n[o];Se(s)?e.push(s):s&&typeof s=="object"&&r(s)}}return r(t),e}var Oo={};F(Oo,{Invocation:()=>Id,create:()=>PE,invoke:()=>No,view:()=>_g});var No=t=>new Eg(t),PE=({root:t,blocks:e})=>new Id(t,e),_g=({root:t,blocks:e},r)=>{let n=_n(t,e,null);return n==null?r!==void 0?r:qr(t):PE({root:n,blocks:e})},Eg=class{constructor({issuer:e,audience:r,capability:n,proofs:o=[],expiration:s,lifetimeInSeconds:i,notBefore:a,nonce:c,facts:u=[]}){this.issuer=e,this.audience=r,this.proofs=o,this.capabilities=[n],this.expiration=s,this.lifetimeInSeconds=i,this.notBefore=a,this.nonce=c,this.facts=u,this.attachedBlocks=new Map}attach(e){this.attachedBlocks.set(`${e.cid}`,e)}delegate(){return Lt(this)}buildIPLDView(){return Lt(this)}async execute(e){let r=this,[n]=await e.execute(r);return n}},Id=class extends Gt{};var _r={};F(_r,{MessageSchema:()=>LE,build:()=>eU,view:()=>tU});var xc={};F(xc,{issue:()=>Y3,view:()=>Pd});var Pd=({root:t,blocks:e},r)=>{let n=_n(t,e,null);if(n==null)return r!==void 0?r:qr(t);let o=Ge(n.bytes);return new Bd({root:{...n,data:o},store:e})},Bd=class{constructor({root:e,store:r,ran:n,issuer:o,signature:s,proofs:i}){this.store=r,this.root=e,this._ran=n,this._signature=s,this._proofs=i,this._issuer=o}get ran(){let e=this._ran;if(e)return e;{let r=_g({root:this.root.data.ocm.ran,blocks:this.store},this.root.data.ocm.ran);return this._ran=r,r}}get proofs(){let e=this._proofs;if(e)return e;{let{store:r,root:n}=this,{prf:o}=n.data.ocm,s=[];if(o)for(let i of o){let a=Cd({root:i,blocks:r},i);s.push(a)}return this._proofs=s,s}}get meta(){return this.root.data.ocm.meta}get issuer(){let e=this._issuer;if(e)return e;{let{iss:r}=this.root.data.ocm;if(r){let n=Ue(r);return this._issuer=n,n}}}get out(){return this.root.data.ocm.out}get fx(){return this.root.data.ocm.fx}get signature(){let e=this._signature;if(e)return e;{let r=hi(this.root.data.sig);return this._signature=r,r}}verifySignature(e){return this.signature.verify(e,Bo(this.root.data.ocm))}buildIPLDView(){return this}*iterateIPLDBlocks(){let{ran:e,fx:r,proofs:n,root:o}=this;yield*Po(e);for(let s of r.fork)yield*Po(s);r.join&&(yield*Po(r.join));for(let s of n)yield*Po(s);yield o}},Ag=class{constructor({issuer:e,result:r,ran:n,fx:o=X3,proofs:s=[],meta:i={}}){this.issuer=e,this.result=r,this.ran=n,this.fx=o,this.proofs=s,this.meta=i}async buildIPLDView({hasher:e=ue,codec:r=xr}={}){let n=G1();Zl(Po(this.ran),n);for(let c of this.proofs)Zl(Po(c),n);let o={ran:this.ran.link(),out:this.result,fx:this.fx,meta:this.meta,iss:this.issuer.did(),prf:this.proofs.map(c=>c.link())},s=await this.issuer.sign(Bo(o)),a=await Kl({ocm:o,sig:s},n,{hasher:e,codec:r});return new Bd({root:a,store:n,signature:s,proofs:this.proofs,ran:this.ran})}},X3=Object.freeze({fork:Object.freeze([])}),Y3=t=>new Ag(t).buildIPLDView();var LE=bc({"ucanto/message@7.0.0":Ne({execute:Jr().array().optional(),delegate:hg({key:Zr(),value:Jr()}).array().optional()})}),eU=({invocations:t,receipts:e})=>new Dg({invocations:t,receipts:e}).buildIPLDView(),tU=({root:t,store:e},r)=>{let n=_n(t,e,null);if(n===null)return r!==void 0?r:qr(t);let o=xr.decode(n.bytes),[s,i]=LE.match(o,r);switch(s){case"ucanto/message@7.0.0":return new Ld({root:{...n,data:o},store:e});default:return i}},Dg=class{constructor({invocations:e,receipts:r}){this.invocations=e,this.receipts=r}async buildIPLDView(e){let r=new Map,{invocations:n,...o}=await rU(this.invocations||[],r),{receipts:s,...i}=await nU(this.receipts||[],r),a=await Kl({"ucanto/message@7.0.0":{...o,...i}},r,e);return new Ld({root:a,store:r},{receipts:s,invocations:n})}},rU=async(t,e)=>{let r=[],n=[];for(let o of t){let s=await o.buildIPLDView();n.push(s.link()),r.push(s);for(let i of s.iterateIPLDBlocks())e.set(`${i.cid}`,i)}return{invocations:r,...n.length>0?{execute:n}:{}}},nU=async(t,e)=>{if(t.length===0)return{};let r=new Map,n={};for(let[o,s]of t.entries()){let i=await s.buildIPLDView();for(let c of i.iterateIPLDBlocks())e.set(`${c.cid}`,c);let a=`${i.ran.link()}`;a in n?r.set(`${a}@${o}`,i):(n[a]=i.root.cid,r.set(a,i))}return{receipts:r,report:n}},Ld=class{constructor({root:e,store:r},{invocations:n,receipts:o}={}){this.root=e,this.store=r,this._invocations=n,this._receipts=o}*iterateIPLDBlocks(){for(let e of this.invocations)yield*e.iterateIPLDBlocks();for(let e of this.receipts.values())yield*e.iterateIPLDBlocks();yield this.root}get(e,r){let o=(this.root.data["ucanto/message@7.0.0"].report||{})[`${e}`];return o?Pd({root:o,blocks:this.store}):r!==void 0?r:hE(`Message does not include receipt for ${e}`)}get invocationLinks(){return this.root.data["ucanto/message@7.0.0"].execute||[]}get invocations(){let e=this._invocations;return e||(e=this.invocationLinks.map(r=>Oo.view({root:r,blocks:this.store}))),e}get receipts(){let e=this._receipts;if(!e){e=new Map;let r=this.root.data["ucanto/message@7.0.0"].report||{};for(let[n,o]of Object.entries(r)){let s=Pd({root:o,blocks:this.store});e.set(`${s.ran.link()}`,s)}}return e}};var $o=t=>new Cg(t),Cg=class{constructor(e){this.id=e.id,this.options=e,this.codec=e.codec,this.channel=e.channel,this.hasher=e.hasher||ue}async execute(...e){return sU(e,this)}},sU=async(t,e)=>{let r=await _r.build({invocations:t}),n=await e.codec.encode(r,e),o=await e.channel.request(n);try{let s=await e.codec.decode(o);return r.invocationLinks.map(a=>s.get(a))}catch(s){let{message:i,...a}=s,c=[];for await(let u of r.invocationLinks){let l=await xc.issue({ran:u,result:{error:{...a,message:i}},issuer:{did(){return e.id.did()},sign(){return st.createNonStandard("",new Uint8Array)}}});c.push(l)}return c}};var Cq=sr.delegate;var ir={};F(ir,{codec:()=>Re,contentType:()=>Rd,inbound:()=>mU,outbound:()=>Ug,request:()=>Mo,response:()=>Fo});var Mo={};F(Mo,{codec:()=>Re,contentType:()=>_i,decode:()=>uU,encode:()=>cU});var _i=Re.contentType,aU=Object.freeze({"content-type":_i,accept:_i}),cU=(t,e)=>{let r=new Map;for(let o of t.iterateIPLDBlocks())r.set(`${o.cid}`,o);let n=Re.encode({roots:[t.root],blocks:r});return{headers:e?.headers||aU,body:n}},uU=async({headers:t,body:e})=>{let{roots:r,blocks:n}=Re.decode(e);return _r.view({root:r[0].cid,store:n})};var Fo={};F(Fo,{codec:()=>Re,contentType:()=>kc,decode:()=>fU,encode:()=>dU});var kc=Re.contentType,lU=Object.freeze({"content-type":kc}),dU=(t,e)=>{let r=new Map;for(let o of t.iterateIPLDBlocks())r.set(`${o.cid}`,o);let n=Re.encode({roots:[t.root],blocks:r});return{headers:lU,body:n}},fU=async({headers:t,body:e})=>{let{roots:r,blocks:n}=Re.decode(e);return _r.view({root:r[0].cid,store:n})};var Ud=t=>new Ig(t),Ig=class{accept({headers:e}){let r=e["content-type"]||e["Content-Type"],n=this.decoders[r];if(!n)return{error:{status:415,message:"The server cannot process the request because the payload format is not supported. Please check the content-type header and try again with a supported media type.",headers:{accept:Object.keys(this.decoders).join(", ")}}};let o=pU(e.accept||e.Accept||"*/*");for(let{category:s,type:i}of o)for(let a of this.encoders)if((s==="*"||s===a.category)&&(i==="*"||i===a.type))return{ok:{...a,decoder:n}};return{error:{status:406,message:"The requested resource cannot be served in the requested content type. Please specify a supported content type using the Accept header.",headers:{accept:RE(Object.values(this.encoders))}}}}constructor({decoders:e={},encoders:r={}}){if(this.decoders=e,Object.keys(e).length===0)throw new Error("At least one decoder MUST be provided");if(this.encoders=Object.entries(r).map(([n,o])=>({...Pg(n),encoder:o})).sort((n,o)=>o.preference-n.preference),this.encoders.length===0)throw new Error("At least one encoder MUST be provided")}},UE=t=>new Bg(t),Bg=class{constructor({decoders:e={},encoders:r={}}){if(this.decoders=e,Object.keys(e).length===0)throw new Error("At least one decoder MUST be provided");if(this.encoders=Object.entries(r).map(([n,o])=>({...Pg(n),encoder:o})).sort((n,o)=>o.preference-n.preference),this.acceptType=RE(this.encoders),this.encoders.length===0)throw new Error("At least one encoder MUST be provided");this.encoder=this.encoders[0].encoder}encode(e){return this.encoder.encode(e,{accept:this.acceptType})}decode(e){let{headers:r}=e,n=r["content-type"]||r["Content-Type"],o=this.decoders[n]||this.decoders["*/*"];switch(e.status){case 415:case 406:throw Object.assign(new RangeError(new TextDecoder().decode(e.body)),{status:e.status,headers:e.headers})}if(!o)throw Object.assign(TypeError(`Can not decode response with content-type '${n}' because no matching transport decoder is configured.`),{error:!0});return o.decode(e)}},Pg=t=>{let[e="*/*",r=""]=t.trim().split(";"),[n="*",o="*"]=e.split("/"),s=new URLSearchParams(r),i=parseFloat(s.get("q")||"0");return{category:n,type:o,preference:isNaN(i)?0:i}},hU=({category:t,type:e,preference:r})=>`${t}/${e}${r?`;q=${r}`:""}`,pU=t=>t.split(",").map(Pg).sort((e,r)=>r.preference-e.preference),RE=t=>t.map(hU).join(", ");var Rd=Re.contentType,mU=Ud({decoders:{[_i]:Mo},encoders:{[kc]:Fo}}),Ug=UE({encoders:{[_i]:Mo},decoders:{[kc]:Fo}});var Ln={};F(Ln,{open:()=>Og});var Og=({url:t,method:e="POST",fetch:r})=>{if(!r)if(typeof globalThis.fetch<"u")r=globalThis.fetch.bind(globalThis);else throw new TypeError("ucanto HTTP transport got undefined `fetch`. Try passing in a `fetch` implementation explicitly.");return new Rg({url:t,method:e,fetch:r})},Rg=class{constructor({url:e,fetch:r,method:n}){this.fetch=r,this.method=n,this.url=e}async request({headers:e,body:r}){let n=await this.fetch(this.url.href,{headers:e,body:r,method:this.method}),o=n.ok?await n.arrayBuffer():Ng.throw("HTTP Request failed",n);return{headers:n.headers.entries?Object.fromEntries(n.headers.entries()):{},body:new Uint8Array(o)}}},Ng=class extends Error{static throw(e,r){throw new this(e,r)}constructor(e,{url:r,status:n=500,statusText:o="Server error"}){super(e),this.name="HTTPError",this.url=r,this.status=n,this.statusText=o}};var Ti={};F(Ti,{PUB_KEY_OFFSET:()=>r_,code:()=>Di,decode:()=>Yg,derive:()=>n_,encode:()=>s_,format:()=>FU,from:()=>o_,generate:()=>MU,name:()=>OU,or:()=>Xg,parse:()=>zU,signatureAlgorithm:()=>e_,signatureCode:()=>$U});var yU=De(NE(),1);var Qe=BigInt(0),he=BigInt(1),Nn=BigInt(2),gU=BigInt(8),OE=BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),Ie=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),l:OE,n:OE,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")});var jE=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000"),vc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Oq=BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742"),wU=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),bU=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),xU=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),kU=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Ke=class t{constructor(e,r,n,o){this.x=e,this.y=r,this.z=n,this.t=o}static fromAffine(e){if(!(e instanceof je))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(je.ZERO)?t.ZERO:new t(e.x,e.y,he,A(e.x*e.y))}static toAffineBatch(e){let r=EU(e.map(n=>n.z));return e.map((n,o)=>n.toAffine(r[o]))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){ME(e);let{x:r,y:n,z:o}=this,{x:s,y:i,z:a}=e,c=A(r*a),u=A(s*o),l=A(n*a),d=A(i*o);return c===u&&l===d}negate(){return new t(A(-this.x),this.y,this.z,A(-this.t))}double(){let{x:e,y:r,z:n}=this,{a:o}=Ie,s=A(e*e),i=A(r*r),a=A(Nn*A(n*n)),c=A(o*s),u=e+r,l=A(A(u*u)-s-i),d=c+i,p=d-a,f=c-i,h=A(l*p),m=A(d*f),b=A(l*f),g=A(p*d);return new t(h,m,g,b)}add(e){ME(e);let{x:r,y:n,z:o,t:s}=this,{x:i,y:a,z:c,t:u}=e,l=A((n-r)*(a+i)),d=A((n+r)*(a-i)),p=A(d-l);if(p===Qe)return this.double();let f=A(o*Nn*u),h=A(s*Nn*c),m=h+f,b=d+l,g=h-f,k=A(m*p),E=A(b*g),_=A(m*g),P=A(p*b);return new t(k,E,P,_)}subtract(e){return this.add(e.negate())}precomputeWindow(e){let r=1+256/e,n=[],o=this,s=o;for(let i=0;i<r;i++){s=o,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(o),n.push(s);o=s.double()}return n}wNAF(e,r){!r&&this.equals(t.BASE)&&(r=je.BASE);let n=r&&r._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let o=r&&jg.get(r);o||(o=this.precomputeWindow(n),r&&n!==1&&(o=t.normalizeZ(o),jg.set(r,o)));let s=t.ZERO,i=t.BASE,a=1+256/n,c=2**(n-1),u=BigInt(2**n-1),l=2**n,d=BigInt(n);for(let p=0;p<a;p++){let f=p*c,h=Number(e&u);e>>=d,h>c&&(h-=l,e+=he);let m=f,b=f+Math.abs(h)-1,g=p%2!==0,k=h<0;h===0?i=i.add($E(g,o[m])):s=s.add($E(k,o[b]))}return t.normalizeZ([s,i])[0]}multiply(e,r){return this.wNAF(Od(e,Ie.l),r)}multiplyUnsafe(e){let r=Od(e,Ie.l,!1),n=t.BASE,o=t.ZERO;if(r===Qe)return o;if(this.equals(o)||r===he)return this;if(this.equals(n))return this.wNAF(r);let s=o,i=this;for(;r>Qe;)r&he&&(s=s.add(i)),i=i.double(),r>>=he;return s}isSmallOrder(){return this.multiplyUnsafe(Ie.h).equals(t.ZERO)}isTorsionFree(){let e=this.multiplyUnsafe(Ie.l/Nn).double();return Ie.l%Nn&&(e=e.add(this)),e.equals(t.ZERO)}toAffine(e){let{x:r,y:n,z:o}=this,s=this.equals(t.ZERO);e==null&&(e=s?gU:$d(o));let i=A(r*e),a=A(n*e),c=A(o*e);if(s)return je.ZERO;if(c!==he)throw new Error("invZ was invalid");return new je(i,a)}fromRistrettoBytes(){Mg()}toRistrettoBytes(){Mg()}fromRistrettoHash(){Mg()}};Ke.BASE=new Ke(Ie.Gx,Ie.Gy,he,A(Ie.Gx*Ie.Gy));Ke.ZERO=new Ke(Qe,he,he,Qe);function $E(t,e){let r=e.negate();return t?r:e}function ME(t){if(!(t instanceof Ke))throw new TypeError("ExtendedPoint expected")}function $g(t){if(!(t instanceof zo))throw new TypeError("RistrettoPoint expected")}function Mg(){throw new Error("Legacy method: switch to RistrettoPoint")}var zo=class t{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){let{d:r}=Ie,n=A(vc*e*e),o=A((n+he)*xU),s=BigInt(-1),i=A((s-r*n)*A(n+r)),{isValid:a,value:c}=Hg(o,i),u=A(c*e);Rn(u)||(u=A(-u)),a||(c=u),a||(s=n);let l=A(s*(n-he)*kU-i),d=c*c,p=A((c+c)*i),f=A(l*wU),h=A(he-d),m=A(he+d);return new Ke(A(p*m),A(h*f),A(f*m),A(p*h))}static hashToCurve(e){e=On(e,64);let r=Fg(e.slice(0,32)),n=this.calcElligatorRistrettoMap(r),o=Fg(e.slice(32,64)),s=this.calcElligatorRistrettoMap(o);return new t(n.add(s))}static fromHex(e){e=On(e,32);let{a:r,d:n}=Ie,o="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",s=Fg(e);if(!AU(Ec(s),e)||Rn(s))throw new Error(o);let i=A(s*s),a=A(he+r*i),c=A(he-r*i),u=A(a*a),l=A(c*c),d=A(r*n*u-l),{isValid:p,value:f}=zE(A(d*l)),h=A(f*c),m=A(f*h*d),b=A((s+s)*h);Rn(b)&&(b=A(-b));let g=A(a*m),k=A(b*g);if(!p||Rn(k)||g===Qe)throw new Error(o);return new t(new Ke(b,g,he,k))}toRawBytes(){let{x:e,y:r,z:n,t:o}=this.ep,s=A(A(n+r)*A(n-r)),i=A(e*r),a=A(i*i),{value:c}=zE(A(s*a)),u=A(c*s),l=A(c*i),d=A(u*l*o),p;if(Rn(o*d)){let h=A(r*vc),m=A(e*vc);e=h,r=m,p=A(u*bU)}else p=l;Rn(e*d)&&(r=A(-r));let f=A((n-r)*p);return Rn(f)&&(f=A(-f)),Ec(f)}toHex(){return _c(this.toRawBytes())}toString(){return this.toHex()}equals(e){$g(e);let r=this.ep,n=e.ep,o=A(r.x*n.y)===A(r.y*n.x),s=A(r.y*n.y)===A(r.x*n.x);return o||s}add(e){return $g(e),new t(this.ep.add(e.ep))}subtract(e){return $g(e),new t(this.ep.subtract(e.ep))}multiply(e){return new t(this.ep.multiply(e))}multiplyUnsafe(e){return new t(this.ep.multiplyUnsafe(e))}};zo.BASE=new zo(Ke.BASE);zo.ZERO=new zo(Ke.ZERO);var jg=new WeakMap,je=class t{constructor(e,r){this.x=e,this.y=r}_setWindowSize(e){this._WINDOW_SIZE=e,jg.delete(this)}static fromHex(e,r=!0){let{d:n,P:o}=Ie;e=On(e,32);let s=e.slice();s[31]=e[31]&-129;let i=Ac(s);if(r&&i>=o)throw new Error("Expected 0 < hex < P");if(!r&&i>=jE)throw new Error("Expected 0 < hex < 2**256");let a=A(i*i),c=A(a-he),u=A(n*a+he),{isValid:l,value:d}=Hg(c,u);if(!l)throw new Error("Point.fromHex: invalid y coordinate");let p=(d&he)===he;return(e[31]&128)!==0!==p&&(d=A(-d)),new t(d,i)}static async fromPrivateKey(e){return(await Md(e)).point}toRawBytes(){let e=Ec(this.y);return e[31]|=this.x&he?128:0,e}toHex(){return _c(this.toRawBytes())}toX25519(){let{y:e}=this,r=A((he+e)*$d(he-e));return Ec(r)}isTorsionFree(){return Ke.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new t(A(-this.x),this.y)}add(e){return Ke.fromAffine(this).add(Ke.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Ke.fromAffine(this).multiply(e,this).toAffine()}};je.BASE=new je(Ie.Gx,Ie.Gy);je.ZERO=new je(Qe,he);var Sc=class t{constructor(e,r){this.r=e,this.s=r,this.assertValidity()}static fromHex(e){let r=On(e,64),n=je.fromHex(r.slice(0,32),!1),o=Ac(r.slice(32,64));return new t(n,o)}assertValidity(){let{r:e,s:r}=this;if(!(e instanceof je))throw new Error("Expected Point instance");return Od(r,Ie.l,!1),this}toRawBytes(){let e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(Ec(this.s),32),e}toHex(){return _c(this.toRawBytes())}};function FE(...t){if(!t.every(n=>n instanceof Uint8Array))throw new Error("Expected Uint8Array list");if(t.length===1)return t[0];let e=t.reduce((n,o)=>n+o.length,0),r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}var vU=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function _c(t){if(!(t instanceof Uint8Array))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=vU[t[r]];return e}function Wg(t){if(typeof t!="string")throw new TypeError("hexToBytes: expected string, got "+typeof t);if(t.length%2)throw new Error("hexToBytes: received invalid unpadded hex");let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++){let n=r*2,o=t.slice(n,n+2),s=Number.parseInt(o,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[r]=s}return e}function WE(t){let r=t.toString(16).padStart(64,"0");return Wg(r)}function Ec(t){return WE(t).reverse()}function Rn(t){return(A(t)&he)===he}function Ac(t){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");return BigInt("0x"+_c(Uint8Array.from(t).reverse()))}var SU=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function Fg(t){return A(Ac(t)&SU)}function A(t,e=Ie.P){let r=t%e;return r>=Qe?r:e+r}function $d(t,e=Ie.P){if(t===Qe||e<=Qe)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=A(t,e),n=e,o=Qe,s=he,i=he,a=Qe;for(;r!==Qe;){let u=n/r,l=n%r,d=o-i*u,p=s-a*u;n=r,r=l,o=i,s=a,i=d,a=p}if(n!==he)throw new Error("invert: does not exist");return A(o,e)}function EU(t,e=Ie.P){let r=new Array(t.length),n=t.reduce((s,i,a)=>i===Qe?s:(r[a]=s,A(s*i,e)),he),o=$d(n,e);return t.reduceRight((s,i,a)=>i===Qe?s:(r[a]=A(s*r[a],e),A(s*i,e)),o),r}function Ar(t,e){let{P:r}=Ie,n=t;for(;e-- >Qe;)n*=n,n%=r;return n}function _U(t){let{P:e}=Ie,r=BigInt(5),n=BigInt(10),o=BigInt(20),s=BigInt(40),i=BigInt(80),c=t*t%e*t%e,u=Ar(c,Nn)*c%e,l=Ar(u,he)*t%e,d=Ar(l,r)*l%e,p=Ar(d,n)*d%e,f=Ar(p,o)*p%e,h=Ar(f,s)*f%e,m=Ar(h,i)*h%e,b=Ar(m,i)*h%e,g=Ar(b,n)*d%e;return{pow_p_5_8:Ar(g,Nn)*t%e,b2:c}}function Hg(t,e){let r=A(e*e*e),n=A(r*r*e),o=_U(t*n).pow_p_5_8,s=A(t*r*o),i=A(e*s*s),a=s,c=A(s*vc),u=i===t,l=i===A(-t),d=i===A(-t*vc);return u&&(s=a),(l||d)&&(s=c),Rn(s)&&(s=A(-s)),{isValid:u||l,value:s}}function zE(t){return Hg(he,t)}function Nd(t){return A(Ac(t),Ie.l)}function AU(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function On(t,e){let r=t instanceof Uint8Array?Uint8Array.from(t):Wg(t);if(typeof e=="number"&&r.length!==e)throw new Error(`Expected ${e} bytes`);return r}function Od(t,e,r=!0){if(!e)throw new TypeError("Specify max value");if(typeof t=="number"&&Number.isSafeInteger(t)&&(t=BigInt(t)),typeof t=="bigint"&&t<e){if(r){if(Qe<t)return t}else if(Qe<=t)return t}throw new TypeError("Expected valid scalar: 0 < scalar < max")}function DU(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function TU(t){if(t=typeof t=="bigint"||typeof t=="number"?WE(Od(t,jE)):On(t),t.length!==32)throw new Error("Expected 32 bytes");return t}function CU(t){let e=DU(t.slice(0,32)),r=t.slice(32,64),n=Nd(e),o=je.BASE.multiply(n),s=o.toRawBytes();return{head:e,prefix:r,scalar:n,point:o,pointBytes:s}}var zg;async function Md(t){return CU(await $n.sha512(TU(t)))}async function HE(t){return(await Md(t)).pointBytes}async function qE(t,e){t=On(t);let{prefix:r,scalar:n,pointBytes:o}=await Md(e),s=Nd(await $n.sha512(r,t)),i=je.BASE.multiply(s),a=Nd(await $n.sha512(i.toRawBytes(),o,t)),c=A(s+a*n,Ie.l);return new Sc(i,c).toRawBytes()}function IU(t,e,r){e=On(e),r instanceof je||(r=je.fromHex(r,!1));let{r:n,s:o}=t instanceof Sc?t.assertValidity():Sc.fromHex(t),s=Ke.BASE.multiplyUnsafe(o);return{r:n,s:o,SB:s,pub:r,msg:e}}function BU(t,e,r,n){let o=Nd(n),s=Ke.fromAffine(t).multiplyUnsafe(o);return Ke.fromAffine(e).add(s).subtract(r).multiplyUnsafe(Ie.h).equals(Ke.ZERO)}async function VE(t,e,r){let{r:n,SB:o,msg:s,pub:i}=IU(t,e,r),a=await $n.sha512(n.toRawBytes(),i.toRawBytes(),s);return BU(i,n,o,a)}je.BASE._setWindowSize(8);var Un={node:yU,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0},$n={bytesToHex:_c,hexToBytes:Wg,concatBytes:FE,getExtendedPublicKey:Md,mod:A,invert:$d,TORSION_SUBGROUP:["0100000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a","0000000000000000000000000000000000000000000000000000000000000080","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05","ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85","0000000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"],hashToPrivateScalar:t=>{if(t=On(t),t.length<40||t.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return A(Ac(t),Ie.l-he)+he},randomBytes:(t=32)=>{if(Un.web)return Un.web.getRandomValues(new Uint8Array(t));if(Un.node){let{randomBytes:e}=Un.node;return new Uint8Array(e(t).buffer)}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>$n.randomBytes(32),sha512:async(...t)=>{let e=FE(...t);if(Un.web){let r=await Un.web.subtle.digest("SHA-512",e.buffer);return new Uint8Array(r)}else{if(Un.node)return Uint8Array.from(Un.node.createHash("sha512").update(e).digest());throw new Error("The environment doesn't have sha512 function")}},precompute(t=8,e=je.BASE){let r=e.equals(je.BASE)?e:new je(e.x,e.y);return r._setWindowSize(t),r.multiply(Nn),r},sha512Sync:void 0};Object.defineProperties($n,{sha512Sync:{configurable:!1,get(){return zg},set(t){zg||(zg=t)}}});var jo={};F(jo,{code:()=>Dr,decode:()=>jd,encode:()=>UU,format:()=>LU,name:()=>Kg,or:()=>RU,parse:()=>QE,signatureAlgorithm:()=>zd,signatureCode:()=>Tc});var PU=(t,e)=>{if(t.startsWith("did:")){for(let r of e)try{return r.parse(t)}catch{}throw new Error(`Unsupported did ${t}`)}else throw new Error(`Expected did instead got ${t}`)},Fd=(t,e)=>new qg([t,e]),qg=class t{constructor(e){this.variants=e}parse(e){return PU(e,this.variants)}or(e){return new t([...this.variants,e])}},Dc=(t,e)=>new Vg(e,t),Vg=class{constructor(e,r){this.id=e,this.key=r}did(){return this.id}toDIDKey(){return this.key.toDIDKey()}verify(e,r){return this.key.verify(e,r)}withDID(e){return Dc(this.key,e)}};var Dr=237,Kg="Ed25519",Tc=To,zd="EdDSA",JE=Y.encodingLength(Dr),ZE=32+JE,QE=t=>jd(Ue(t)),jd=t=>{let[e]=Y.decode(t);if(e!==Dr)throw new RangeError(`Unsupported key algorithm with multicode 0x${Dr.toString(16)}`);if(t.byteLength!==ZE)throw new RangeError(`Expected Uint8Array with byteLength ${ZE}, instead got Uint8Array with byteLength ${t.byteLength}`);return new Gg(t.buffer,t.byteOffset,t.byteLength)},LU=t=>Ao(t),UU=t=>Qm(t),Gg=class extends Uint8Array{get code(){return Dr}get signatureCode(){return Tc}get signatureAlgorithm(){return zd}get publicKey(){let e=new Uint8Array(this.buffer,this.byteOffset+JE);return Object.defineProperties(this,{publicKey:{value:e}}),e}did(){return`did:key:${Le.encode(this)}`}verify(e,r){return r.code===Tc&&VE(r.raw,e,this.publicKey)}withDID(e){return Dc(this,e)}toDIDKey(){return this.did()}},RU=t=>Fd({parse:QE},t);var Wd=(t,e)=>new Zg([t,e]),Zg=class t{constructor(e){this.variants=e,this.from=NU(e)}or(e){return new t([e,...this.variants])}},NU=t=>r=>{if(r.id.startsWith("did:key:"))return XE(r,t);for(let[n,o]of Object.entries(r.keys)){let s=n;return XE({id:s,keys:{[s]:o}},t).withDID(r.id)}throw new Error(`Archive ${r.id} contains no keys`)},XE=(t,e)=>{for(let r of e)try{return r.from(t)}catch{}throw new Error("Unsupported signer")},Ai=({signer:t,verifier:e},r)=>new Jg(t,e.withDID(r)),Jg=class{constructor(e,r){this.key=e,this.verifier=r}get signer(){return this}get signatureAlgorithm(){return this.key.signatureAlgorithm}get signatureCode(){return this.key.signatureCode}did(){return this.verifier.did()}toDIDKey(){return this.verifier.toDIDKey()}withDID(e){return Ai(this.key,e)}sign(e){return this.key.sign(e)}verify(e,r){return this.verifier.verify(e,r)}toArchive(){let{keys:e}=this.key.toArchive();return{id:this.did(),keys:e}}};var Di=4864,OU=Kg,e_=zd,$U=Tc,Wo=Y.encodingLength(Di),t_=Y.encodingLength(Dr),Qr=32,Qg=Wo+Qr+t_+Qr,r_=Wo+Qr,MU=()=>n_($n.randomPrivateKey()),n_=async t=>{if(t.byteLength!==Qr)throw new Error(`Expected Uint8Array with byteLength of ${Qr} instead not ${t.byteLength}`);let e=await HE(t),r=new Hd(Qg);return Y.encodeTo(Di,r,0),r.set(t,Wo),Y.encodeTo(Dr,r,Wo+Qr),r.set(e,Wo+Qr+t_),r},o_=({id:t,keys:e})=>{if(t.startsWith("did:key:")){let r=e[t];if(r instanceof Uint8Array)return Yg(r)}throw new TypeError("Unsupported archive format")},Xg=t=>Wd({from:o_},t),Yg=t=>{if(t.byteLength!==Qg)throw new Error(`Expected Uint8Array with byteLength of ${Qg} instead not ${t.byteLength}`);{let[e]=Y.decode(t);if(e!==Di)throw new Error(`Given bytes must be a multiformat with ${Di} tag`)}{let[e]=Y.decode(t.subarray(r_));if(e!==Dr)throw new Error(`Given bytes must contain public key in multiformats with ${Dr} tag`)}return new Hd(t)},s_=t=>t.encode(),FU=(t,e)=>(e||Ml).encode(s_(t)),zU=(t,e)=>Yg((e||Ml).decode(t)),Hd=class extends Uint8Array{get code(){return Di}get signer(){return this}get verifier(){let e=new Uint8Array(this.buffer,Wo+Qr),r=jd(e);return Object.defineProperties(this,{verifier:{value:r}}),r}get secret(){let e=new Uint8Array(this.buffer,Wo,Qr);return Object.defineProperties(this,{secret:{value:e}}),e}did(){return this.verifier.did()}toDIDKey(){return this.verifier.toDIDKey()}withDID(e){return Ai(this,e)}async sign(e){let r=await qE(e,this.secret);return fi(this.signatureCode,r)}verify(e,r){return this.verifier.verify(e,r)}get signatureAlgorithm(){return e_}get signatureCode(){return To}encode(){return this}toArchive(){let e=this.did();return{id:e,keys:{[e]:this.encode()}}}};function Ho(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Cc(t=0){return globalThis.Buffer?.allocUnsafe!=null?Ho(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function ew(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=Cc(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return Ho(r)}var tw={};F(tw,{identity:()=>WU});var WU=ii({prefix:"\0",name:"identity",encode:t=>i1(t),decode:t=>s1(t)});var rw={};F(rw,{base2:()=>HU});var HU=Me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var nw={};F(nw,{base8:()=>qU});var qU=Me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ow={};F(ow,{base10:()=>VU});var VU=Sn({prefix:"9",name:"base10",alphabet:"0123456789"});var sw={};F(sw,{base16:()=>GU,base16upper:()=>KU});var GU=Me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),KU=Me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var iw={};F(iw,{base36:()=>ZU,base36upper:()=>JU});var ZU=Sn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),JU=Sn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var aw={};F(aw,{base256emoji:()=>t4});var i_=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}"),QU=i_.reduce((t,e,r)=>(t[r]=e,t),[]),XU=i_.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function YU(t){return t.reduce((e,r)=>(e+=QU[r],e),"")}function e4(t){let e=[];for(let r of t){let n=XU[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var t4=ii({prefix:"\u{1F680}",name:"base256emoji",encode:YU,decode:e4});var iV=new TextEncoder,aV=new TextDecoder;var cw={...tw,...rw,...nw,...ow,...sw,...Wm,...iw,...jm,...Xm,...aw},uV={...vy,...Vm};function c_(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var a_=c_("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),uw=c_("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=Cc(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),n4={utf8:a_,"utf-8":a_,hex:cw.base16,latin1:uw,ascii:uw,binary:uw,...cw},qd=n4;function Xr(t,e="utf8"){let r=qd[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ho(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function Ic(t,e="utf8"){let r=qd[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}function o4(t){if(!Array.isArray(t)||t.length===0)throw new Error("Delegations required to be an non empty array.");let e=t.map(a=>a.root.cid),r=new Set,n=[],o=0;for(let a of t)for(let c of a.export()){let u=c.cid.toV1().toString();r.has(u)||(o+=Er(c),n.push(c),r.add(u))}let s=lE(e.length),i=Pn(new ArrayBuffer(s+o),{roots:e});for(let a of n)i.write(a);return i.close()}function Vd(t){if(!(t instanceof Uint8Array)||t.length===0)throw new TypeError("Input should be a non-empty Uint8Array.");let e=Vr.fromBytes(t),r=e.getRoots(),n=[];for(let o of r){let s=e.get(o);if(s){let i=new Map;for(let a of e.blocks())a.cid.toString()!==o.toString()&&i.set(a.cid.toString(),a);n.push(new Gt(s,i))}else throw new Error("Failed to find root from raw delegation.")}return n}function l_(t,e="base64url"){let r=o4(t);return Ic(r,e)}function d_(t,e="base64url"){let r=Xr(t,e);return Vd(r)}var xe;(function(t){t.assertEqual=o=>o;function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(xe||(xe={}));var M=xe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Mn=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}},B=xe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),s4=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ut=class extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}toString(){return this.message}get message(){return JSON.stringify(this.issues,xe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ut.create=t=>new Ut(t);var Bc=(t,e)=>{let r;switch(t.code){case B.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case B.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,xe.jsonStringifyReplacer)}`;break;case B.unrecognized_keys:r=`Unrecognized key(s) in object: ${xe.joinValues(t.keys,", ")}`;break;case B.invalid_union:r="Invalid input";break;case B.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${xe.joinValues(t.options)}`;break;case B.invalid_enum_value:r=`Invalid enum value. Expected ${xe.joinValues(t.options)}, received '${t.received}'`;break;case B.invalid_arguments:r="Invalid function arguments";break;case B.invalid_return_type:r="Invalid function return type";break;case B.invalid_date:r="Invalid date";break;case B.invalid_string:typeof t.validation=="object"?"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:xe.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case B.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case B.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case B.custom:r="Invalid input";break;case B.invalid_intersection_types:r="Intersection results could not be merged";break;case B.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case B.not_finite:r="Number must be finite";break;default:r=e.defaultError,xe.assertNever(t)}return{message:r}},p_=Bc;function i4(t){p_=t}function Kd(){return p_}var Zd=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s},a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:o.message||a}},a4=[];function z(t,e){let r=Zd({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Kd(),Bc].filter(n=>!!n)});t.common.issues.push(r)}var it=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return te;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r)n.push({key:await o.key,value:await o.value});return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return te;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},te=Object.freeze({status:"aborted"}),m_=t=>({status:"dirty",value:t}),dt=t=>({status:"valid",value:t}),lw=t=>t.status==="aborted",dw=t=>t.status==="dirty",Jd=t=>t.status==="valid",Qd=t=>typeof Promise<"u"&&t instanceof Promise,K;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(K||(K={}));var Kt=class{constructor(e,r,n,o){this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._path.concat(this._key)}},f_=(t,e)=>{if(Jd(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,error:new Ut(t.common.issues)}};function re(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>i.code!=="invalid_type"?{message:a.defaultError}:typeof a.data>"u"?{message:n??a.defaultError}:{message:r??a.defaultError},description:o}}var ne=class{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Mn(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Mn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new it,ctx:{common:e.parent.common,data:e.data,parsedType:Mn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Qd(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){var n;let o={common:{issues:[],async:(n=r?.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Mn(e)},s=this._parseSync({data:e,path:o.path,parent:o});return f_(o,s)}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Mn(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Qd(o)?o:Promise.resolve(o));return f_(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:B.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Rt({schema:this,typeName:Q.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return ar.create(this,this._def)}nullable(){return tn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return en.create(this,this._def)}promise(){return jn.create(this,this._def)}or(e){return Qo.create([this,e],this._def)}and(e){return Xo.create(this,e,this._def)}transform(e){return new Rt({...re(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new ns({...re(this._def),innerType:this,defaultValue:r,typeName:Q.ZodDefault})}brand(){return new rf({typeName:Q.ZodBranded,type:this,...re(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Ui({...re(this._def),innerType:this,catchValue:r,typeName:Q.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Pc.create(this,e)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},c4=/^c[^\s-]{8,}$/i,u4=/^[a-z][a-z0-9]*$/,l4=/^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i,d4=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/,f4=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,h4=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,p4=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,m4=t=>t.precision?t.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${t.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${t.precision}}Z$`):t.precision===0?t.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):t.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function y4(t,e){return!!((e==="v4"||!e)&&h4.test(t)||(e==="v6"||!e)&&p4.test(t))}var Fn=class t extends ne{constructor(){super(...arguments),this._regex=(e,r,n)=>this.refinement(o=>e.test(o),{validation:r,code:B.invalid_string,...K.errToObj(n)}),this.nonempty=e=>this.min(1,K.errToObj(e)),this.trim=()=>new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let s=this._getOrReturnCtx(e);return z(s,{code:B.invalid_type,expected:M.string,received:s.parsedType}),te}let n=new it,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),z(o,{code:B.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),z(o,{code:B.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?z(o,{code:B.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&z(o,{code:B.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")d4.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"email",code:B.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")f4.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"emoji",code:B.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")l4.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"uuid",code:B.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")c4.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"cuid",code:B.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")u4.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"cuid2",code:B.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),z(o,{validation:"url",code:B.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"regex",code:B.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),z(o,{code:B.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),z(o,{code:B.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?m4(s).test(e.data)||(o=this._getOrReturnCtx(e,o),z(o,{code:B.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="ip"?y4(e.data,s.version)||(o=this._getOrReturnCtx(e,o),z(o,{validation:"ip",code:B.invalid_string,message:s.message}),n.dirty()):xe.assertNever(s);return{status:n.value,value:e.data}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...K.errToObj(e)})}url(e){return this._addCheck({kind:"url",...K.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...K.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...K.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...K.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...K.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...K.errToObj(e)})}datetime(e){var r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(r=e?.offset)!==null&&r!==void 0?r:!1,...K.errToObj(e?.message)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...K.errToObj(r)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...K.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...K.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...K.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...K.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...K.errToObj(r)})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Fn.create=t=>{var e;return new Fn({checks:[],typeName:Q.ZodString,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,...re(t)})};function g4(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=parseInt(t.toFixed(o).replace(".","")),i=parseInt(e.toFixed(o).replace(".",""));return s%i/Math.pow(10,o)}var qo=class t extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){let s=this._getOrReturnCtx(e);return z(s,{code:B.invalid_type,expected:M.number,received:s.parsedType}),te}let n,o=new it;for(let s of this._def.checks)s.kind==="int"?xe.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:B.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:B.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:B.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?g4(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),z(n,{code:B.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:B.not_finite,message:s.message}),o.dirty()):xe.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,K.toString(r))}gt(e,r){return this.setLimit("min",e,!1,K.toString(r))}lte(e,r){return this.setLimit("max",e,!0,K.toString(r))}lt(e,r){return this.setLimit("max",e,!1,K.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:K.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:K.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:K.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:K.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:K.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:K.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:K.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&xe.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};qo.create=t=>new qo({checks:[],typeName:Q.ZodNumber,coerce:t?.coerce||!1,...re(t)});var Vo=class t extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==M.bigint){let s=this._getOrReturnCtx(e);return z(s,{code:B.invalid_type,expected:M.bigint,received:s.parsedType}),te}let n,o=new it;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:B.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:B.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),z(n,{code:B.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):xe.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,K.toString(r))}gt(e,r){return this.setLimit("min",e,!1,K.toString(r))}lte(e,r){return this.setLimit("max",e,!0,K.toString(r))}lt(e,r){return this.setLimit("max",e,!1,K.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:K.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:K.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:K.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:K.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:K.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:K.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Vo.create=t=>{var e;return new Vo({checks:[],typeName:Q.ZodBigInt,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,...re(t)})};var Go=class extends ne{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let n=this._getOrReturnCtx(e);return z(n,{code:B.invalid_type,expected:M.boolean,received:n.parsedType}),te}return dt(e.data)}};Go.create=t=>new Go({typeName:Q.ZodBoolean,coerce:t?.coerce||!1,...re(t)});var Ko=class t extends ne{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let s=this._getOrReturnCtx(e);return z(s,{code:B.invalid_type,expected:M.date,received:s.parsedType}),te}if(isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return z(s,{code:B.invalid_date}),te}let n=new it,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),z(o,{code:B.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),z(o,{code:B.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):xe.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:K.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:K.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Ko.create=t=>new Ko({checks:[],coerce:t?.coerce||!1,typeName:Q.ZodDate,...re(t)});var Ii=class extends ne{_parse(e){if(this._getType(e)!==M.symbol){let n=this._getOrReturnCtx(e);return z(n,{code:B.invalid_type,expected:M.symbol,received:n.parsedType}),te}return dt(e.data)}};Ii.create=t=>new Ii({typeName:Q.ZodSymbol,...re(t)});var Zo=class extends ne{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return z(n,{code:B.invalid_type,expected:M.undefined,received:n.parsedType}),te}return dt(e.data)}};Zo.create=t=>new Zo({typeName:Q.ZodUndefined,...re(t)});var Jo=class extends ne{_parse(e){if(this._getType(e)!==M.null){let n=this._getOrReturnCtx(e);return z(n,{code:B.invalid_type,expected:M.null,received:n.parsedType}),te}return dt(e.data)}};Jo.create=t=>new Jo({typeName:Q.ZodNull,...re(t)});var zn=class extends ne{constructor(){super(...arguments),this._any=!0}_parse(e){return dt(e.data)}};zn.create=t=>new zn({typeName:Q.ZodAny,...re(t)});var Yr=class extends ne{constructor(){super(...arguments),this._unknown=!0}_parse(e){return dt(e.data)}};Yr.create=t=>new Yr({typeName:Q.ZodUnknown,...re(t)});var cr=class extends ne{_parse(e){let r=this._getOrReturnCtx(e);return z(r,{code:B.invalid_type,expected:M.never,received:r.parsedType}),te}};cr.create=t=>new cr({typeName:Q.ZodNever,...re(t)});var Bi=class extends ne{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return z(n,{code:B.invalid_type,expected:M.void,received:n.parsedType}),te}return dt(e.data)}};Bi.create=t=>new Bi({typeName:Q.ZodVoid,...re(t)});var en=class t extends ne{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==M.array)return z(r,{code:B.invalid_type,expected:M.array,received:r.parsedType}),te;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(z(r,{code:i?B.too_big:B.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(z(r,{code:B.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(z(r,{code:B.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Kt(r,i,r.path,a)))).then(i=>it.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Kt(r,i,r.path,a)));return it.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:K.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:K.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:K.toString(r)}})}nonempty(e){return this.min(1,e)}};en.create=(t,e)=>new en({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...re(e)});var Xd;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Xd||(Xd={}));function Ci(t){if(t instanceof wt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ar.create(Ci(n))}return new wt({...t._def,shape:()=>e})}else return t instanceof en?en.create(Ci(t.element)):t instanceof ar?ar.create(Ci(t.unwrap())):t instanceof tn?tn.create(Ci(t.unwrap())):t instanceof Tr?Tr.create(t.items.map(e=>Ci(e))):t}var wt=class t extends ne{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=xe.objectKeys(e);return this._cached={shape:e,keys:r}}_parse(e){if(this._getType(e)!==M.object){let u=this._getOrReturnCtx(e);return z(u,{code:B.invalid_type,expected:M.object,received:u.parsedType}),te}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof cr&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Kt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof cr){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(z(o,{code:B.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Kt(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key;u.push({key:d,value:await l.value,alwaysSet:l.alwaysSet})}return u}).then(u=>it.mergeObjectSync(n,u)):it.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return K.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{var o,s,i,a;let c=(i=(s=(o=this._def).errorMap)===null||s===void 0?void 0:s.call(o,r,n).message)!==null&&i!==void 0?i:n.defaultError;return r.code==="unrecognized_keys"?{message:(a=K.errToObj(e).message)!==null&&a!==void 0?a:c}:{message:c}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>Xd.mergeShapes(this._def.shape(),e._def.shape()),typeName:Q.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};return xe.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new t({...this._def,shape:()=>r})}omit(e){let r={};return xe.objectKeys(this.shape).forEach(n=>{e[n]||(r[n]=this.shape[n])}),new t({...this._def,shape:()=>r})}deepPartial(){return Ci(this)}partial(e){let r={};return xe.objectKeys(this.shape).forEach(n=>{let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}),new t({...this._def,shape:()=>r})}required(e){let r={};return xe.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ar;)s=s._def.innerType;r[n]=s}}),new t({...this._def,shape:()=>r})}keyof(){return y_(xe.objectKeys(this.shape))}};wt.create=(t,e)=>new wt({shape:()=>t,unknownKeys:"strip",catchall:cr.create(),typeName:Q.ZodObject,...re(e)});wt.strictCreate=(t,e)=>new wt({shape:()=>t,unknownKeys:"strict",catchall:cr.create(),typeName:Q.ZodObject,...re(e)});wt.lazycreate=(t,e)=>new wt({shape:t,unknownKeys:"strip",catchall:cr.create(),typeName:Q.ZodObject,...re(e)});var Qo=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ut(a.ctx.common.issues));return z(r,{code:B.invalid_union,unionErrors:i}),te}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ut(c));return z(r,{code:B.invalid_union,unionErrors:a}),te}}get options(){return this._def.options}};Qo.create=(t,e)=>new Qo({options:t,typeName:Q.ZodUnion,...re(e)});var Gd=t=>t instanceof Yo?Gd(t.schema):t instanceof Rt?Gd(t.innerType()):t instanceof es?[t.value]:t instanceof ts?t.options:t instanceof rs?Object.keys(t.enum):t instanceof ns?Gd(t._def.innerType):t instanceof Zo?[void 0]:t instanceof Jo?[null]:null,Yd=class t extends ne{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.object)return z(r,{code:B.invalid_type,expected:M.object,received:r.parsedType}),te;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(z(r,{code:B.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),te)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Gd(s.shape[e]);if(!i)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:Q.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...re(n)})}};function fw(t,e){let r=Mn(t),n=Mn(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){let o=xe.objectKeys(e),s=xe.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=fw(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===M.array&&n===M.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=fw(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Xo=class extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(lw(s)||lw(i))return te;let a=fw(s.value,i.value);return a.valid?((dw(s)||dw(i))&&r.dirty(),{status:r.value,value:a.data}):(z(n,{code:B.invalid_intersection_types}),te)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Xo.create=(t,e,r)=>new Xo({left:t,right:e,typeName:Q.ZodIntersection,...re(r)});var Tr=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return z(n,{code:B.invalid_type,expected:M.array,received:n.parsedType}),te;if(n.data.length<this._def.items.length)return z(n,{code:B.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),te;!this._def.rest&&n.data.length>this._def.items.length&&(z(n,{code:B.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Kt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>it.mergeArray(r,i)):it.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Tr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Tr({items:t,typeName:Q.ZodTuple,rest:null,...re(e)})};var ef=class t extends ne{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return z(n,{code:B.invalid_type,expected:M.object,received:n.parsedType}),te;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Kt(n,a,n.path,a)),value:i._parse(new Kt(n,n.data[a],n.path,a))});return n.common.async?it.mergeObjectAsync(r,o):it.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ne?new t({keyType:e,valueType:r,typeName:Q.ZodRecord,...re(n)}):new t({keyType:Fn.create(),valueType:e,typeName:Q.ZodRecord,...re(r)})}},Pi=class extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return z(n,{code:B.invalid_type,expected:M.map,received:n.parsedType}),te;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new Kt(n,a,n.path,[u,"key"])),value:s._parse(new Kt(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return te;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return te;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Pi.create=(t,e,r)=>new Pi({valueType:e,keyType:t,typeName:Q.ZodMap,...re(r)});var Li=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return z(n,{code:B.invalid_type,expected:M.set,received:n.parsedType}),te;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(z(n,{code:B.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(z(n,{code:B.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return te;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Kt(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:K.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:K.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Li.create=(t,e)=>new Li({valueType:t,minSize:null,maxSize:null,typeName:Q.ZodSet,...re(e)});var tf=class t extends ne{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.function)return z(r,{code:B.invalid_type,expected:M.function,received:r.parsedType}),te;function n(a,c){return Zd({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Kd(),Bc].filter(u=>!!u),issueData:{code:B.invalid_arguments,argumentsError:c}})}function o(a,c){return Zd({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Kd(),Bc].filter(u=>!!u),issueData:{code:B.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;return this._def.returns instanceof jn?dt(async(...a)=>{let c=new Ut([]),u=await this._def.args.parseAsync(a,s).catch(p=>{throw c.addIssue(n(a,p)),c}),l=await i(...u);return await this._def.returns._def.type.parseAsync(l,s).catch(p=>{throw c.addIssue(o(l,p)),c})}):dt((...a)=>{let c=this._def.args.safeParse(a,s);if(!c.success)throw new Ut([n(a,c.error)]);let u=i(...c.data),l=this._def.returns.safeParse(u,s);if(!l.success)throw new Ut([o(u,l.error)]);return l.data})}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Tr.create(e).rest(Yr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Tr.create([]).rest(Yr.create()),returns:r||Yr.create(),typeName:Q.ZodFunction,...re(n)})}},Yo=class extends ne{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Yo.create=(t,e)=>new Yo({getter:t,typeName:Q.ZodLazy,...re(e)});var es=class extends ne{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return z(r,{received:r.data,code:B.invalid_literal,expected:this._def.value}),te}return{status:"valid",value:e.data}}get value(){return this._def.value}};es.create=(t,e)=>new es({value:t,typeName:Q.ZodLiteral,...re(e)});function y_(t,e){return new ts({values:t,typeName:Q.ZodEnum,...re(e)})}var ts=class t extends ne{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return z(r,{expected:xe.joinValues(n),received:r.parsedType,code:B.invalid_type}),te}if(this._def.values.indexOf(e.data)===-1){let r=this._getOrReturnCtx(e),n=this._def.values;return z(r,{received:r.data,code:B.invalid_enum_value,options:n}),te}return dt(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e){return t.create(e)}exclude(e){return t.create(this.options.filter(r=>!e.includes(r)))}};ts.create=y_;var rs=class extends ne{_parse(e){let r=xe.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let o=xe.objectValues(r);return z(n,{expected:xe.joinValues(o),received:n.parsedType,code:B.invalid_type}),te}if(r.indexOf(e.data)===-1){let o=xe.objectValues(r);return z(n,{received:n.data,code:B.invalid_enum_value,options:o}),te}return dt(e.data)}get enum(){return this._def.values}};rs.create=(t,e)=>new rs({values:t,typeName:Q.ZodNativeEnum,...re(e)});var jn=class extends ne{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return z(r,{code:B.invalid_type,expected:M.promise,received:r.parsedType}),te;let n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return dt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};jn.create=(t,e)=>new jn({type:t,typeName:Q.ZodPromise,...re(e)});var Rt=class extends ne{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null;if(o.type==="preprocess"){let i=o.transform(n.data);return n.common.async?Promise.resolve(i).then(a=>this._def.schema._parseAsync({data:a,path:n.path,parent:n})):this._def.schema._parseSync({data:i,path:n.path,parent:n})}let s={addIssue:i=>{z(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?te:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?te:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Jd(i))return i;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Jd(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):i);xe.assertNever(o)}};Rt.create=(t,e,r)=>new Rt({schema:t,typeName:Q.ZodEffects,effect:e,...re(r)});Rt.createWithPreprocess=(t,e,r)=>new Rt({schema:e,effect:{type:"preprocess",transform:t},typeName:Q.ZodEffects,...re(r)});var ar=class extends ne{_parse(e){return this._getType(e)===M.undefined?dt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ar.create=(t,e)=>new ar({innerType:t,typeName:Q.ZodOptional,...re(e)});var tn=class extends ne{_parse(e){return this._getType(e)===M.null?dt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};tn.create=(t,e)=>new tn({innerType:t,typeName:Q.ZodNullable,...re(e)});var ns=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ns.create=(t,e)=>new ns({innerType:t,typeName:Q.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...re(e)});var Ui=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Qd(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ut(n.common.issues)}})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ut(n.common.issues)}})}}removeCatch(){return this._def.innerType}};Ui.create=(t,e)=>new Ui({innerType:t,typeName:Q.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...re(e)});var Ri=class extends ne{_parse(e){if(this._getType(e)!==M.nan){let n=this._getOrReturnCtx(e);return z(n,{code:B.invalid_type,expected:M.nan,received:n.parsedType}),te}return{status:"valid",value:e.data}}};Ri.create=t=>new Ri({typeName:Q.ZodNaN,...re(t)});var w4=Symbol("zod_brand"),rf=class extends ne{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Pc=class t extends ne{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?te:s.status==="dirty"?(r.dirty(),m_(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?te:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Q.ZodPipeline})}},g_=(t,e={},r)=>t?zn.create().superRefine((n,o)=>{var s,i;if(!t(n)){let a=typeof e=="function"?e(n):e,c=(i=(s=a.fatal)!==null&&s!==void 0?s:r)!==null&&i!==void 0?i:!0,u=typeof a=="string"?{message:a}:a;o.addIssue({code:"custom",...u,fatal:c})}}):zn.create(),b4={object:wt.lazycreate},Q;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline"})(Q||(Q={}));var x4=(t,e={message:`Input not instance of ${t.name}`})=>g_(r=>r instanceof t,e),w_=Fn.create,b_=qo.create,k4=Ri.create,v4=Vo.create,x_=Go.create,S4=Ko.create,E4=Ii.create,_4=Zo.create,A4=Jo.create,D4=zn.create,T4=Yr.create,C4=cr.create,I4=Bi.create,B4=en.create,P4=wt.create,L4=wt.strictCreate,U4=Qo.create,R4=Yd.create,N4=Xo.create,O4=Tr.create,$4=ef.create,M4=Pi.create,F4=Li.create,z4=tf.create,j4=Yo.create,W4=es.create,H4=ts.create,q4=rs.create,V4=jn.create,h_=Rt.create,G4=ar.create,K4=tn.create,Z4=Rt.createWithPreprocess,J4=Pc.create,Q4=()=>w_().optional(),X4=()=>b_().optional(),Y4=()=>x_().optional(),eR={string:t=>Fn.create({...t,coerce:!0}),number:t=>qo.create({...t,coerce:!0}),boolean:t=>Go.create({...t,coerce:!0}),bigint:t=>Vo.create({...t,coerce:!0}),date:t=>Ko.create({...t,coerce:!0})},tR=te,Xe=Object.freeze({__proto__:null,defaultErrorMap:Bc,setErrorMap:i4,getErrorMap:Kd,makeIssue:Zd,EMPTY_PATH:a4,addIssueToContext:z,ParseStatus:it,INVALID:te,DIRTY:m_,OK:dt,isAborted:lw,isDirty:dw,isValid:Jd,isAsync:Qd,get util(){return xe},ZodParsedType:M,getParsedType:Mn,ZodType:ne,ZodString:Fn,ZodNumber:qo,ZodBigInt:Vo,ZodBoolean:Go,ZodDate:Ko,ZodSymbol:Ii,ZodUndefined:Zo,ZodNull:Jo,ZodAny:zn,ZodUnknown:Yr,ZodNever:cr,ZodVoid:Bi,ZodArray:en,get objectUtil(){return Xd},ZodObject:wt,ZodUnion:Qo,ZodDiscriminatedUnion:Yd,ZodIntersection:Xo,ZodTuple:Tr,ZodRecord:ef,ZodMap:Pi,ZodSet:Li,ZodFunction:tf,ZodLazy:Yo,ZodLiteral:es,ZodEnum:ts,ZodNativeEnum:rs,ZodPromise:jn,ZodEffects:Rt,ZodTransformer:Rt,ZodOptional:ar,ZodNullable:tn,ZodDefault:ns,ZodCatch:Ui,ZodNaN:Ri,BRAND:w4,ZodBranded:rf,ZodPipeline:Pc,custom:g_,Schema:ne,ZodSchema:ne,late:b4,get ZodFirstPartyTypeKind(){return Q},coerce:eR,any:D4,array:B4,bigint:v4,boolean:x_,date:S4,discriminatedUnion:R4,effect:h_,enum:H4,function:z4,instanceof:x4,intersection:N4,lazy:j4,literal:W4,map:M4,nan:k4,nativeEnum:q4,never:C4,null:A4,nullable:K4,number:b_,object:P4,oboolean:Y4,onumber:X4,optional:G4,ostring:Q4,pipeline:J4,preprocess:Z4,promise:V4,record:$4,set:F4,strictObject:L4,string:w_,symbol:E4,transformer:h_,tuple:O4,undefined:_4,union:U4,unknown:T4,void:I4,NEVER:tR,ZodIssueCode:B,quotelessJson:s4,ZodError:Ut});var rR=Xe.enum(["awake/init","awake/res","awake/msg"]),v_=Xe.object({awv:Xe.literal("0.1.0"),type:rR}),S_=Xe.object({did:Xe.string().startsWith("did:",{message:"should be a DID `did:key:z...`"}),sig:Xe.string()}).strict(),E_=Xe.object({"awake/ack":Xe.string().startsWith("did:",{message:"should be a DID `did:key:z...`"})}).strict(),NV=v_.extend({type:Xe.literal("awake/init"),did:Xe.string().startsWith("did:",{message:"should be a DID `did:key:z...`"}),caps:Xe.array(Xe.object({with:Xe.string(),can:Xe.string()})).nonempty()}).strict(),k_=Xe.string().startsWith("did:",{message:"should be a DID `did:key:z...`"}),OV=v_.extend({type:Xe.literal("awake/res"),iss:k_,aud:k_,msg:Xe.string().min(1)}).strict();var nf=class{constructor(e){this.channel=e.channel,this.agent=e.agent,this.did=e.agent.did(),this.challenge=void 0,this.nextdid=void 0,this.audience=void 0,this.pin=Math.floor(Math.random()*1e6)}async bootstrap(e){this.channel.sendInit(e);let{ucan:r}=await this.channel.awaitRes(),n=__(r.facts,"awake/challenge");if(this.nextdid=Ue(__(r.facts,"awake/nextdid")),n==="oob-pin")return await this.sendPinSignature(),this.pin.toString()}async awaitBootstrap(){let e=await this.channel.awaitInit();this.nextdid=e.did;let r=await gi({issuer:this.agent.issuer,audience:this.nextdid,capabilities:[{with:"awake:",can:"*"}],facts:[{"awake/challenge":"oob-pin"},{"awake/nextdid":this.channel.keypair.did}]});await this.channel.sendRes(this.nextdid,r);let n=await this.channel.awaitMsg(this.nextdid),{did:o,sig:s}=S_.parse(n.msg);this.audience=Ue(o),this.challenge=s}async ack(e){if(!this.challenge||!this.nextdid||!this.audience)throw new Error("No challenge active.");let r=Xr(this.challenge,"base64"),n=jo.parse(this.audience.did()),o=Xr(this.channel.keypair.did+e),s=await ue.encode(o);if(!await n.verify(s,En(r)))throw new Error(`Challenge failed: ${e} is not valid for the current challenge.`);await this.channel.sendMsg(this.nextdid,{"awake/ack":this.did})}async awaitAck(){if(!this.nextdid)throw new Error("No session is active. await ack");let e=await this.channel.awaitMsg(this.nextdid),r=E_.parse(e.msg);this.audience=Ue(r["awake/ack"])}async link(e){if(!this.nextdid||!this.audience)throw new Error("No session is active. request link");let r={type:"link",meta:e.meta,caps:e.caps};this.channel.sendMsg(this.nextdid,r);let n=await this.channel.awaitMsg(this.nextdid),o=d_(n.msg.delegation);return await this.channel.sendFin(this.nextdid),await this.agent.addProof(o[0]),{delegation:o[0],meta:n.msg.meta}}async awaitLink(){if(!this.nextdid||!this.audience)throw new Error("No challenge active.");let e=await this.channel.awaitMsg(this.nextdid),r=await this.agent.delegate({abilities:["*"],audience:this.audience,expiration:1/0,audienceMeta:e.msg.meta});this.channel.subscribe("awake/msg",n=>{this.channel.close()}),this.channel.sendMsg(this.nextdid,{meta:{name:this.agent.did(),type:"device"},delegation:l_([r])})}async sendPinSignature(){if(!this.nextdid)throw new Error("No session is active.");let e=Xr(this.nextdid.did()+this.pin.toString()),r=await this.agent.issuer.sign(await ue.encode(e));this.channel.sendMsg(this.nextdid,{did:this.did,sig:Ic(r,"base64")})}};function __(t,e){for(let r of t)if(r[e])return r[e]}var Lc=t=>t,A_=t=>Object.entries(t),D_=([t,...e])=>{let r=t.map(n=>[n]);for(let n of e){let o=r.splice(0);for(let s of n)for(let i of o)r.push([...i,s])}return r},hw=(t,e)=>{let[r,n]=t.length<e.length?[new Set(t),new Set(e)]:[new Set(e),new Set(t)];for(let o of r)n.has(o)||r.delete(o);return[...r]};var Uc=class extends Vt{constructor(e,r,n){super(),this.claimed=e,this.delegated=r,this.cause=n,this.name=Lc("EscalatedCapability")}describe(){return`Constraint violation: ${this.cause.message}`}},rn=class extends Vt{constructor(e,r){super(),this.name=Lc("InvalidClaim"),this.causes=e,this.context=r}describe(){return[`Can not derive ${this.context} from delegated capabilities:`,...this.causes.map(e=>pw(e.message))].join(`
|
11
|
-
`)}get cause(){if(this.causes.length!==1)return this;{let[e]=this.causes,r=e.name==="InvalidClaim"?e.cause:e;return Object.defineProperties(this,{cause:{value:r}}),r}}};var Wn=class extends Vt{constructor(e,r){super(),this.name=Lc("MalformedCapability"),this.capability=e,this.cause=r}describe(){return[`Encountered malformed '${this.capability.can}' capability: ${T_(this.capability)}`,pw(this.cause.message)].join(`
|
12
|
-
`)}},Ni=class extends Vt{constructor(e){super(),this.name=Lc("UnknownCapability"),this.capability=e}describe(){return`Encountered unknown capability: ${T_(this.capability)}`}};var T_=(t,e)=>JSON.stringify(t,(r,n)=>Se(n)?n.toString():n,e),oR=(t,e=" ")=>`${e}${t.split(`
|
13
|
-
`).join(`
|
14
|
-
${e}`)}`,pw=t=>oR(`- ${t}`);var T=({derives:t=mR,nb:e=sR,...r})=>new mw({derives:t,nb:e,...r}),sR=x.struct({}),iR=(t,e)=>new yw(t,e),aR=(...t)=>new gw(t),cR=({from:t,to:e,derives:r})=>new ww(t,e,r),of=class{match(e){return{error:new Ni(e.capability)}}select(e){return pR(this,e)}derive({derives:e,to:r}){return cR({derives:e,to:r,from:this})}},Rc=class extends of{or(e){return iR(this,e)}and(e){return aR(this,e)}},mw=class extends Rc{constructor(e){super(),this.descriptor=e,this.schema=x.struct({can:x.literal(e.can),with:e.with,nb:e.nb})}create(e){let{descriptor:r,can:n}=this,o=r.nb,s=e.nb||{},i=r.with.read(e.with);if(i.error)throw Object.assign(new Error(`Invalid 'with' - ${i.error.message}`),{cause:i});let a=r.nb.read(s);if(a.error)throw Object.assign(new Error(`Invalid 'nb' - ${a.error.message}`),{cause:a});return C_({can:n,with:i.ok,nb:a.ok})}invoke({with:e,nb:r,...n}){return No({...n,capability:this.create({with:e,nb:r})})}async delegate({nb:e={},with:r,...n}){let{descriptor:o,can:s}=this,i=o.nb,a=o.with.read(r);if(a.error)throw Object.assign(new Error(`Invalid 'with' - ${a.error.message}`),{cause:a});let c=o.nb.partial().read(e);if(c.error)throw Object.assign(new Error(`Invalid 'nb' - ${c.error.message}`),{cause:c});return Lt({capabilities:[C_({can:s,with:a.ok,nb:c.ok})],...n})}get can(){return this.descriptor.can}match(e){let r=fR(this.descriptor,e);return r.error?r:{ok:new bw(e,r.ok,this.descriptor)}}toString(){return JSON.stringify({can:this.descriptor.can})}},C_=({can:t,with:e,nb:r})=>({can:t,with:e,...uR(r)?{}:{nb:r}}),uR=t=>{for(let e in t)return!1;return!0},yw=class extends Rc{constructor(e,r){super(),this.left=e,this.right=r}match(e){let r=this.left.match(e);if(r.error){let n=this.right.match(e);return n.error?n.error.name==="MalformedCapability"?n:r:n}else return r}toString(){return`${this.left.toString()}|${this.right.toString()}`}},gw=class t extends of{constructor(e){super(),this.selectors=e}match(e){let r=[];for(let n of this.selectors){let o=n.match(e);if(o.error)return o;r.push(o.ok)}return{ok:new sf(r)}}select(e){return I_(this,e)}and(e){return new t([...this.selectors,e])}toString(){return`[${this.selectors.map(String).join(", ")}]`}},ww=class extends Rc{constructor(e,r,n){super(),this.from=e,this.to=r,this.derives=n}create(e){return this.to.create(e)}invoke(e){return this.to.invoke(e)}delegate(e){return this.to.delegate(e)}get can(){return this.to.can}match(e){let r=this.to.match(e);return r.error?r:{ok:new xw(r.ok,this.from,this.derives)}}toString(){return this.to.toString()}},bw=class t{constructor(e,r,n){this.source=[e],this.value=r,this.descriptor=n}get can(){return this.value.can}get proofs(){let e=[this.source[0].delegation];return Object.defineProperties(this,{proofs:{value:e}}),e}prune(e){return e.canIssue(this.value,this.source[0].delegation.issuer.did())?null:this}select(e){let r=[],n=[],o=[];for(let s of e){let i=hR(this.descriptor,this.value,s);if(i.ok){let a=this.descriptor.derives(this.value,i.ok);a.error?n.push(new rn([new Uc(this.value,i.ok,a.error)],this)):o.push(new t(s,i.ok,this.descriptor))}else switch(i.error.name){case"UnknownCapability":r.push(i.error.capability);break;case"MalformedCapability":default:n.push(new rn([i.error],this))}}return{matches:o,unknown:r,errors:n}}toString(){let{nb:e}=this.value;return JSON.stringify({can:this.descriptor.can,with:this.value.with,nb:e&&Object.keys(e).length>0?e:void 0})}},xw=class t{constructor(e,r,n){this.selected=e,this.from=r,this.derives=n}get can(){return this.value.can}get source(){return this.selected.source}get proofs(){let e=[];for(let{delegation:r}of this.selected.source)e.push(r);return Object.defineProperties(this,{proofs:{value:e}}),e}get value(){return this.selected.value}prune(e){let r=this.selected.prune(e);return r?new t(r,this.from,this.derives):null}select(e){let{derives:r,selected:n,from:o}=this,{value:s}=n,i=n.select(e),a=o.select(e),c=[],u=[];for(let l of a.matches){let d=r(s,l.value);d.error?u.push(new rn([new Uc(s,l.value,d.error)],this)):c.push(l)}return{unknown:hw(i.unknown,a.unknown),errors:[...u,...i.errors,...a.errors.map(l=>new rn([l],this))],matches:[...i.matches.map(l=>new t(l,o,r)),...c]}}toString(){return this.selected.toString()}},sf=class t{constructor(e){this.matches=e}get selectors(){return this.matches}get source(){let e=[];for(let r of this.matches)e.push(...r.source);return Object.defineProperties(this,{source:{value:e}}),e}prune(e){let r=[];for(let n of this.matches){let o=n.prune(e);o&&r.push(o)}return r.length===0?null:new t(r)}get proofs(){let e=[];for(let{delegation:r}of this.source)e.push(r);return Object.defineProperties(this,{proofs:{value:e}}),e}get value(){let e=[];for(let r of this.matches)e.push(r.value);return Object.defineProperties(this,{value:{value:e}}),e}select(e){return I_(this,e)}toString(){return`[${this.matches.map(e=>e.toString()).join(", ")}]`}},lR=(t,e,r)=>{switch(t){case e:case"*":return e;default:return t.endsWith("/*")&&e.startsWith(t.slice(0,-1))?e:r}},dR=(t,e,r)=>{switch(t){case e:case"ucan:*":return e;default:return r}},fR=(t,e)=>{let{delegation:r}=e,n=e.capability;if(t.can!==n.can)return{error:new Ni(n)};let o=t.with.read(n.with);if(o.error)return{error:new Wn(n,o.error)};let s=t.nb.read(n.nb||{});return s.error?{error:new Wn(n,s.error)}:{ok:new af(t.can,o.ok,s.ok,r)}},hR=(t,e,{capability:r,delegation:n})=>{let o=lR(r.can,e.can,null);if(o==null)return{error:new Ni(r)};let s=dR(r.with,e.with,r.with),i=t.with.read(s);if(i.error)return{error:new Wn(r,i.error)};let a=t.nb.read({...e.nb,...r.nb});return a.error?{error:new Wn(r,a.error)}:{ok:new af(o,i.ok,a.ok,n)}},af=class{constructor(e,r,n,o){this.can=e,this.with=r,this.delegation=o,this.nb=n}},pR=(t,e)=>{let r=[],n=[],o=[];for(let s of e){let i=t.match(s);if(i.error)switch(i.error.name){case"UnknownCapability":r.push(i.error.capability);break;case"MalformedCapability":default:o.push(new rn([i.error],i.error.capability))}else n.push(i.ok)}return{matches:n,errors:o,unknown:r}},I_=(t,e)=>{let r,n=[],o=[];for(let i of t.selectors){let a=i.select(e);r=r?hw(r,a.unknown):a.unknown;for(let c of a.errors)o.push(new rn([c],t));n.push(a.matches)}let s=D_(n).map(i=>new sf(i));return{unknown:r||[],errors:o,matches:s}},mR=(t,e)=>{if(e.with.endsWith("*")){if(!t.with.startsWith(e.with.slice(0,-1)))return x.error(`Resource ${t.with} does not match delegated ${e.with} `)}else if(e.with!==t.with)return x.error(`Resource ${t.with} is not contained by ${e.with}`);let r=e.nb||{},n=t.nb||{},o=A_(r);for(let[s,i]of o)if(n[s]!=i)return x.error(`${String(s)}: ${n[s]} violates ${i}`);return{ok:!0}};function ce(t,e){return t.with===e.with?C({}):ie(`Can not derive ${t.can} with ${t.with} from ${e.with}`)}function _e(t,e,r){return e===void 0||e==="*"?C({}):String(t)===String(e)?C({}):ie(`Constrain violation: ${t} violates imposed ${r} constraint ${e}`)}var kw=(t,e)=>t.with!==e.with?ie(`Expected 'with: "${e.with}"' instead got '${t.with}'`):e.nb.link&&`${e.nb.link}`!=`${t.nb.link}`?ie(`Link ${t.nb.link?`${t.nb.link}`:""} violates imposed ${e.nb.link} constraint.`):C({}),os=(t,e,r)=>_e(String(t),e===void 0?void 0:String(e),r),q=t=>t.error?t:void 0;function B_(t){let[e,...r]=t.split("/");return{namespace:e,segments:r}}function P_(t,e){let r=B_(t),n=B_(e);return r.namespace==="*"&&r.segments.length===0?!0:n.namespace==="*"&&n.segments.length===0||r.namespace!==n.namespace?!1:r.segments[0]==="*"?!0:r.segments.length!==n.segments.length?!1:r.segments.reduce((o,s,i)=>o&&n.segments[i]===s,!0)}var L_=T({can:"store/*",with:V.match({protocol:"did:"}),derives:ce}),Nc=T({can:"store/add",with:V.match({protocol:"did:"}),nb:x.struct({link:pe,size:x.integer(),origin:pe.optional()}),derives:(t,e)=>{let r=kw(t,e);return r.error?r:t.nb.size!==void 0&&e.nb.size!==void 0?t.nb.size>e.nb.size?ie(`Size constraint violation: ${t.nb.size} > ${e.nb.size}`):C({}):C({})}}),Oc=T({can:"store/remove",with:V.match({protocol:"did:"}),nb:x.struct({link:pe}),derives:kw}),$c=T({can:"store/list",with:V.match({protocol:"did:"}),nb:x.struct({cursor:x.string().optional(),size:x.integer().optional(),pre:x.boolean().optional()}),derives:(t,e)=>t.with!==e.with?ie(`Expected 'with: "${e.with}"' instead got '${t.with}'`):C({})}),pG=Nc.or(Oc).or($c);var R_=T({can:"upload/*",with:V.match({protocol:"did:"}),derives:ce}),gR=pe.match({code:Re.code,version:1}),Mc=T({can:"upload/add",with:V.match({protocol:"did:"}),nb:x.struct({root:pe,shards:gR.array().optional()}),derives:(t,e)=>q(ce(t,e))||q(_e(t.nb.root,e.nb.root,"root"))||q(_e(t.nb.shards,e.nb.shards,"shards"))||C({})}),Fc=T({can:"upload/remove",with:V.match({protocol:"did:"}),nb:x.struct({root:pe}),derives:(t,e)=>q(ce(t,e))||q(_e(t.nb.root,e.nb.root,"root"))||C({})}),zc=T({can:"upload/list",with:V.match({protocol:"did:"}),nb:x.struct({cursor:x.string().optional(),size:x.integer().optional(),pre:x.boolean().optional()})}),wG=Mc.or(Fc).or(zc);var ss=T({can:"*",with:V.match({protocol:"did:"}),derives:ce});var vw=x.did({method:"key"}),O_=T({can:"space/*",with:vw,derives:ce}),cf=Nc.or($c).or(Oc).or(Mc).or(zc).or(Fc).derive({to:T({can:"space/info",with:vw}),derives:ce}),SG=T({can:"space/allocate",with:vw,nb:x.struct({size:x.integer()}),derives:(t,e)=>{let r=ce(t,e);return r.ok?t.nb.size<=e.nb.size?C({}):ie(`Claimed size ${t.nb.size} escalates delegated size ${e.nb.size}`):r}});var Hn={};F(Hn,{Account:()=>Sw,AuthorizationRequest:()=>F_,CapabilityRequest:()=>Ew,access:()=>_w,authorize:()=>jc,claim:()=>Aw,confirm:()=>bR,delegate:()=>Dw,session:()=>Wc,top:()=>ss});var Sw=ee.match({method:"mailto"}),Ew=x.struct({can:x.string()}),F_=x.struct({iss:Sw,att:Ew.array()}),_w=T({can:"access/*",with:V.match({protocol:"did:"})}),jc=T({can:"access/authorize",with:ee.match({method:"key"}),nb:F_,derives:(t,e)=>q(ce(t,e))||q(_e(t.nb.iss,e.nb.iss,"iss"))||q(z_(t.nb.att,e.nb.att))||C({})}),bR=T({can:"access/confirm",with:ee,nb:x.struct({iss:Sw,aud:x.did(),att:Ew.array()}),derives:(t,e)=>q(ce(t,e))||q(_e(t.nb.iss,e.nb.iss,"iss"))||q(_e(t.nb.aud,e.nb.aud,"aud"))||q(z_(t.nb.att,e.nb.att))||C({})}),Wc=T({can:"ucan/attest",with:V.match({protocol:"did:"}),nb:x.struct({proof:pe})}),Aw=T({can:"access/claim",with:ee.match({method:"key"}).or(ee.match({method:"mailto"}))}),Dw=T({can:"access/delegate",with:ee.match({method:"key"}),nb:x.struct({delegations:x.dictionary({value:x.Link.match()})}),derives:(t,e)=>q(ce(t,e))||q(xR(t,e))||C({})});function xR(t,e){let r=j_(M_(t),new Set(M_(e)));return r.size>0?ie(`unauthorized nb.delegations ${[...r].join(", ")}`):C({})}var z_=(t,e)=>{let r=new Set(e.map(o=>o.can));if(r.has("*"))return C({});let n=j_(t.map(o=>o.can),r);return n.size>0?ie(`unauthorized nb.att.can ${[...n].join(", ")}`):C({})};function*M_(t){for(let e of Object.values(t.nb.delegations||{}))yield e.toString()}function j_(t,e){let r=new Set;for(let n of t)e.has(n)||r.add(n);return r}var Ow={};F(Ow,{Verifier:()=>Vn,code:()=>Hc,decode:()=>e2,from:()=>Y_,generate:()=>Nw,name:()=>DR,or:()=>IR,signatureAlgorithm:()=>Uw,signatureCode:()=>qc});var kR=globalThis||window||self,qn=kR.crypto;var uf=(t,e)=>{let r=Y.encodingLength(t),n=new Uint8Array(e.byteLength+r);return Y.encodeTo(t,n,0),n.set(e,r),n},lf=(t,e,r=0)=>{let n=r!==0?e.subarray(r):e,[o,s]=Y.decode(n);if(o!==t)throw new Error(`Expected multiformat with 0x${t.toString(16)} tag instead got 0x${o.toString(16)}`);return new Uint8Array(n.buffer,n.byteOffset+s)},IG=Y.encodingLength,BG=Y.encodeTo,PG=Y.decode;var df=t=>{if(t<=127)return new Uint8Array([t]);let e=[];for(;t!==0;)e.push(t&255),t=t>>>8;return e.reverse(),new Uint8Array([128|e.length&255,...e])},vR=(t,e=0)=>{if(!(t[e]&128))return{number:t[e],consumed:1};let r=t[e]&127;if(t.length<r+1)throw new Error(`ASN parsing error: Too few bytes. Expected encoded length's length to be at least ${r}`);let n=0;for(let o=0;o<r;o++)n=n<<8,n=n|t[e+o+1];return{number:n,consumed:r+1}},W_=(t,e,r)=>{let n=Oi(t,e,r);return n.position+n.length},Oi=(t,e,r)=>{let n=t[r];if(n!==e)throw new Error(`ASN parsing error: Expected tag 0x${e.toString(16)} at position ${r}, but got 0x${n.toString(16)}.`);let o=vR(t,r+1);return{position:r+1+o.consumed,length:o.number}},H_=t=>{let e=df(t.byteLength+1),r=new Uint8Array(1+e.byteLength+1+t.byteLength),n=0;return r[n]=3,n+=1,r.set(e,n),n+=e.byteLength,r[n]=0,n+=1,r.set(t,n),r},q_=t=>{let e=df(t.byteLength),r=new Uint8Array(1+e.byteLength+t.byteLength),n=0;return r[n]=4,n+=1,r.set(e,n),n+=e.byteLength,r.set(t,n),r},is=t=>{let e=0;for(let s of t)e+=s.byteLength;let r=df(e),n=new Uint8Array(1+r.byteLength+e),o=0;n[o]=48,o+=1,n.set(r,o),o+=r.byteLength;for(let s of t)n.set(s,o),o+=s.byteLength;return n},SR=(t,e=0)=>{let{position:r,length:n}=Oi(t,48,e);return new Uint8Array(t.buffer,t.byteOffset+r,n)},ff=t=>{let e=t.byteLength===0||t[0]&128?1:0,r=df(t.byteLength+e),n=new Uint8Array(1+r.byteLength+t.byteLength+e),o=0;return n[o]=2,o+=1,n.set(r,o),o+=r.byteLength,e>0&&(n[o]=0,o+=e),n.set(t,o),n},hf=(t,e=0)=>Oi(t,48,e).position,pf=(t,e=0)=>W_(t,48,e),V_=(t,e=0)=>W_(t,2,e),G_=(t,e=0)=>{let{position:r,length:n}=Oi(t,3,e),o=t[r];if(o!==0)throw new Error(`Can not read bitstring, expected length to be multiple of 8, but got ${o} unused bits in last byte.`);return new Uint8Array(t.buffer,t.byteOffset+r+1,n-1)},ur=(t,e=0)=>{let{position:r,length:n}=Oi(t,2,e),o=0;for(;t[r+o]===0;)o++;return new Uint8Array(t.buffer,t.byteOffset+r+o,n-o)},K_=(t,e=0)=>{let{position:r,length:n}=Oi(t,4,e);return new Uint8Array(t.buffer,t.byteOffset+r,n)},Tw=(t,e,r=0)=>{let n=[],o=SR(e,r),s=0;for(let i of t){let a=i(o,s);n.push(a),s=a.byteOffset+a.byteLength-o.byteOffset}return n};var ER=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),mf=t=>is([ER,H_(t)]),Cw=t=>{let e=hf(t,0),r=pf(t,e);return G_(t,r)};var _R=new Uint8Array([2,1,0,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),Bw=t=>{let e=0;return e=hf(t,e),e=V_(t,e),e=pf(t,e),K_(t,e)},Pw=t=>is([_R,q_(t)]);var Lw=({n:t,e})=>is([ff(t),ff(e)]);var WG=new Uint8Array,Q_=(t,e=0)=>{let[r,n,o,s,i,a,c,u,l]=Tw([ur,ur,ur,ur,ur,ur,ur,ur,ur],t,e);return{v:r,n,e:o,d:s,p:i,q:a,dp:c,dq:u,qi:l}};var DR="RSA",Hc=4869,yf=4613,qc=ac,Uw="RS256",xf="RSASSA-PKCS1-v1_5",Rw="SHA-256",TR=2048,CR=128,X_={name:xf,hash:{name:Rw}},Nw=async({size:t=TR,extractable:e=!1}={})=>{let{publicKey:r,privateKey:n}=await qn.subtle.generateKey({name:xf,modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:Rw}},e,["sign","verify"]),o=await qn.subtle.exportKey("spki",r),s=uf(yf,Cw(new Uint8Array(o))),i=new Vn({bytes:s,publicKey:r});if(e){let a=await qn.subtle.exportKey("pkcs8",n),c=uf(Hc,Bw(new Uint8Array(a)));return new wf({privateKey:n,bytes:c,verifier:i})}else return new bf({privateKey:n,verifier:i})},Y_=({id:t,keys:e})=>{if(t.startsWith("did:key:")){let r=t,n=e[r];return n instanceof Uint8Array?e2(n):new bf({privateKey:n,verifier:Vn.parse(r)})}else throw new TypeError(`RSA can not import from ${t} archive, try generic Signer instead`)},IR=t=>Wd({from:Y_},t),e2=t=>{let e=Q_(lf(Hc,t)),r=uf(yf,Lw(e));return new wf({bytes:t,privateKey:qn.subtle.importKey("pkcs8",Pw(lf(Hc,t)),X_,!0,["sign"]),verifier:Vn.decode(r)})},Vn=class t{constructor({publicKey:e,bytes:r}){this.publicKey=e,this.bytes=r}withDID(e){return Dc(this,e)}toDIDKey(){return this.did()}static decode(e){return new this({bytes:e,publicKey:qn.subtle.importKey("spki",mf(lf(yf,e)),X_,!0,["verify"])})}static parse(e){return t.decode(Ue(e))}static or(e){return Fd(this,e)}get code(){return yf}get signatureCode(){return qc}get signatureAlgorithm(){return Uw}did(){return`did:key:${Le.encode(this.bytes)}`}async verify(e,r){return r.code!==qc?!1:qn.subtle.verify({name:xf,hash:{name:Rw}},await this.publicKey,r.raw,e)}};var gf=class{constructor({privateKey:e,verifier:r}){this.verifier=r,this.privateKey=e}get signer(){return this}get code(){return Hc}get signatureCode(){return qc}get signatureAlgorithm(){return Uw}did(){return this.verifier.did()}toDIDKey(){return this.verifier.toDIDKey()}verify(e,r){return this.verifier.verify(e,r)}async sign(e){let r=await qn.subtle.sign({name:xf,saltLength:CR},await this.privateKey,e);return fi(qc,new Uint8Array(r))}},wf=class extends gf{constructor(e){super(e),this.bytes=e.bytes}withDID(e){return Ai(this,e)}toArchive(){let e=this.did();return{id:e,keys:{[e]:this.bytes}}}},bf=class extends gf{constructor(e){super(e),this.privateKey=e.privateKey}withDID(e){return Ai(this,e)}toArchive(){let e=this.did();return{id:e,keys:{[e]:this.privateKey}}}};var t2=jo.or(Vn),r2=Xg(Ow);function $i(t){return t.expiration===void 0||t.expiration<=Math.floor(Date.now()/1e3)}function $w(t){return t.notBefore?t.notBefore>Math.floor(Date.now()/1e3):!1}function n2(t,e){let{checkAudience:r,checkIsExpired:n=!0,checkIsTooEarly:o=!0}=e??{};if(r&&t.audience.did()!==r.did())throw new Error(`Delegation audience ${t.audience.did()} does not match required DID ${r.did()}`);if(n&&$i(t))throw new Error("Delegation expired.");if(o&&$w(t))throw new Error("Delegation is not active yet (too early).")}function o2(t,e){let r=sr.allows(t);if(r[e.with]){let n=Object.keys(r[e.with]);for(let o of n)if(P_(o,e.can))return!0}return!1}var kf={};F(kf,{AccountDID:()=>i2,Provider:()=>s2,add:()=>Mw});var s2=ee.match({method:"web"}),i2=ee.match({method:"mailto"}),Mw=T({can:"provider/add",with:i2,nb:Ne({provider:s2,consumer:ee.match({method:"key"})}),derives:(t,e)=>q(ce(t,e))||q(_e(t.nb.provider,e.nb.provider,"provider"))||q(_e(t.nb.consumer,e.nb.consumer,"consumer"))||C({})});var a2=ee.match({method:"web"}),c2=ee.match({method:"key"}),u2=T({can:"consumer/has",with:a2,nb:Ne({consumer:c2}),derives:(t,e)=>q(ce(t,e))||q(_e(t.nb.consumer,e.nb.consumer,"consumer"))||C({})}),l2=T({can:"consumer/get",with:a2,nb:Ne({consumer:c2}),derives:(t,e)=>q(ce(t,e))||q(_e(t.nb.consumer,e.nb.consumer,"consumer"))||C({})});var LR=ee.match({method:"web"}),UR=ee.match({method:"mailto"}),d2=T({can:"customer/get",with:LR,nb:Ne({customer:UR}),derives:(t,e)=>q(ce(t,e))||q(_e(t.nb.customer,e.nb.customer,"customer"))||C({})});var iK=T({can:"console/log",with:x.did(),nb:x.struct({value:x.unknown()}),derives:ce}),aK=T({can:"console/error",with:x.did(),nb:x.struct({error:x.unknown()}),derives:ce});var Fw=ee,f2=T({can:"rate-limit/add",with:Fw,nb:Ne({subject:x.string(),rate:x.number()}),derives:(t,e)=>q(ce(t,e))||q(_e(t.nb.subject,e.nb.subject,"subject"))||q(_e(t.nb.rate,e.nb.rate,"rate"))||C({})}),h2=T({can:"rate-limit/remove",with:Fw,nb:Ne({id:x.string()}),derives:(t,e)=>q(ce(t,e))||q(_e(t.nb.id,e.nb.id,"id"))||C({})}),p2=T({can:"rate-limit/list",with:Fw,nb:Ne({subject:x.string()}),derives:(t,e)=>q(ce(t,e))||q(_e(t.nb.subject,e.nb.subject,"subject"))||C({})});var $R=ee.match({method:"web"}),m2=T({can:"subscription/get",with:$R,nb:Ne({subscription:x.string()}),derives:(t,e)=>q(ce(t,e))||q(_e(t.nb.subscription,e.nb.subscription,"consumer"))||C({})});var FR=4113,zR=85,vf=x.link({code:zR,version:1,multihash:{code:FR}}),y2=T({can:"filecoin/add",with:x.did(),nb:x.struct({content:x.link(),piece:vf}),derives:(t,e)=>q(ce(t,e))||q(os(t.nb.content,e.nb.content,"nb.content"))||q(os(t.nb.piece,e.nb.piece,"nb.piece"))||C({})}),g2=T({can:"aggregate/add",with:x.did(),nb:x.struct({piece:vf,storefront:x.text(),group:x.text()}),derives:(t,e)=>q(ce(t,e))||q(os(t.nb.piece,e.nb.piece,"nb.piece"))||q(_e(t.nb.storefront,e.nb.storefront,"nb.storefront"))||q(_e(t.nb.group,e.nb.group,"nb.group"))||C({})}),w2=T({can:"deal/add",with:x.did(),nb:x.struct({pieces:x.link(),aggregate:vf,storefront:x.text(),label:x.text().optional()}),derives:(t,e)=>q(ce(t,e))||q(os(t.nb.aggregate,e.nb.aggregate,"nb.aggregate"))||q(os(t.nb.pieces,e.nb.pieces,"nb.pieces"))||q(_e(t.nb.storefront,e.nb.storefront,"nb.storefront"))||q(_e(t.nb.label,e.nb.label,"nb.label"))||C({})}),b2=T({can:"chain-tracker/info",with:x.did(),nb:x.struct({piece:vf}),derives:(t,e)=>q(ce(t,e))||q(os(t.nb.piece,e.nb.piece,"nb.piece"))||C({})});var pK=[ss.can,Mw.can,O_.can,cf.can,R_.can,Mc.can,Fc.can,zc.can,L_.can,Nc.can,Oc.can,$c.can,_w.can,jc.can,Wc.can,d2.can,u2.can,l2.can,m2.can,f2.can,h2.can,p2.can,y2.can,g2.can,w2.can,b2.can];var Gn,Sf=class Sf{constructor(e,r={}){ke(this,Gn,void 0);this.meta=e.meta,this.principal=e.principal,this.spaces=e.spaces,this.delegations=e.delegations,this.currentSpace=e.currentSpace,fe(this,Gn,n=>r.store?r.store.save(n):void 0)}static async create(e={},r={}){let n=new Sf({meta:{name:"agent",type:"device",...e.meta},principal:e.principal??await Ti.generate(),spaces:e.spaces??new Map,delegations:e.delegations??new Map,currentSpace:e.currentSpace},r);return r.store&&await r.store.save(n.export()),n}static fromExport(e,r){let n=new Map;for(let[o,s]of e.delegations)n.set(o,{delegation:vg(s.delegation.map(i=>({cid:se.parse(i.cid),bytes:i.bytes}))),meta:s.meta});return new Sf({meta:e.meta,principal:r2.from(e.principal),currentSpace:e.currentSpace,spaces:e.spaces,delegations:n},r)}export(){let e={meta:this.meta,principal:this.principal.toArchive(),currentSpace:this.currentSpace,spaces:this.spaces,delegations:new Map};for(let[r,n]of this.delegations)e.delegations.set(r,{meta:n.meta,delegation:[...n.delegation.export()].map(o=>({cid:o.cid.toString(),bytes:o.bytes}))});return e}async addSpace(e,r,n){this.spaces.set(e,r),await(n?this.addDelegation(n):$(this,Gn).call(this,this.export()))}async setCurrentSpace(e){this.currentSpace=e,await $(this,Gn).call(this,this.export())}async addDelegation(e,r){this.delegations.set(e.cid.toString(),{delegation:e,meta:r??{}}),await $(this,Gn).call(this,this.export())}async removeDelegation(e){this.delegations.delete(e.toString()),await $(this,Gn).call(this,this.export())}};Gn=new WeakMap;var Kn=Sf,HR=t=>t.can===Hn.session.can,zw=t=>t.capabilities.some(e=>HR(e));function x2(t){let e={};for(let{delegation:r}of t.delegations.values())if(zw(r)){let n=r.capabilities[0];if(n&&!$i(r)){let o=n.nb.proof;o&&(e[o.toString()]=r)}}return e}var Vc=null;typeof WebSocket<"u"?Vc=WebSocket:typeof MozWebSocket<"u"?Vc=MozWebSocket:typeof global<"u"?Vc=global.WebSocket||global.MozWebSocket:typeof window<"u"?Vc=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(Vc=self.WebSocket||self.MozWebSocket);var Ef=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},jw=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},k2=t=>globalThis.DOMException===void 0?new jw(t):new DOMException(t),v2=t=>{let e=t.reason===void 0?k2("This operation was aborted."):t.reason;return e instanceof Error?e:k2(e)};function Ww(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a=new Promise((c,u)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(r===Number.POSITIVE_INFINITY){c(t);return}if(e.signal){let{signal:d}=e;d.aborted&&u(v2(d)),d.addEventListener("abort",()=>{u(v2(d))})}let l=new Ef;i=s.setTimeout.call(void 0,()=>{if(n){try{c(n())}catch(d){u(d)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?c():o instanceof Error?u(o):(l.message=o??`Promise timed out after ${r} milliseconds`,u(l))},r),(async()=>{try{c(await t)}catch(d){u(d)}finally{s.clearTimeout.call(void 0,i)}})()});return a.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},a}var Hw=Symbol("resolveValue");async function qw(t,e={}){let{interval:r=20,timeout:n=Number.POSITIVE_INFINITY,before:o=!0}=e,s,i=new Promise((a,c)=>{let u=async()=>{try{let l=await t();if(typeof l=="object"&&l[Hw])a(l[Hw]);else{if(typeof l!="boolean")throw new TypeError("Expected condition to return a boolean");l===!0?a():s=setTimeout(u,r)}}catch(l){c(l)}};o?u():s=setTimeout(u,r)});if(n===Number.POSITIVE_INFINITY)return i;try{return await Ww(i,typeof n=="number"?{milliseconds:n}:n)}finally{clearTimeout(s)}}qw.resolveWith=t=>({[Hw]:t});var _f=class t extends Error{constructor(e,r){super(e,r),this.name="AbortError",this.message=e,this.code=t.code}};_f.code="ERR_AWAIT_MSG_CANCEL";function Vw(t){let{domain:e,local:r}=E2(t);return`did:mailto:${encodeURIComponent(e)}:${encodeURIComponent(r)}`}function S2(t){let{domain:e,local:r}=E2(t);return`${r}@${e}`}function E2(t){let e=t.split("@");if(e.length<2)throw new TypeError(`expected at least 2 @-delimtied segments, but got ${e.length}`);let r=e.at(-1)??"",n=e.slice(0,-1).join("@");return{domain:r,local:n}}async function VR(t,e,r){let n=await t.invokeAndExecute(jc,{audience:t.connection.id,with:t.issuer.did(),nb:{iss:e.did(),att:[...r]}});if(n?.out.error)throw n.out.error}async function Gw(t,e=t.connection.id.did(),{addProofs:r=!1}={}){let n=await t.invokeAndExecute(Aw,{audience:t.connection.id,with:e});if(n.out.error)throw n.out.error;let o=Object.values(n.out.ok.delegations).flatMap(s=>Vd(s));if(r){for(let s of o)await t.addProof(s);await D2(t,o)}return o}async function GR({access:t,space:e,account:r,provider:n}){let o=await t.invokeAndExecute(kf.add,{audience:t.connection.id,with:r.did(),nb:{provider:n,consumer:e}});if(o.out.error)throw o.out.error}function KR(t){return t.some(e=>zw(e))}async function ZR(t,e,r,n){let o=n?.interval||250;for(;;){if(n?.signal?.aborted)throw n.signal.reason??new Error("operation aborted");let s=await e.invokeAndExecute(Hn.claim,{with:r});if(s.out.error)throw s.out.error;let i=Object.values(s.out.ok.delegations).flatMap(a=>Vd(a));if(t(i))return i;await new Promise(a=>setTimeout(a,o))}}async function JR(t,e={}){return[...await ZR(KR,t,t.issuer.did(),{signal:e?.signal,interval:e?.interval})]}async function QR(t,e,r={}){let n=r.expectAuthorization||JR;await VR(t,{did:()=>Vw(e)},r?.capabilities||[{can:"space/*"},{can:"store/*"},{can:"provider/add"},{can:"upload/*"}]);let s=[...await n(t,r)];r?.dontAddProofs||await Promise.all(s.map(async i=>t.addProof(i)))}async function _2(t,e,r){await QR(t,e,r),await Gw(t,t.issuer.did(),{addProofs:r?.addProofs??!0})}async function A2(t,e,r,n){let o=n?.space||t.currentSpace(),s=o?e.spaces.get(o):void 0,i=n?.provider||(()=>{let u=t.connection.id.did();if(ee.match({method:"web"}).is(u))return u;throw new Error(`unable to determine provider to use to addProviderAndDelegateToAccount using access.connection.id did ${u}. expected a did:web:`)})();if(!o||!s)throw new Error("No space selected");if(s&&s.isRegistered)throw new Error("Space already registered with web3.storage.");let a={did:()=>Vw(S2(r))};await GR({access:t,space:o,account:a,provider:i});let c=await XR(t,o,a);if(c.out.error)throw c.out.error;s.isRegistered=!0,await e.addSpace(o,s)}async function XR(t,e,r){let n=await YR(t.issuer,e,r,void 0,t.proofs([{with:e,can:"*"}]),1/0);return t.invokeAndExecute(Dw,{audience:t.connection.id,with:e,expiration:1/0,nb:{delegations:{[n.cid.toString()]:n.cid}},proofs:[n]})}async function YR(t,e,r,n=[{can:"*",with:e}],o=[],s){return Lt({issuer:t,audience:r,capabilities:n,proofs:o,expiration:s})}var T2="https://up.web3.storage",eN=yt.parse("did:web:web3.storage"),C2=new WeakMap;function tN(t={}){return $o({id:t.principal??eN,codec:Ug,channel:t.channel??Og({url:t.url??new URL(T2),method:"POST",fetch:t.fetch??globalThis.fetch.bind(globalThis)})})}var Ce,Gc,Kw,Df=class Df{constructor(e,r={}){ke(this,Gc);ke(this,Ce,void 0);let n=r.connection?.channel;this.url=r.url??n?.url??new URL(T2),this.connection=r.connection??tN({principal:r.servicePrincipal,url:this.url}),fe(this,Ce,e),C2.set(this,$(this,Ce))}static async create(e,r={}){let n=await Kn.create(e,r);return new Df(n,r)}static from(e,r={}){let n=Kn.fromExport(e,r);return new Df(n,r)}get issuer(){return $(this,Ce).principal}get meta(){return $(this,Ce).meta}get spaces(){return $(this,Ce).spaces}did(){return $(this,Ce).principal.did()}async addProof(e){n2(e,{checkAudience:this.issuer,checkIsExpired:!0}),await $(this,Ce).addDelegation(e,{audience:this.meta}),await this.removeExpiredDelegations()}async removeExpiredDelegations(){for(let[,e]of $(this,Ce).delegations)$i(e.delegation)&&await $(this,Ce).removeDelegation(e.delegation.cid)}proofs(e){let r=[];for(let{delegation:o}of yo(this,Gc,Kw).call(this,e))o.audience.did()===this.issuer.did()&&r.push(o);let n=x2($(this,Ce));for(let o of r){let s=n[o.asCID.toString()];s&&r.push(s)}return r}delegations(e){let r=[];for(let{delegation:n}of this.delegationsWithMeta(e))r.push(n);return r}delegationsWithMeta(e){let r=[];for(let n of yo(this,Gc,Kw).call(this,e)){let{delegation:o}=n;!o.capabilities.some(i=>i.can===Wc.can)&&o.audience.did()!==this.issuer.did()&&r.push(n)}return r}async createSpace(e){let r=await Ti.generate(),n=await ss.delegate({issuer:r,audience:this.issuer,with:r.did(),expiration:1/0}),o={isRegistered:!1};if(e!=null){if(typeof e!="string")throw new TypeError("invalid name");o.name=e}return await $(this,Ce).addSpace(r.did(),o,n),{did:r.did(),meta:o,proof:n}}async importSpaceFromDelegation(e){let r=e.facts[0]?.space??{isRegistered:!1},n=t2.parse(e.capabilities[0].with).did();return $(this,Ce).spaces.set(n,r),await this.addProof(e),{did:n,meta:r,proof:e}}async setCurrentSpace(e){if(!$(this,Ce).spaces.has(e))throw new Error(`Agent has no proofs for ${e}.`);return await $(this,Ce).setCurrentSpace(e),e}currentSpace(){return $(this,Ce).currentSpace}currentSpaceWithMeta(){if(!$(this,Ce).currentSpace)return;let e=this.proofs([{can:"space/info",with:$(this,Ce).currentSpace}]),r=new Set;for(let n of e)for(let o of n.capabilities)r.add(o.can);return{did:$(this,Ce).currentSpace,proofs:e,capabilities:[...r],meta:$(this,Ce).spaces.get($(this,Ce).currentSpace)}}async registerSpace(e,r={}){return await A2(this,$(this,Ce),e,r)}async delegate(e){let r=this.currentSpaceWithMeta();if(!r)throw new Error("no space selected.");let n=e.abilities.map(s=>({with:r.did,can:s}));for(let s of n)if(!this.proofs([s]).length)throw new Error(`cannot delegate capability ${s.can} with ${s.with}`);let o=await Lt({issuer:this.issuer,capabilities:n,proofs:this.proofs(n),facts:[{space:r.meta??{}}],...e});return await $(this,Ce).addDelegation(o,{audience:e.audienceMeta}),await this.removeExpiredDelegations(),o}async invokeAndExecute(e,r){return(await this.invoke(e,r)).execute(this.connection)}execute(...e){return this.connection.execute(...e)}async invoke(e,r){let n=r.with||this.currentSpace();if(!n)throw new Error("No space or resource selected, you need pass a resource.");let o=[...r.proofs||[],...this.proofs([{with:n,can:e.can}])];if(o.length===0&&r.with!==this.did())throw new Error(`no proofs available for resource ${n} and ability ${e.can}`);return No({...r,audience:r.audience||this.connection.id,capability:e.create({with:n,nb:r.nb}),issuer:this.issuer,proofs:[...o]})}peer(e){return new nf({agent:this,channel:e})}async getSpaceInfo(e){let r=e||this.currentSpace();if(!r)throw new Error("No space selected, you need pass a resource.");let n=await this.invokeAndExecute(cf,{with:r});if(n.out.error)throw n.out.error;return n.out.ok}};Ce=new WeakMap,Gc=new WeakSet,Kw=function(e){let r=new Set(e),n=[];for(let[,o]of $(this,Ce).delegations)if(!$i(o.delegation)&&!$w(o.delegation))if(Array.isArray(e)&&e.length>0)for(let s of r)o2(o.delegation,s)&&(r.delete(s),n.push(o));else n.push(o);return n};var Af=Df;async function D2(t,e){let r=C2.get(t);if(!r)throw Object.assign(new Error("cannot determine AgentData for Agent"),{agent:t});if(e.length>0){let n=sr.allows(e[0],...e.slice(1));for(let[o,s]of Object.entries(n))o.startsWith("did:key")&&s["space/*"]&&r.addSpace(o,{isRegistered:!0})}}function ft(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var rN="AccessStore",Zw=1,Kc,Zc,Zn,nn,Jc,Mi,Tf,Cf=class{constructor(e,r={}){ke(this,Mi);ke(this,Kc,void 0);ke(this,Zc,void 0);ke(this,Zn,void 0);ke(this,nn,void 0);ke(this,Jc,void 0);fe(this,Kc,e),fe(this,Zc,r.dbVersion),fe(this,Zn,r.dbStoreName??rN),fe(this,Jc,r.autoOpen??!0)}async open(){if($(this,nn))return;let{resolve:r,reject:n,promise:o}=ft(),s=indexedDB.open($(this,Kc),$(this,Zc));return s.addEventListener("upgradeneeded",()=>{s.result.createObjectStore($(this,Zn))}),s.addEventListener("success",()=>{fe(this,nn,s.result),r()}),s.addEventListener("error",()=>n(s.error)),o}async close(){let e=$(this,nn);if(!e)throw new Error("Store is not open");e.close(),fe(this,nn,void 0)}async save(e){let r=await yo(this,Mi,Tf).call(this);return await Jw(r,"readwrite",$(this,Zn),async s=>{let{resolve:i,reject:a,promise:c}=ft();try{let u=s.put({id:Zw,...e},Zw);u.addEventListener("success",()=>i()),u.addEventListener("error",()=>{a(new Error("failed to query DB",{cause:u.error}))})}catch(u){console.log("error",u)}return c})()}async load(){let e=await yo(this,Mi,Tf).call(this);return await Jw(e,"readonly",$(this,Zn),async n=>{let{resolve:o,reject:s,promise:i}=ft(),a=n.get(Zw);return a.addEventListener("success",()=>{o(a.result)}),a.addEventListener("error",()=>s(new Error("failed to query DB",{cause:a.error}))),i})()}async reset(){let e=await yo(this,Mi,Tf).call(this);Jw(e,"readwrite",$(this,Zn),r=>{let{resolve:n,reject:o,promise:s}=ft(),i=r.clear();return i.addEventListener("success",()=>{n()}),i.addEventListener("error",()=>o(new Error("failed to query DB",{cause:i.error}))),s})}};Kc=new WeakMap,Zc=new WeakMap,Zn=new WeakMap,nn=new WeakMap,Jc=new WeakMap,Mi=new WeakSet,Tf=async function(){if(!$(this,nn)){if(!$(this,Jc))throw new Error("Store is not open");await this.open()}return $(this,nn)};function Jw(t,e,r,n){return async()=>{let o=t.transaction(r,e),{resolve:s,reject:i,promise:a}=ft(),c;o.addEventListener("complete",()=>s(c)),o.addEventListener("abort",()=>i(o.error||new Error("transaction aborted"))),o.addEventListener("error",()=>i(new Error("transaction error",{cause:o.error})));try{c=await n(o.objectStore(r)),o.commit()}catch(u){i(u),o.abort()}return a}}var If=class extends Cf{};var qi={};F(qi,{add:()=>sb,list:()=>DN,remove:()=>TN});var iZ=new TextEncoder,aZ=new TextDecoder;var Qw={};F(Qw,{contentType:()=>I2,encode:()=>sN});var I2="application/cbor",oN=Object.freeze({"content-type":I2}),sN=(t,e)=>{let r=[];for(let o of t.receipts.values()){let s=o.out;s.ok?r.push(s.ok):r.push({...s.error,error:!0})}let n=Bo(r);return{headers:oN,body:n}};var Bf={};F(Bf,{contentType:()=>iN,decode:()=>aN});var iN="application/car",aN=async({body:t})=>{let{roots:e,blocks:r}=gc(t),n=[];for(let{cid:s}of e){let i=Oo.view({root:s,blocks:r});n.push(i)}return await _r.build({invocations:n})};var{contentType:cN}=Bf;var uZ=Ud({decoders:{[cN]:Bf,[Rd]:Mo},encoders:{"*/*;q=0.1":Qw,[Rd]:Fo}});function Fi(t,e){return t.with===e.with?C({}):ie(`Can not derive ${t.can} with ${t.with} from ${e.with}`)}function Pf(t,e,r){return e===void 0||e==="*"?C({}):String(t)===String(e)?C({}):ie(`Constrain violation: ${t} violates imposed ${r} constraint ${e}`)}var Xw=(t,e)=>t.with!==e.with?ie(`Expected 'with: "${e.with}"' instead got '${t.with}'`):e.nb.link&&`${e.nb.link}`!=`${t.nb.link}`?ie(`Link ${t.nb.link?`${t.nb.link}`:""} violates imposed ${e.nb.link} constraint.`):C({});var zi=t=>t.error?t:void 0;var yZ=T({can:"store/*",with:V.match({protocol:"did:"}),derives:Fi}),Lf=T({can:"store/add",with:V.match({protocol:"did:"}),nb:x.struct({link:pe,size:x.integer(),origin:pe.optional()}),derives:(t,e)=>{let r=Xw(t,e);return r.error?r:t.nb.size!==void 0&&e.nb.size!==void 0?t.nb.size>e.nb.size?ie(`Size constraint violation: ${t.nb.size} > ${e.nb.size}`):C({}):C({})}}),Uf=T({can:"store/remove",with:V.match({protocol:"did:"}),nb:x.struct({link:pe}),derives:Xw}),Rf=T({can:"store/list",with:V.match({protocol:"did:"}),nb:x.struct({cursor:x.string().optional(),size:x.integer().optional(),pre:x.boolean().optional()}),derives:(t,e)=>t.with!==e.with?ie(`Expected 'with: "${e.with}"' instead got '${t.with}'`):C({})}),gZ=Lf.or(Uf).or(Rf);var O2=De(R2(),1),fN=new Set(["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed"]),ji=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},hN=(t,e,r)=>{let n=r.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=n,t},pN=t=>fN.has(t),N2=t=>globalThis.DOMException===void 0?new Error(t):new DOMException(t);async function Wi(t,e){return new Promise((r,n)=>{e={onFailedAttempt(){},retries:10,...e};let o=O2.default.operation(e);o.attempt(async s=>{try{r(await t(s))}catch(i){if(!(i instanceof Error)){n(new TypeError(`Non-error was thrown: "${i}". You should only throw errors.`));return}if(i instanceof ji)o.stop(),n(i.originalError);else if(i instanceof TypeError&&!pN(i.message))o.stop(),n(i);else{hN(i,s,e);try{await e.onFailedAttempt(i)}catch(a){n(a);return}o.retry(i)||n(o.mainError())}}}),e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",()=>{o.stop();let s=e.signal.reason===void 0?N2("The operation was aborted."):e.signal.reason;n(s instanceof Error?s:N2(s))},{once:!0})})}var mN=new URL("https://up.web3.storage"),on=Ue("did:web:web3.storage"),Jn=$o({id:on,codec:ir.outbound,channel:Ln.open({url:mN,method:"POST"})});var V2=De(q2(),1),{fetch:_N}=V2.default;function AN(t,e){function r({total:n,loaded:o,lengthComputable:s}){return e({total:n,loaded:o,lengthComputable:s,url:t})}return r}async function sb({issuer:t,with:e,proofs:r,audience:n},o,s={}){let i=new Uint8Array(await o.arrayBuffer()),a=await ir.codec.link(i),c=s.connection??Jn,u=await Wi(async()=>await Lf.invoke({issuer:t,audience:n??on,with:e,nb:{link:a,size:o.size},proofs:r}).execute(c),{onFailedAttempt:console.warn,retries:s.retries??3});if(!u.out.ok)throw new Error(`failed ${Lf.can} invocation`,{cause:u.out.error});if(u.out.ok.status==="done")return a;let l=u.out.ok,d=_N,p=await Wi(async()=>{try{let f=await d(l.url,{method:"PUT",mode:"cors",body:o,headers:l.headers,signal:s.signal,onUploadProgress:s.onUploadProgress?AN(l.url,s.onUploadProgress):void 0,duplex:"half"});if(f.status>=400&&f.status<500)throw new ji(`upload failed: ${f.status}`);return f}catch(f){throw s.signal?.aborted===!0?new ji("upload aborted"):f}},{onFailedAttempt:console.warn,retries:s.retries??3});if(!p.ok)throw new Error(`upload failed: ${p.status}`);return a}async function DN({issuer:t,with:e,proofs:r,audience:n},o={}){let s=o.connection??Jn,i=await Rf.invoke({issuer:t,audience:n??on,with:e,proofs:r,nb:{cursor:o.cursor,size:o.size,pre:o.pre}}).execute(s);if(!i.out.ok)throw new Error(`failed ${Rf.can} invocation`,{cause:i.out.error});return i.out.ok}async function TN({issuer:t,with:e,proofs:r,audience:n},o,s={}){let i=s.connection??Jn,a=await Uf.invoke({issuer:t,audience:n??on,with:e,nb:{link:o},proofs:r}).execute(i);if(!a.out.ok)throw new Error(`failed ${Uf.can} invocation`,{cause:a.out.error})}var Vi={};F(Vi,{add:()=>ib,list:()=>BN,remove:()=>PN});var OZ=T({can:"upload/*",with:V.match({protocol:"did:"}),derives:Fi}),CN=pe.match({code:Re.code,version:1}),$f=T({can:"upload/add",with:V.match({protocol:"did:"}),nb:x.struct({root:pe,shards:CN.array().optional()}),derives:(t,e)=>zi(Fi(t,e))||zi(Pf(t.nb.root,e.nb.root,"root"))||zi(Pf(t.nb.shards,e.nb.shards,"shards"))||C({})}),Mf=T({can:"upload/remove",with:V.match({protocol:"did:"}),nb:x.struct({root:pe}),derives:(t,e)=>zi(Fi(t,e))||zi(Pf(t.nb.root,e.nb.root,"root"))||C({})}),Ff=T({can:"upload/list",with:V.match({protocol:"did:"}),nb:x.struct({cursor:x.string().optional(),size:x.integer().optional(),pre:x.boolean().optional()})}),$Z=$f.or(Mf).or(Ff);async function ib({issuer:t,with:e,proofs:r,audience:n},o,s,i={}){let a=i.connection??Jn,c=await Wi(async()=>await $f.invoke({issuer:t,audience:n??on,with:e,nb:{root:o,shards:s},proofs:r}).execute(a),{onFailedAttempt:console.warn,retries:i.retries??3});if(!c.out.ok)throw new Error(`failed ${$f.can} invocation`,{cause:c.out.error});return c.out.ok}async function BN({issuer:t,with:e,proofs:r,audience:n},o={}){let s=o.connection??Jn,i=await Ff.invoke({issuer:t,audience:n??on,with:e,proofs:r,nb:{cursor:o.cursor,size:o.size,pre:o.pre}}).execute(s);if(!i.out.ok)throw new Error(`failed ${Ff.can} invocation`,{cause:i.out.error});return i.out.ok}async function PN({issuer:t,with:e,proofs:r,audience:n},o,s={}){let i=s.connection??Jn,a=await Mf.invoke({issuer:t,audience:n??on,with:e,nb:{root:o},proofs:r}).execute(i);if(!a.out.ok)throw new Error(`failed ${Mf.can} invocation`,{cause:a.out.error});return a.out.ok}var Xi={};F(Xi,{DEFAULT_DIRECTORY_MODE:()=>tD,DEFAULT_FILE_MODE:()=>eD,NodeType:()=>ae,code:()=>Qi,createAdvancedFile:()=>t5,createComplexFile:()=>n5,createDirectoryShard:()=>Ab,createEmptyFile:()=>YN,createFileChunk:()=>e5,createFileShard:()=>r5,createFlatDirectory:()=>Xf,createRaw:()=>rD,createShardedDirectory:()=>oD,createSimpleFile:()=>nD,createSymlink:()=>iD,cumulativeContentByteLength:()=>Pr,cumulativeDagByteLength:()=>to,decode:()=>uD,decodeMetadata:()=>ds,encode:()=>cD,encodeAdvancedFile:()=>Cb,encodeComplexFile:()=>Ib,encodeDirectory:()=>th,encodeDirectoryMetadata:()=>Lb,encodeFile:()=>sD,encodeFileChunk:()=>Tb,encodeFileShard:()=>o5,encodeHAMTShard:()=>rh,encodeLink:()=>Yf,encodeMetadata:()=>nu,encodeMode:()=>dD,encodeRaw:()=>Db,encodeSimpleFile:()=>eh,encodeSymlink:()=>aD,filesize:()=>c5,matchFile:()=>a5,name:()=>_b});var LN=new TextDecoder;function ab(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 zf(t,e){let r;[r,e]=ab(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 G2(t,e){let r;return[r,e]=ab(t,e),[r&7,r>>3,e]}function UN(t){let e={},r=t.length,n=0;for(;n<r;){let o,s;if([o,s,n]=G2(t,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=zf(t,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=zf(t,n),e.Name=LN.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=ab(t,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>r)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function K2(t){let e=t.length,r=0,n,o=!1,s;for(;r<e;){let a,c;if([a,c,r]=G2(t,r),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,r]=zf(t,r),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let u;[u,r]=zf(t,r),n.push(UN(u))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(r>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return s&&(i.Data=s),i.Links=n||[],i}var J2=new TextEncoder,Z2=2**32,RN=2**31;function NN(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=Xc(e,r,t.Tsize)-1,e[r]=24}if(typeof t.Name=="string"){let n=J2.encode(t.Name);r-=n.length,e.set(n,r),r=Xc(e,r,n.length)-1,e[r]=18}return t.Hash&&(r-=t.Hash.length,e.set(t.Hash,r),r=Xc(e,r,t.Hash.length)-1,e[r]=10),e.length-r}function Q2(t){let e=$N(t),r=new Uint8Array(e),n=e;if(t.Data&&(n-=t.Data.length,r.set(t.Data,n),n=Xc(r,n,t.Data.length)-1,r[n]=10),t.Links)for(let o=t.Links.length-1;o>=0;o--){let s=NN(t.Links[o],r.subarray(0,n));n-=s,n=Xc(r,n,s)-1,r[n]=18}return r}function ON(t){let e=0;if(t.Hash){let r=t.Hash.length;e+=1+r+Gi(r)}if(typeof t.Name=="string"){let r=J2.encode(t.Name).length;e+=1+r+Gi(r)}return typeof t.Tsize=="number"&&(e+=1+Gi(t.Tsize)),e}function $N(t){let e=0;if(t.Data){let r=t.Data.length;e+=1+r+Gi(r)}if(t.Links)for(let r of t.Links){let n=ON(r);e+=1+n+Gi(n)}return e}function Xc(t,e,r){e-=Gi(r);let n=e;for(;r>=RN;)t[e++]=r&127|128,r/=128;for(;r>=128;)t[e++]=r&127|128,r>>>=7;return t[e]=r,n}function Gi(t){return t%2===0&&t++,Math.floor((MN(t)+6)/7)}function MN(t){let e=0;return t>=Z2&&(t=Math.floor(t/Z2),e=32),t>=65536&&(t>>>=16,e+=16),t>=256&&(t>>>=8,e+=8),e+FN[t]}var FN=[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 zN=["Data","Links"],jN=["Hash","Name","Tsize"],cb=new TextEncoder;function Y2(t,e){if(t===e)return 0;let r=t.Name?cb.encode(t.Name):[],n=e.Name?cb.encode(e.Name):[],o=r.length,s=n.length;for(let i=0,a=Math.min(o,s);i<a;++i)if(r[i]!==n[i]){o=r[i],s=n[i];break}return o<s?-1:s<o?1:0}function X2(t,e){return!Object.keys(t).some(r=>!e.includes(r))}function WN(t){if(typeof t.asCID=="object"){let r=se.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=se.asCID(t.Hash);try{r||(typeof t.Hash=="string"?r=se.parse(t.Hash):t.Hash instanceof Uint8Array&&(r=se.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 ub(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=cb.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(WN),e.Links.sort(Y2);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function eA(t){if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form");if(!X2(t,zN))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(!X2(r,jN))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&&Y2(r,t.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}var Qn=112;function tA(t){eA(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),Q2(e)}function Cr(t){let e=K2(t),r={};return e.Data&&(r.Data=e.Data),e.Links&&(r.Links=e.Links.map(n=>{let o={};try{o.Hash=se.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 an=De(JA(),1),Zi=an.default.Reader,Sb=an.default.Writer,Z=an.default.util,nt=an.default.roots.unixfs||(an.default.roots.unixfs={}),Ji=nt.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=Z.newBuffer([]),t.prototype.filesize=Z.Long?Z.Long.fromBits(0,0,!0):0,t.prototype.blocksizes=Z.emptyArray,t.prototype.hashType=Z.Long?Z.Long.fromBits(0,0,!0):0,t.prototype.fanout=Z.Long?Z.Long.fromBits(0,0,!0):0,t.prototype.mode=0,t.prototype.mtime=null,t.encode=function(r,n){if(n||(n=Sb.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")&&nt.UnixTime.encode(r.mtime,n.uint32(66).fork()).ldelim(),n},t.decode=function(r,n){r instanceof Zi||(r=Zi.create(r));for(var o=n===void 0?r.len:r.pos+n,s=new nt.Data;r.pos<o;){var i=r.uint32();switch(i>>>3){case 1:s.Type=r.int32();break;case 2:s.Data=r.bytes();break;case 3:s.filesize=r.uint64();break;case 4:if(s.blocksizes&&s.blocksizes.length||(s.blocksizes=[]),(i&7)===2)for(var a=r.uint32()+r.pos;r.pos<a;)s.blocksizes.push(r.uint64());else s.blocksizes.push(r.uint64());break;case 5:s.hashType=r.uint64();break;case 6:s.fanout=r.uint64();break;case 7:s.mode=r.uint32();break;case 8:s.mtime=nt.UnixTime.decode(r,r.uint32());break;default:r.skipType(i&7);break}}if(!s.hasOwnProperty("Type"))throw Z.ProtocolError("missing required 'Type'",{instance:s});return s},t.fromObject=function(r){if(r instanceof nt.Data)return r;var n=new nt.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"?Z.base64.decode(r.Data,n.Data=Z.newBuffer(Z.base64.length(r.Data)),0):r.Data.length&&(n.Data=r.Data)),r.filesize!=null&&(Z.Long?(n.filesize=Z.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 Z.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)Z.Long?(n.blocksizes[o]=Z.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 Z.LongBits(r.blocksizes[o].low>>>0,r.blocksizes[o].high>>>0).toNumber(!0))}if(r.hashType!=null&&(Z.Long?(n.hashType=Z.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 Z.LongBits(r.hashType.low>>>0,r.hashType.high>>>0).toNumber(!0))),r.fanout!=null&&(Z.Long?(n.fanout=Z.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 Z.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=nt.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=Z.newBuffer(o.Data))),Z.Long){var s=new Z.Long(0,0,!0);o.filesize=n.longs===String?s.toString():n.longs===Number?s.toNumber():s}else o.filesize=n.longs===String?"0":0;if(Z.Long){var s=new Z.Long(0,0,!0);o.hashType=n.longs===String?s.toString():n.longs===Number?s.toNumber():s}else o.hashType=n.longs===String?"0":0;if(Z.Long){var s=new Z.Long(0,0,!0);o.fanout=n.longs===String?s.toString():n.longs===Number?s.toNumber():s}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?nt.Data.DataType[r.Type]:r.Type),r.Data!=null&&r.hasOwnProperty("Data")&&(o.Data=n.bytes===String?Z.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?Z.Long.prototype.toString.call(r.filesize):n.longs===Number?new Z.LongBits(r.filesize.low>>>0,r.filesize.high>>>0).toNumber(!0):r.filesize),r.blocksizes&&r.blocksizes.length){o.blocksizes=[];for(var i=0;i<r.blocksizes.length;++i)typeof r.blocksizes[i]=="number"?o.blocksizes[i]=n.longs===String?String(r.blocksizes[i]):r.blocksizes[i]:o.blocksizes[i]=n.longs===String?Z.Long.prototype.toString.call(r.blocksizes[i]):n.longs===Number?new Z.LongBits(r.blocksizes[i].low>>>0,r.blocksizes[i].high>>>0).toNumber(!0):r.blocksizes[i]}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?Z.Long.prototype.toString.call(r.hashType):n.longs===Number?new Z.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?Z.Long.prototype.toString.call(r.fanout):n.longs===Number?new Z.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=nt.UnixTime.toObject(r.mtime,n)),o},t.prototype.toJSON=function(){return this.constructor.toObject(this,an.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})(),mJ=nt.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=Z.Long?Z.Long.fromBits(0,0,!1):0,t.prototype.FractionalNanoseconds=0,t.encode=function(r,n){return n||(n=Sb.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 Zi||(r=Zi.create(r));for(var o=n===void 0?r.len:r.pos+n,s=new nt.UnixTime;r.pos<o;){var i=r.uint32();switch(i>>>3){case 1:s.Seconds=r.int64();break;case 2:s.FractionalNanoseconds=r.fixed32();break;default:r.skipType(i&7);break}}if(!s.hasOwnProperty("Seconds"))throw Z.ProtocolError("missing required 'Seconds'",{instance:s});return s},t.fromObject=function(r){if(r instanceof nt.UnixTime)return r;var n=new nt.UnixTime;return r.Seconds!=null&&(Z.Long?(n.Seconds=Z.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 Z.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(Z.Long){var s=new Z.Long(0,0,!1);o.Seconds=n.longs===String?s.toString():n.longs===Number?s.toNumber():s}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?Z.Long.prototype.toString.call(r.Seconds):n.longs===Number?new Z.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,an.default.util.toJSONOptions)},t})(),yJ=nt.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=Sb.create()),r.MimeType!=null&&Object.hasOwnProperty.call(r,"MimeType")&&n.uint32(10).string(r.MimeType),n},t.decode=function(r,n){r instanceof Zi||(r=Zi.create(r));for(var o=n===void 0?r.len:r.pos+n,s=new nt.Metadata;r.pos<o;){var i=r.uint32();switch(i>>>3){case 1:s.MimeType=r.string();break;default:r.skipType(i&7);break}}return s},t.fromObject=function(r){if(r instanceof nt.Metadata)return r;var n=new nt.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,an.default.util.toJSONOptions)},t})();var ae=Ji.DataType;var YA=Object.freeze([]),Eb=new Uint8Array(0),Nt=Object.freeze({}),eD=parseInt("0644",8),tD=parseInt("0755",8),Qi=Qn,_b="UnixFS",eo=(t,e)=>(Object(globalThis).debug&&console.log({data:t,links:e}),tA(ub({Data:Ji.encode(t).finish(),Links:e}))),rD=t=>({type:ae.Raw,content:t}),YN=t=>nD(Eb,t),nD=(t,e)=>({type:ae.File,layout:"simple",content:t,metadata:ds(e)}),e5=t=>({type:ae.File,layout:"simple",content:t}),t5=(t,e)=>({type:ae.File,layout:"advanced",parts:t,metadata:ds(e)}),r5=t=>({type:ae.File,layout:"advanced",parts:t}),n5=(t,e,r)=>({type:ae.File,layout:"complex",content:t,parts:e,metadata:ds(r)}),Xf=(t,e)=>({type:ae.Directory,metadata:ds(e),entries:t}),oD=(t,e,r,n,o=Nt)=>({type:ae.HAMTShard,bitfield:e,fanout:Bb(r),hashType:Pb(n),entries:t,metadata:ds(o)}),Ab=(t,e,r,n)=>({type:ae.HAMTShard,bitfield:e,fanout:Bb(r),hashType:Pb(n),entries:t}),Db=t=>eo({Type:ae.Raw,Data:t.byteLength>0?t:void 0,filesize:t.byteLength,blocksizes:YA},[]),sD=(t,e=!1)=>{let r=e?Nt:Object(t).metadata;switch(t.layout){case"simple":return eh(t.content,r);case"advanced":return Cb(t.parts,r);case"complex":return Ib(t.content,t.parts,r);default:throw new TypeError(`File with unknown layout "${Object(t).layout}" was passed`)}},Tb=t=>eh(t,Nt),o5=t=>eo({Type:ae.File,blocksizes:t.map(ru),filesize:Pr(t)},t.map(Yf)),Cb=(t,e=Nt)=>eo({Type:ae.File,blocksizes:t.map(ru),filesize:Pr(t),...nu(e)},t.map(Yf)),Yf=t=>({Name:"",Tsize:t.dagByteLength,Hash:t.cid}),eh=(t,e=Nt)=>eo({Type:ae.File,Data:t.byteLength>0?t:void 0,filesize:t.byteLength,blocksizes:[],...nu(e)},[]),Ib=(t,e,r=Nt)=>eo({Type:ae.File,Data:t,filesize:t.byteLength+Pr(e),blocksizes:e.map(ru)},e.map(Yf)),th=t=>eo({Type:t.type,...Lb(t.metadata||Nt)},t.entries.map(lD)),rh=({bitfield:t,fanout:e,hashType:r,entries:n,metadata:o=Nt})=>eo({Type:ae.HAMTShard,Data:t.byteLength>0?t:void 0,fanout:Bb(e),hashType:Pb(r),...Lb(o)},n.map(lD)),Bb=t=>{if(Math.log2(t)%1===0)return t;throw new TypeError(`Expected hamt size to be a power of two instead got ${t}`)},Pb=t=>{if(Number.isInteger(t))return t;throw new TypeError(`Expected an integer value instead got ${t}`)};var iD=(t,e=Nt)=>({type:ae.Symlink,content:t,metadata:ds(e)}),aD=(t,e=!1)=>{let r=e?Nt:Object(t).metadata;return eo({Type:ae.Symlink,Data:t.content,...nu(r||Nt)},[])},cD=(t,e=!0)=>{switch(t.type){case ae.Raw:return Db(t.content);case ae.File:return sD(t);case ae.Directory:return th(t);case ae.HAMTShard:return rh(t);case ae.Symlink:return aD(t);default:throw new Error(`Unknown node type ${Object(t).type}`)}},uD=t=>{let e=Cr(t),r=Ji.decode(e.Data),{Type:n,Data:o,mtime:s,mode:i,blocksizes:a,...c}=Ji.toObject(r,{defaults:!1,arrays:!0,longs:Number,objects:!1}),u={...i&&{mode:i},...s5(s)},l=e.Links;switch(r.Type){case ae.Raw:return rD(o);case ae.File:return l.length===0?new Zf(o,u):o.byteLength===0?new Jf(QA(c.blocksizes,l),u):new Qf(o,QA(c.blocksizes,l),u);case ae.Directory:return Xf(XA(l),u);case ae.HAMTShard:return oD(XA(l),o||Eb,c.fanout,c.hashType,u);case ae.Symlink:return iD(o,u);default:throw new TypeError(`Unsupported node type ${r.Type}`)}},s5=t=>t==null?void 0:{mtime:{secs:t.Seconds,nsecs:t.FractionalNanoseconds||0}};var QA=(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},XA=t=>t.map(e=>({cid:e.Hash,name:e.Name||"",dagByteLength:e.Tsize||0})),Pr=t=>t.reduce((e,r)=>e+r.contentByteLength,0),to=(t,e)=>e.reduce((r,n)=>r+n.dagByteLength,t.byteLength),ru=t=>t.contentByteLength,lD=({name:t,dagByteLength:e,cid:r})=>({Name:t,Tsize:e,Hash:r}),Lb=t=>nu(t,tD),nu=({mode:t,mtime:e},r=eD)=>({mode:t!=null?dD(t,r):void 0,mtime:e!=null?i5(e):void 0}),ds=t=>t==null?Nt:{...t.mode==null?void 0:{mode:fD(t.mode)},...t.mtime==null?void 0:{mtime:t.mtime}},i5=t=>t==null?void 0:t.nsecs!==0?{Seconds:t.secs,FractionalNanoseconds:t.nsecs}:{Seconds:t.secs},dD=(t,e)=>{let r=t==null?void 0:fD(t);return r===e||r==null?void 0:r},fD=t=>t&4095|t&4294963200,a5=({content:t=Eb,parts:e=YA,metadata:r=Nt,...n})=>e.length===0?new Zf(t,r):t.byteLength===0?new Jf(e,r):new Qf(t,e,r),Zf=class{constructor(e,r){this.content=e,this.metadata=r,this.layout="simple",this.type=ae.File}get filesize(){return this.content.byteLength}encode(){return eh(this.content,this.metadata)}},Jf=class{constructor(e,r){this.parts=e,this.metadata=r}get layout(){return"advanced"}get type(){return ae.File}get fileSize(){return Pr(this.parts)}get blockSizes(){return this.parts.map(ru)}encode(){return Cb(this.parts,this.metadata)}},Qf=class{constructor(e,r,n){this.content=e,this.parts=r,this.metadata=n}get layout(){return"complex"}get type(){return ae.File}get fileSize(){return this.content.byteLength+Pr(this.parts)}get blockSizes(){return this.parts.map(ru)}encode(){return Ib(this.content,this.parts,this.metadata)}},c5=t=>{switch(t.type){case ae.Raw:case ae.Symlink:return t.content.byteLength;case ae.File:switch(t.layout){case"simple":return t.content.byteLength;case"advanced":return Pr(t.parts);case"complex":return t.content.byteLength+Pr(t.parts)}default:return 0}};var u5=function*(t){let e=yield*t;yield*oh(e)};function*$b(){return yield ah}var ea=function*(){yield ch};var nh=function*(t){let e=yield*$b();if(d5(t)){let r=!1,n;if(t.then(o=>{r=!1,n=o,ro(e)},o=>{r=!0,n=o,ro(e)}),yield*ea(),r)throw n;return n}else return m5(l5(e)),yield*ea(),t};function*l5(t){ro(t)}var d5=t=>t!=null&&typeof t.then=="function",oh=function*(t){yield t},sh=function*(t){let e=[];for(let r of Object.entries(t)){let[n,o]=r;o!==iu&&e.push(yield*ra(h5(o,n)))}yield*Fb(e)},ih=t=>t.length>0?f5(t.map(u5)):iu;function*f5(t){let e=[];for(let r of t)e.push(yield*ra(r));yield*Fb(e)}var h5=(t,e)=>t===iu?iu:t instanceof ou?new ou([...t.tags,e],t.source):new ou([e],t),ou=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 ch:case ah:return e;default:{let r=e,{value:n}=r;for(let o of this.tags)n=p5(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"}},au=()=>iu;var p5=(t,e)=>({type:t,[t]:e});var ah=Symbol("current"),ch=Symbol("suspend");var cn=class t{static of(e){return e.group||Yi}static enqueue(e,r){e.group=r,r.stack.active.push(e)}constructor(e,r=[],n=new Set,o=new ta(r,n)){this.driver=e,this.parent=t.of(e),this.stack=o,this.id=++yD}},Ub=class{constructor(){this.status=su,this.stack=new ta,this.id=0}},ta=class{constructor(e=[],r=new Set){this.active=e,this.idle=r}static size({active:e,idle:r}){return e.length+r.size}},m5=t=>ro(t[Symbol.iterator]()),ro=t=>{let e=cn.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(Yi.status===su)for(Yi.status=gD;;)try{for(let r of Mb(Yi));Yi.status=su;break}catch{Yi.stack.active.shift()}},y5=t=>ro(t),Mb=function*(t){let{active:e}=t.stack,r=e[0];for(t.stack.idle.delete(r);r;){let n=wD;e:for(;!n.done&&r===e[0];){let o=n.value;switch(o){case ch:t.stack.idle.add(r);break e;case ah:n=r.next(r);break;default:n=r.next(yield o);break}}e.shift(),r=e[0],t.stack.idle.delete(r)}};var ra=(t,e)=>new Ob(t,e),g5=(t,e)=>pD(t,{ok:!0,value:e});var Rb=(t,e)=>pD(t,{ok:!1,error:e});function*pD(t,e){try{let r=t,n=e.ok?r.return(e.value):r.throw(e.error);if(!n.done)if(n.value===ch){let{idle:o}=cn.of(r).stack;o.add(r)}else ro(r)}catch{}}function*Fb(t){if(t.length===0)return;let e=yield*$b(),r=new cn(e),n=null;for(let o of t){let{result:s}=o;if(s){!s.ok&&!n&&(n=s);continue}w5(o,r)}try{if(n)throw n.error;for(;yield*Mb(r),ta.size(r.stack)>0;)yield*ea()}catch(o){for(let s of r.stack.active)yield*Rb(s,o);for(let s of r.stack.idle)yield*Rb(s,o),ro(s);throw o}}var w5=(t,e)=>{let r=cn.of(t);if(r!==e){let{active:n,idle:o}=r.stack,s=e.stack;if(t.group=e,o.has(t))o.delete(t),s.idle.add(t);else{let i=n.indexOf(t);i>=0&&(n.splice(i,1),s.active.push(t))}}};function*zb(t){t.status===su&&(yield*t),t.result||(yield*Fb([t]));let e=t.result;if(e.ok)return e.value;throw e.error}var Nb=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}},Ob=class extends Nb{constructor(e,r=b5,n={},o=wD){super(n),this.id=++yD,this.name=r.name||"",this.task=e,this.state=o,this.status=su,this.result,this.handler=n,this.controller}*resume(){y5(this)}join(){return zb(this)}abort(e){return Rb(this,e)}exit(e){return g5(this,e)}get[Symbol.toStringTag](){return"Fork"}*[Symbol.iterator](){return this.activate()}activate(){return this.controller=this.task[Symbol.iterator](),this.status=gD,ro(this),this}panic(e){this.result={ok:!1,error:e},this.status=hD;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=hD;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)}}},mD=function*(t,e){let r=yield*$b(),n=new cn(r);for(cn.enqueue(t[Symbol.iterator](),n);;){for(let o of Mb(n))cn.enqueue(e(o)[Symbol.iterator](),n);if(ta.size(n.stack)>0)yield*ea();else break}},yD=0,su="idle",gD="active",hD="finished",wD={done:!1,value:ah},b5={},iu=function*(){}(),Yi=new Ub;function jb(){}Object.defineProperties(jb,{prototype:{value:new Proxy(Object.prototype,{get(t,e,r){return typeof e=="symbol"?Reflect.get(t,e,r):r.get(e)}})}});var Wb=()=>new cu;var xD=(t,e=0,r=t.byteLength)=>{let n=[],o=e<0?t.byteLength-e:e,s=r<0?t.byteLength-r:r;if(o===0&&s>=t.byteLength)return t;if(o>s||o>t.byteLength||s<=0)return Wb();let i=0,a=0;for(let c of t.segments){let u=a+c.byteLength;if(i===0){if(s<=u){let l=c.subarray(o-a,s-a);n.push(l),i=l.byteLength;break}else if(o<u){let l=o===a?c:c.subarray(o-a);n.push(l),i=l.byteLength}}else if(s<=u){let l=s===u?c:c.subarray(0,s-a);n.push(l),i+=l.byteLength;break}else n.push(c),i+=c.byteLength;a=u}return new cu(n,t.byteOffset+o,i)},x5=(t,e)=>e.byteLength>0?(t.segments.push(e),new cu(t.segments,t.byteOffset,t.byteLength+e.byteLength)):t,k5=(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}}},v5=(t,e,r)=>{let n=r;for(let o of t.segments)e.set(o,n),n+=o.byteLength;return e};function*S5(t){for(let e of t.segments)yield*e}var cu=class extends jb{constructor(e=[],r=0,n=0){super(),this.segments=e,this.byteLength=n,this.length=n,this.byteOffset=r}[Symbol.iterator](){return S5(this)}slice(e,r){return xD(this,e,r)}subarray(e,r){return xD(this,e,r)}push(e){return x5(this,e)}get(e){return k5(this,e)}copyTo(e,r){return v5(this,e,r)}};var uu=t=>{throw new Error(t)},kD=(t,e,...r)=>uu(String.raw(t,JSON.stringify(e),...r)),vD=new Uint8Array(0),SD=[];var ED=t=>({config:t,buffer:Wb()}),_D=(t,e)=>e.byteLength>0?DD(t.config,t.buffer.push(e),!1):{...t,chunks:SD},AD=t=>DD(t.config,t.buffer,!0),DD=(t,e,r)=>{let n=t.chunker,o=[],s=0;for(let i of n.cut(n.context,e,r))if(i>0){let a=e.subarray(s,s+i);o.push(a),s+=i}return{config:t,chunks:o,buffer:e.subarray(s)}};var TD=()=>({mutable:!0,needs:{},nodes:{},links:{},linked:Vb});var Gb=(t,e)=>{let r=na(e,{});for(let n of t){let{ready:o,has:s,wants:i}=ID(n.children,r.links);i.length===0?r=na(r,{links:qb(void 0,s),linked:[{id:n.id,links:o}]}):r=na(r,{needs:qb(n.id,i),nodes:{[n.id]:{children:n.children,count:i.length}}})}return r},CD=(t,e,r)=>{let n=r.needs[t],o=r.nodes[n];if(o!=null)if(o.count===1){let{ready:s,has:i}=ID(o.children,{...r.links,[t]:e});return na(r,{needs:{[t]:void 0},links:qb(void 0,i),nodes:{[n]:void 0},linked:[{id:n,links:s}]})}else return na(r,{needs:{[t]:void 0},links:{[t]:e},nodes:{[n]:{...o,count:o.count-1}}});else return na(r,{links:{[t]:e}})},na=(t,{needs:e,nodes:r,links:n,linked:o})=>{let s=t.mutable?t:{...t},i=t.mutable?D5:void 0;return e&&(s.needs=Hb(t.needs,e,i)),r&&(s.nodes=Hb(t.nodes,r,i)),n&&(s.links=Hb(t.links,n,i)),s.linked=o?A5(t.linked||Vb,o,Vb):t.linked||[],s},qb=(t,e)=>{let r={};for(let n of e)r[n]=t;return r},Hb=(t,e,r=t)=>{let n=t===r?{...t}:t;for(let o of Object.entries(e)){let[s,i]=o;i==null?delete n[s]:n[s]=i}return n};var A5=(t,e,r=t)=>{if(t===r)return[...t,...e];for(let n of e)t.push(n);return t},ID=(t,e)=>{let r=[],n=[],o=[];for(let s of t){let i=e[s];i?(r.push(s),o.push(i)):n.push(s)}return{has:r,wants:n,ready:o}},Vb=Object.freeze([]),D5=Object.freeze({});var BD=(t,e)=>{switch(t.type){case"write":return C5(e,t.bytes);case"link":return I5(e,t.link);case"block":return{state:e,effect:au()};case"close":return B5(e);case"end":return{state:e,effect:au()};default:return kD`File Writer got unknown message ${t}`}},PD=(t,e,r)=>({status:"open",metadata:e,config:r,writer:t,chunker:ED({chunker:r.chunker}),layout:r.fileLayout.open(),nodeQueue:TD()}),C5=(t,e)=>{if(t.status==="open"){let{chunks:r,...n}=_D(t.chunker,e),{nodes:o,leaves:s,layout:i}=t.config.fileLayout.write(t.layout,r),{linked:a,...c}=Gb(o,t.nodeQueue),u=[...LD(s,t.config),...Kb(a,t.config)];return{state:{...t,chunker:n,layout:i,nodeQueue:c},effect:sh({link:ih(u)})}}else return uu("Unable to perform write on closed file")},I5=(t,{id:e,link:r,block:n})=>{let{linked:o,...s}=CD(e,r,t.nodeQueue),i=Kb(o,t.config),a=t.status==="closed"&&e===t.rootID?{...t,status:"linked",link:r,nodeQueue:s}:{...t,nodeQueue:s},c=t.status==="closed"&&e===t.rootID&&t.end?t.end.resume():au();return{state:a,effect:sh({link:ih(i),block:U5(t.writer,n),end:c})}},B5=t=>{if(t.status==="open"){let{chunks:e}=AD(t.chunker),{layout:r,...n}=t.config.fileLayout.write(t.layout,e),{root:o,...s}=t.config.fileLayout.close(r,t.metadata),[i,a]=N5(o)?[[...n.nodes,...s.nodes],[...n.leaves,...s.leaves,o]]:[[...n.nodes,...s.nodes,o],[...n.leaves,...s.leaves]],{linked:c,...u}=Gb(i,t.nodeQueue),l=[...LD(a,t.config),...Kb(c,t.config)],d=ra(ea());return{state:{...t,chunker:null,layout:null,rootID:o.id,status:"closed",end:d,nodeQueue:u},effect:sh({link:ih(l),end:zb(d)})}}else return{state:t,effect:au()}},LD=(t,e)=>t.map(r=>P5(e,r,e.fileChunkEncoder)),P5=function*({hasher:t,linker:e},{id:r,content:n},o){let s=o.encode(n?R5(n):vD),i=yield*nh(t.digest(s)),a=e.createLink(o.code,i),c={cid:a,bytes:s},u={cid:a,contentByteLength:n?n.byteLength:0,dagByteLength:s.byteLength};return{id:r,block:c,link:u}},Kb=(t,e)=>t.map(r=>L5(e,r)),L5=function*(t,{id:e,links:r},n){let o=t.fileEncoder.encode({type:ae.File,layout:"advanced",parts:r,metadata:n}),s=yield*nh(Promise.resolve(t.hasher.digest(o))),i=t.linker.createLink(t.fileEncoder.code,s),a={bytes:o,cid:i},c={cid:i,contentByteLength:Pr(r),dagByteLength:to(o,r)};return{id:e,block:a,link:c}},U5=function*(t,e){(t.desiredSize||0)<=0&&(yield*nh(t.ready)),t.write(e)},R5=t=>t instanceof Uint8Array?t:t.copyTo(new Uint8Array(t.byteLength),0),N5=t=>t.children==null;var Zb={};F(Zb,{context:()=>$5,cut:()=>RD,name:()=>UD,type:()=>M5,withMaxChunkSize:()=>lu});var UD="fixed",$5={maxChunkSize:262144},M5="Stateless",lu=t=>({type:"Stateless",context:{maxChunkSize:t},name:UD,cut:RD}),RD=({maxChunkSize:t},{byteLength:e},r)=>{let n=e/t|0,o=new Array(n).fill(t),s=r?e-n*t:0;return s>0&&o.push(s),o};var du=class{constructor(e,r,n){this.id=e,this.children=r,this.metadata=n}},oa=t=>({open:()=>z5({width:t}),write:j5,close:W5}),F5={width:174},z5=({width:t}=F5)=>({width:t,head:null,leafIndex:[],nodeIndex:[],lastID:0}),j5=(t,e)=>{if(e.length===0)return{layout:t,nodes:xt,leaves:xt};{let{lastID:r}=t,[n,o]=t.head?[null,(e.unshift(t.head),e)]:e.length===1&&t.leafIndex.length===0?[e[0],xt]:[null,e];if(o.length===0)return{layout:{...t,head:n},nodes:xt,leaves:xt};{let s=[...t.leafIndex],i=[];for(let a of o){let c={id:++r,content:a};i.push(c),s.push(c.id)}return s.length>=t.width?OD({...t,leafIndex:s,head:n,lastID:r},i):{layout:{...t,head:n,leafIndex:s,lastID:r},leaves:i,nodes:xt}}}},OD=(t,e=xt,r=[],n=!1)=>{let{lastID:o}=t,s=t.nodeIndex.map(u=>[...u]),i=[...t.leafIndex],{width:a}=t;for(;i.length>=a||i.length>0&&n;){ND(s,1);let u=new du(++o,i.splice(0,a));s[0].push(u.id),r.push(u)}let c=0;for(;c<s.length;){let u=s[c];for(c++;u.length>=a||u.length>0&&n&&c<s.length;){let l=new du(++o,u.splice(0,a));ND(s,c+1),s[c].push(l.id),r.push(l)}}return{layout:{...t,lastID:o,leafIndex:i,nodeIndex:s},leaves:e,nodes:r}},W5=(t,e)=>{let r=t;if(t.head)return{root:{id:1,content:t.head,metadata:e},leaves:xt,nodes:xt};if(t.leafIndex.length===0)return{root:{id:1,metadata:e},leaves:xt,nodes:xt};{let{nodes:n,layout:o}=OD(r,xt,[],!0),{nodeIndex:s}=o,i=s.length-1,a=s[i];if(a.length===1){let c=n[n.length-1];return n.length=n.length-1,{root:c,nodes:n,leaves:xt}}else return{root:new du(o.lastID+1,a,e),nodes:n,leaves:xt}}},ND=(t,e)=>{for(;t.length<e;)t.push([]);return t},xt=[];var un=()=>({chunker:Zb,fileChunkEncoder:Jb,smallFileEncoder:Jb,fileEncoder:Xi,fileLayout:oa(174),hasher:ue,linker:{createLink:se.createV1}}),Lr=t=>({...un(),...t}),Jb={code:Qi,name:_b,encode:Tb};var fs=({writer:t,metadata:e={},settings:r=un()})=>new Qb(PD(t,e,Lr(r))),$D=async(t,e)=>(await FD(t,oh({type:"write",bytes:e})),t),MD=async(t,{releaseLock:e=!1,closeWriter:r=!1}={})=>{await FD(t,oh({type:"close"}));let{state:n}=t;if(n.status==="linked")return r?await t.state.writer.close():e&&t.state.writer.releaseLock(),n.link;uu(`Expected writer to be in 'linked' state after close, but it is in "${n.status}" instead`)},FD=(t,e)=>ra(mD(e,r=>{let{state:n,effect:o}=BD(r,t.state);return t.state=n,o})),Qb=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.config}write(e){return $D(this,e)}close(e){return MD(this,e)}};var q5=un,fu=({writer:t,settings:e=q5(),metadata:r={}})=>new uh({writer:t,metadata:r,settings:e,entries:new Map,closed:!1}),hu=(t,e,r,{overwrite:n=!1}={})=>{let o=Yb(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},pu=(t,e)=>(Yb(t.state).entries.delete(e),t),Yb=t=>{if(t.closed)throw new Error("Can not change written directory, but you can .fork() and make changes to it");return t},zD=async(t,{closeWriter:e=!1,releaseLock:r=!1}={})=>{let{writer:n,settings:o,metadata:s}=Yb(t.state);t.state.closed=!0;let i=[...jD(t)],a=Xf(i,s),c=th(a),u=await o.hasher.digest(c),l=o.linker.createLink(Qi,u);return(n.desiredSize||0)<=0&&await n.ready,n.write({cid:l,bytes:c}),e?await n.close():r&&n.releaseLock(),{cid:l,dagByteLength:to(c,i)}},jD=function*({state:t}){for(let[e,{dagByteLength:r,cid:n}]of t.entries)yield{name:e,dagByteLength:r,cid:n}},WD=({state:t},{writer:e=t.writer,metadata:r=t.metadata,settings:n=t.settings}={})=>new uh({writer:e,metadata:r,settings:n,entries:new Map(t.entries.entries()),closed:!1}),uh=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.settings}links(){return jD(this)}set(e,r,n){return hu(this,e,r,n)}remove(e){return pu(this,e)}fork(e){return WD(this,e)}close(e){return zD(this,e)}entries(){return this.state.entries.entries()}has(e){return this.state.entries.has(e)}get size(){return this.state.entries.size}};var fh={};F(fh,{API:()=>lh,and:()=>Y5,bitCount:()=>dh,empty:()=>HD,from:()=>G5,fromBytes:()=>rO,get:()=>X5,or:()=>eO,popcount:()=>ex,set:()=>qD,size:()=>K5,toBytes:()=>tO,unset:()=>Q5});var lh={};var HD=(t=32)=>{if(t!==32)throw new Error(`Uint32 BitField does not support size: ${t}`);return 0},G5=(t,e)=>{let r=HD(e);for(let n of t)r=qD(r,n);return r},K5=t=>32,Z5=(t,e)=>t>>>e&31,J5=(t,e)=>1<<Z5(t,e),ex=(t,e=31)=>dh(t&J5(e,0)-1),qD=(t,e)=>t|1<<e,Q5=(t,e)=>t&(255^1<<e),X5=(t,e)=>(t>>e&1)!==0,dh=t=>{let e=t-(t>>1&1431655765),r=(e&858993459)+(e>>2&858993459);return(r+(r>>4)&252645135)*16843009>>24},Y5=(t,e)=>t&e,eO=(t,e)=>t|e,tO=t=>Uint8Array.of(t>>24&255,t>>16&255,t>>8&255,t&255),rO=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 KD=De(tx(),1),nO=new TextEncoder,oO=KD.default.x64.hash126,ZD=({bitWidth:t=5,hash:e=oO})=>{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:(i,a)=>i>>>a*t&n,from:i=>e(nO.encode(i)),size:Math.ceil(4*8/t)}};var sa=class{constructor(e,r,n,o,s){this.edit=e,this.config=s,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 gu(this.config)}lookup(e,r,n,o){return QD(this,e,r,n,o)}associate(e,r,n,o,s,i){return ox(this,e,r,n,o,s,i)}dissociate(e,r,n,o,s){return XD(this,e,r,n,o,s)}fork(e=null){return wu(this,e)}entries(){return YD(this)}keys(){return eT(this)}values(){return tT(this)}},ph=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 sO(this,n,o)}associate(e,r,n,o,s,i){return iO(this,e,n,o,s,i)}dissociate(e,r,n,o,s){return aO(this,e,n,o,s)}fork(e=null){return cO(this,e)}entries(){return YD(this)}keys(){return eT(this)}values(){return tT(this)}},sO=(t,e,r)=>{let{children:n,count:o}=t,s=rx(n,o,e);return n[s]===e?n[s+1]:r},iO=(t,e,r,n,o,s)=>{let{children:i,count:a}=t,c=rx(i,a,n);if(i[c]!==n){let u=t.fork(e);return s.value=!0,u.count+=1,u.children.splice(c,r,o),u}else if(i[c+1]!==o){let u=t.fork(e);return u.children[c+1]=o,u}else return t},aO=(t,e,r,n,o)=>{let{children:s,count:i,config:a}=t,c=rx(s,i,n);if(s[c]!==n)return t;if(o.value=!0,i===2){let u=c===0?2:0;return ox(gu(a),e,0,r,s[u],s[u+1],o)}else{let u=t.fork(e);return u.children.splice(c,2),u.count-=1,u}},cO=(t,e=null)=>sT(t.edit,e)?t:new ph(e,t.count,t.children.slice(),t.config),rx=(t,e,r)=>{let n=0;for(;n<e&&t[n]>r;)n+=2;return n};var gu=(t,e=null)=>new sa(e,t.BitField.empty(Math.pow(2,t.bitWidth)),t.BitField.empty(Math.pow(2,t.bitWidth)),[],t),mh=(t,e,r)=>QD(t,0,t.config.Path.from(e),e,r),QD=(t,e,r,n,o)=>{let{datamap:s,nodemap:i,config:a}=t,{Path:c,BitField:u}=a,l=c.at(r,e);if(u.get(s,l)){let d=u.popcount(s,l);return bu(t,d)===n?yu(t,d):o}else return u.get(i,l)?ku(t,l).lookup(e+1,r,n,o):o},nx=(t,e,r,n,o)=>ox(t,e,0,t.config.Path.from(r),r,n,o),ox=(t,e,r,n,o,s,i)=>{let{datamap:a,nodemap:c,config:u}=t,{Path:l,BitField:d}=u,p=l.at(n,r);if(d.get(a,p)){let f=d.popcount(a,p),h=bu(t,f);if(o===h)return yu(t,f)===s?t:uO(t,e,f,s);{let m=nT(u,e,r+1,l.from(h),h,yu(t,f),n,o,s);return i.value=!0,dO(t,e,p,m)}}else if(d.get(c,p)){let f=ku(t,p),h=f.associate(e,r+1,n,o,s,i);return f===h?t:rT(t,e,p,h)}else{let f=d.popcount(a,p);i.value=!0;let h=t.fork(e);return h.datamap=d.set(a,p),h.children.splice(xu(f),0,o,s),h}},sx=(t,e,r,n)=>XD(t,e,0,t.config.Path.from(r),r,n);var XD=(t,e,r,n,o,s)=>{let{datamap:i,nodemap:a,config:c}=t,{BitField:u,Path:l}=c,d=l.at(n,r);if(u.get(i,d)){let p=u.popcount(i,d);if(o===bu(t,p)){s.value=!0;let f=wu(t,e);return f.datamap=u.unset(t.datamap,d),f.children.splice(xu(p),2),f}else return t}else if(u.get(a,d)){let p=ku(t,d),f=p.dissociate(e,r+1,n,o,s);return fO(f)?hO(t)?f:lO(t,e,d,f):p===f?t:rT(t,e,d,f)}else return t},YD=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},wu=(t,e)=>sT(t.edit,e)?t:new sa(e,t.datamap,t.nodemap,t.children.slice(),t.config),eT=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},tT=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},uO=(t,e,r,n)=>{let o=t.fork(e);return o.children[oT(r)]=n,o},lO=(t,e,r,n)=>{let{datamap:o,nodemap:s,config:i}=t,{BitField:a}=i,c=wu(t,e);return c.children.splice(yh(t,r),1),c.children.splice(xu(a.popcount(o,r)),0,n.children[0],n.children[1]),c.datamap=a.set(o,r),c.nodemap=a.unset(s,r),c},rT=(t,e,r,n)=>{let o=wu(t,e);return o.children[yh(t,r)]=n,o},dO=(t,e,r,n)=>{let{nodemap:o,datamap:s,config:i}=t,{BitField:a}=i,c=a.popcount(s,r),u=xu(c),l=yh(t,r),d=wu(t,e);return d.datamap=a.unset(s,r),d.children.splice(u,2),d.nodemap=a.set(o,r),d.children.splice(l-1,0,n),d},nT=(t,e,r,n,o,s,i,a,c)=>{let{BitField:u,Path:l}=t;if(l.size<r)return new ph(e,2,[o,s,a,c],t);{let d=l.at(n,r),p=l.at(i,r);return d===p?new sa(e,u.empty(Math.pow(2,t.bitWidth)),u.from([d],Math.pow(2,t.bitWidth)),[nT(t,e,r+1,n,o,s,i,a,c)],t):new sa(e,u.from([d,p],Math.pow(2,t.bitWidth)),u.empty(Math.pow(2,t.bitWidth)),d<p?[o,s,a,c]:[a,c,o,s],t)}},bu=({children:t},e)=>t[xu(e)],xu=t=>t*2,yu=({children:t},e)=>t[oT(e)],oT=t=>t*2+1,ku=(t,e)=>t.children[yh(t,e)],yh=({children:t,nodemap:e,config:r},n)=>t.length-1-r.BitField.popcount(e,n),sT=(t,e)=>t!=null&&t===e,fO=t=>t.nodeArity===0&&t.dataArity===1,hO=({config:{BitField:t},datamap:e,nodemap:r})=>t.popcount(e)===0&&t.popcount(r)===1;var gh=De(tx(),1);function pO(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 VJ=Co({name:"murmur3-32",code:35,encode:t=>pO(gh.default.x86.hash32(t))}),aT=Co({name:"murmur3-128",code:34,encode:t=>bo.fromHex(gh.default.x64.hash128(t))}),ia=Co({name:"murmur3-x64-64",code:34,encode:t=>bo.fromHex(gh.default.x64.hash128(t)).subarray(0,8)});var mO=new TextEncoder,yO=t=>ia.encode(t),cT=({bitWidth:t=8,hash:e=yO}={})=>{let r=e(new Uint8Array).byteLength;return{from:s=>e(mO.encode(s)),at:(s,i)=>{let a=i*t;if(a>r)throw new RangeError("Out of bounds");return ix(s,a,t)},size:Math.ceil(r*8/t)}},ix=(t,e,r)=>{let n=e/8|0,o=e%8,s=r,i=0;for(;s>0&&n<t.byteLength;){let a=t[n],c=8-o,u=c<s?c:s,l=8-o-u,p=(255>>o&a)>>l;i=(i<<u)+p,s-=u,n++,o=0}return i};var ax={};F(ax,{API:()=>lh,and:()=>DO,empty:()=>uT,from:()=>wO,fromBytes:()=>EO,get:()=>vO,or:()=>AO,popcount:()=>_O,set:()=>xO,size:()=>bO,toBytes:()=>SO,unset:()=>kO});var uT=(t=256)=>{if(t%8!==0)throw new Error("Must be multiple of 8");return new Uint8Array(t/8)},wO=(t,e)=>{let r=uT(e);for(let n of t){let{byte:o,byteOffset:s,bitOffset:i}=vu(r,n);r[s]=o|1<<i}return r},bO=t=>t.byteLength*8,vu=(t,e)=>{let r=t.byteLength-1-(e/8|0),n=e%8;return{byte:t[r],byteOffset:r,bitOffset:n}},lT=(t,e,r)=>{if(t[e]!==r){let n=t.slice(0);return n[e]=r,n}return t},xO=(t,e)=>{let{byte:r,byteOffset:n,bitOffset:o}=vu(t,e);return lT(t,n,r|1<<o)},kO=(t,e)=>{let{byte:r,byteOffset:n,bitOffset:o}=vu(t,e);return lT(t,n,r&(255^1<<o))},vO=(t,e)=>{var{byte:r,bitOffset:n}=vu(t,e);return(r>>n&1)!==0},SO=t=>t,EO=t=>t,_O=(t,e=t.byteLength*8)=>{let{byteOffset:r,bitOffset:n,byte:o}=vu(t,e),s=ex(o,n),i=t.byteLength-1;for(;i>r;){let a=t[i];s+=dh(a),i--}return s},AO=(t,e)=>{let r=t.slice(),n=0;for(;n<t.length;)r[n]|=e[n],n++;return r},DO=(t,e)=>{let r=t.slice(),n=0;for(;n<t.length;)r[n]&=e[n],n++;return r};var dT=new RangeError("Not Found");var TO=({bitWidth:t=5,BitField:e=t===5?fh:ax,Path:r=t===5?ZD({bitWidth:t}):cT({bitWidth:t})}={})=>({bitWidth:t,BitField:e,Path:r}),fT=(t,e)=>{let r=lx(e);for(let[n,o]of t)r.set(n,o);return r.build()},ux=(t,e)=>mh(t.root,e,dT)!==dT,hT=(t,e,r=void 0)=>mh(t.root,e,r),lx=t=>{let e={},r=TO(t);return new wh(e,0,gu(r,e),r)},cx=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,gu(this.config,null),this.config)}has(e){return ux(this,e)}get(e){return mh(this.root,e,void 0)}set(e,r){let n={value:!1},o=nx(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=sx(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 wh({},this.count,this.root,this.config)}},wh=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=nx(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=sx(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 cx(this.count,this.root,this.config);throw new Error(".build was called on the finalized builder")}};var CO=new TextEncoder,IO=t=>ia.encode(t),mT=({bitWidth:t=8,hash:e=IO})=>{let r=e(new Uint8Array).byteLength,n={bitWidth:t,hash:e,hashSize:r};return{at:(i,a)=>BO(i,a,n),from:i=>CO.encode(i),size:1/0}},BO=(t,e=0,{bitWidth:r=8,hash:n,hashSize:o})=>{let s=o*8,i=0,a=r,c=r*e;for(;a>0;){let u=c/s>>0,l=n(u===0?t:PO(t,u)),d=s<=c?c%s:c,p=s-d,f=p<a?p:a;i=(i<<f)+ix(l,d,f),a-=f,c+=f}return i},PO=(t,e)=>{let r=new Uint8Array(t.byteLength+1).fill(e,t.byteLength);return r.set(t),r};var yT=8,gT={bitWidth:yT,Path:mT({bitWidth:yT})},wT=t=>Math.pow(2,t.config.bitWidth);var dx=(t=gT)=>lx(t),bT=(t,e=gT)=>fT(t,e),xT=({datamap:t,nodemap:e,config:{BitField:r}})=>UO(r.toBytes(r.or(t,e))),UO=t=>{let e=0;for(;e<t.byteLength;){if(t[e]!==0)return t.subarray(e);e+=1}return t.subarray(e)},kT=function*(t){let{config:e,datamap:r,nodemap:n}=t,{BitField:o}=e,s=o.size(r),i=0,a=0;for(;i<s;){let c=i.toString(16).toUpperCase().padStart(2,"0");if(o.get(r,i)){let u=bu(t,a);yield{prefix:c,key:u,value:yu(t,a)},a++}else o.get(n,i)&&(yield{prefix:c,node:ku(t,i)});i++}};function bh({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*NO(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r],s=se.asCID(n);s?yield[o.join("/"),s]:typeof n=="object"&&(yield*fx(n,o))}else{let r=se.asCID(e);r?yield[t.join("/"),r]:yield*fx(e,t)}}function*fx(t,e){if(t==null||t instanceof Uint8Array)return;let r=se.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,o]of Object.entries(t)){let s=[...e,n];yield*NO(s,o)}}function*OO(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r];yield o.join("/"),typeof n=="object"&&!se.asCID(n)&&(yield*hx(n,o))}else yield*hx(e,t)}function*hx(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"&&!se.asCID(n)&&(yield*OO(o,n))}}function $O(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(i=>`[${JSON.stringify(i)}]`).join("")}`);let s=se.asCID(r);if(s)return{value:s,remaining:e.slice(n+1).join("/")}}return{value:r}}var Qt=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:bh(),bytes:bh(),value:bh(),asBlock:bh()})}links(){return fx(this.value,[])}tree(){return hx(this.value,[])}get(e="/"){return $O(this.value,e.split("/").filter(Boolean))}};async function xh({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),s=se.create(1,e.code,o);return new Qt({value:t,bytes:n,cid:s})}async function kh({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),s=se.create(1,e.code,o);return new Qt({value:n,bytes:t,cid:s})}var MO=un,px=({writer:t,settings:e=MO(),metadata:r={}})=>new vh({writer:t,metadata:r,settings:e,entries:new Su,closed:!1}),FO=t=>{if(t.closed)throw new Error("Can not change written HAMT directory, but you can .fork() and make changes to it");return t},vT=async(t,{closeWriter:e=!1,releaseLock:r=!1}={})=>{let{writer:n,settings:o,metadata:s}=FO(t.state);t.state.closed=!0;let{entries:i}=t.state;if(!(i instanceof Su))throw new Error(`not a HAMT: ${i}`);let a=i.builder.build(),c=ST(a,a.root,o),u=null;for await(let l of c)u=l,(n.desiredSize||0)<=0&&await n.ready,n.write(l);if(u==null)throw new Error("no root block yielded");return e?await n.close():r&&n.releaseLock(),{cid:u.cid,dagByteLength:to(u.bytes,u.value.entries)}},ST=async function*(t,e,r){let n=[];for(let s of kT(e))if("key"in s)n.push({name:`${s.prefix??""}${s.key??""}`,dagByteLength:s.value.dagByteLength,cid:s.value.cid});else{let i=null;for await(let a of ST(t,s.node,r))yield a,i=a;if(i==null)throw new Error("no root block yielded");n.push({name:s.prefix,dagByteLength:to(i.bytes,i.value.entries),cid:i.cid})}let o=Ab(n,xT(e),wT(t),ia.code);yield await zO(o,r)};async function zO(t,e){let r=rh(t),n=await e.hasher.digest(r),o=e.linker.createLink(Qn,n);return new Qt({cid:o,bytes:r,value:t})}var ET=({state:t},{writer:e=t.writer,metadata:r=t.metadata,settings:n=t.settings}={})=>new vh({writer:e,metadata:r,settings:n,entries:new Su(bT(t.entries.entries()).createBuilder()),closed:!1}),vh=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.settings}set(e,r,n){return hu(this,e,r,n)}remove(e){return pu(this,e)}fork(e){return ET(this,e)}close(e){return vT(this,e)}entries(){return this.state.entries.entries()}has(e){return this.state.entries.has(e)}get size(){return this.state.entries.size}},Su=class extends Map{constructor(e=dx()){super(),this.builder=e}clear(){this.builder=dx()}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 hT(this.builder,e)}has(e){return ux(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 Eu=({writable:t,settings:e=un()})=>new mx({writer:t.getWriter(),settings:e}),jO=async(t,{releaseLock:e=!0,closeWriter:r=!0}={})=>(r?await t.writer.close():e&&t.writer.releaseLock(),t),mx=class{constructor({writer:e,settings:r}){this.writer=e,this.settings=Lr(r)}createFileWriter({settings:e=this.settings,metadata:r}={}){return fs({writer:this.writer,settings:e,metadata:r})}createDirectoryWriter({settings:e=this.settings,metadata:r}={}){return fu({writer:this.writer,settings:e,metadata:r})}close(e){return jO(this,e)}},WO=1048576,HO=WO*100,Sh=(t=HO)=>({highWaterMark:t,size:e=>e.bytes.length});var qO=1e3,AT=Sh(),DT=Lr({fileChunkEncoder:ui,smallFileEncoder:ui,chunker:lu(1024*1024),fileLayout:oa(1024)});function TT(t){let{readable:e,writable:r}=new TransformStream({},AT),n=Eu({writable:r,settings:DT}),o=new Eh("",t);return(async()=>(await o.finalize(n),await n.close()))(),e}var Au,Eh=class{constructor(e,r){ke(this,Au,void 0);this.name=e,fe(this,Au,r)}async finalize(e){let r=fs(e);return await $(this,Au).stream().pipeTo(new WritableStream({async write(n){await r.write(n)}})),await r.close()}};Au=new WeakMap;var aa,_u=class{constructor(e,r){ke(this,aa,void 0);w(this,"entries",new Map);this.name=e,fe(this,aa,r)}async finalize(e){let r=this.entries.size<=qO?fu(e):px(e);for(let[n,o]of this.entries){let s=await o.finalize(e);$(this,aa)?.onDirectoryEntryLink&&$(this,aa).onDirectoryEntryLink({name:o.name,...s}),r.set(n,s)}return await r.close()}};aa=new WeakMap;function CT(t,e){let r=new _u("",e);for(let i of t){let a=i.name.split("/");(a[0]===""||a[0]===".")&&a.shift();let c=r;for(let[u,l]of a.entries()){if(u===a.length-1){c.entries.set(l,new Eh(a.join("/"),i));break}let d=c.entries.get(l);if(d==null){let p=c===r?l:`${c.name}/${l}`;d=new _u(p,e),c.entries.set(l,d)}if(!(d instanceof _u))throw new Error(`"${i.name}" cannot be a file and a directory`);c=d}}let{readable:n,writable:o}=new TransformStream({},AT),s=Eu({writable:o,settings:DT});return(async()=>{let i=await r.finalize(s);e?.onDirectoryEntryLink&&e.onDirectoryEntryLink({name:"",...i}),await s.close()})(),n}async function _h(t,e){let r=kr(await t.upTo(8),t);if(r===0)throw new Error("Invalid CAR header (zero length)");let n=await t.exactly(r,!0),o=Ge(n);if(!Jl(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 s=Array.isArray(o.roots);if(o.version===1&&!s||o.version===2&&s)throw new Error("Invalid CAR header format");if(o.version===1)return o;let i=Yl(await t.exactly(Xl,!0));t.seek(i.dataOffset-t.pos);let a=await _h(t,1);return Object.assign(a,i)}async function GO(t){let e=await t.exactly(2,!1);if(e[0]===Tn.SHA2_256&&e[1]===Tn.LENGTH){let i=await t.exactly(34,!0),a=vn(i);return se.create(0,Tn.DAG_PB,a)}let r=kr(await t.upTo(8),t);if(r!==1)throw new Error(`Unexpected CID version (${r})`);let n=kr(await t.upTo(8),t),o=await t.exactly(ed(await t.upTo(8)),!0),s=vn(o);return se.create(r,n,s)}async function IT(t){let e=t.pos,r=kr(await t.upTo(8),t);if(r===0)throw new Error("Invalid CAR section (zero length)");r+=t.pos-e;let n=await GO(t),o=r-Number(t.pos-e);return{cid:n,length:r,blockLength:o}}async function KO(t){let{cid:e,blockLength:r}=await IT(t);return{bytes:await t.exactly(r,!0),cid:e}}async function ZO(t){let e=t.pos,{cid:r,length:n,blockLength:o}=await IT(t),s={cid:r,length:n,blockLength:o,offset:e,blockOffset:t.pos};return t.seek(s.blockLength),s}function ca(t){let e=(async()=>{let r=await _h(t);if(r.version===2){let n=t.pos-r.dataOffset;t=QO(t,r.dataSize-n)}return r})();return{header:()=>e,async*blocks(){for(await e;(await t.upTo(8)).length>0;)yield await KO(t)},async*blocksIndex(){for(await e;(await t.upTo(8)).length>0;)yield await ZO(t)}}}function no(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 JO(t){let e=0,r=0,n=0,o=new Uint8Array(0),s=async i=>{r=o.length-n;let a=[o.subarray(n)];for(;r<i;){let u=await t();if(u==null)break;r<0?u.length>r&&a.push(u.subarray(-r)):a.push(u),r+=u.length}o=new Uint8Array(a.reduce((u,l)=>u+l.length,0));let c=0;for(let u of a)o.set(u,c),c+=u.length;n=0};return{async upTo(i){return o.length-n<i&&await s(i),o.subarray(n,n+Math.min(o.length-n,i))},async exactly(i,a=!1){if(o.length-n<i&&await s(i),o.length-n<i)throw new Error("Unexpected end of data");let c=o.subarray(n,n+i);return a&&(e+=i,n+=i),c},seek(i){e+=i,n+=i},get pos(){return e}}}function ua(t){let e=t[Symbol.asyncIterator]();async function r(){let n=await e.next();return n.done?null:n.value}return JO(r)}function QO(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 s=await t.exactly(n,o);if(s.length+r>e)throw new Error("Unexpected end of data");return o&&(r+=n),s},seek(n){r+=n,t.seek(n)},get pos(){return t.pos}}}var hs=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 BT(no(e))}static async fromIterable(e){if(!e||typeof e[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return BT(ua(e))}};async function BT(t){let e=ca(t),r=await e.header(),n=[];for await(let o of e.blocks())n.push(o);return new hs(r,n)}var Du=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 PT(no(e))}static async fromIterable(e){if(!e||typeof e[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return PT(ua(e))}};async function PT(t){let e=ca(t),{version:r,roots:n}=await e.header();return new Du(r,n,e.blocksIndex())}var Ah=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}},Tu=class t extends Ah{[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 LT(e);return new t(r,n,o)}static async fromIterable(e){let{version:r,roots:n,iterator:o}=await UT(e);return new t(r,n,o)}},yx=class t extends Ah{[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 LT(e);return new t(r,n,o)}static async fromIterable(e){let{version:r,roots:n,iterator:o}=await UT(e);return new t(r,n,o)}};async function LT(t){if(!(t instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return RT(no(t))}async function UT(t){if(!t||typeof t[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return RT(ua(t))}async function RT(t){let e=ca(t),{version:r,roots:n}=await e.header();return{version:r,roots:n,iterator:e.blocks()}}var gx=De(Ql(),1);function wx(t){let e=tr({version:1,roots:t}),r=gx.default.encode(e.length),n=new Uint8Array(r.length+e.length);return n.set(r,0),n.set(e,r.length),n}function NT(t){return{async setRoots(e){let r=wx(e);await t.write(r)},async writeBlock(e){let{cid:r,bytes:n}=e;await t.write(new Uint8Array(gx.default.encode(r.bytes.length+n.length))),await t.write(r.bytes),n.length&&await t.write(n)},async close(){await t.end()}}}function Dh(){}function OT(){let t=[],e=null,r=Dh,n=!1,o=null,s=Dh,i=()=>(e||(e=new Promise(u=>{r=()=>{e=null,r=Dh,u()}})),e),a={write(u){t.push(u);let l=i();return s(),l},async end(){n=!0;let u=i();s(),await u}},c={async next(){let u=t.shift();return u?(t.length===0&&r(),{done:!1,value:u}):n?(r(),{done:!0,value:void 0}):(o||(o=new Promise(l=>{s=()=>(o=null,s=Dh,l(c.next()))})),o)}};return{writer:a,iterator:c}}var Cu=class t{constructor(e,r){this._encoder=r,this._mutex=r.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let r=se.asCID(e.cid);if(!r)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:r,bytes:e.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}static create(e){e=XO(e);let{encoder:r,iterator:n}=$T(),o=new t(e,r),s=new Th(n);return{writer:o,out:s}}static createAppender(){let{encoder:e,iterator:r}=$T();e.setRoots=()=>Promise.resolve();let n=new t([],e),o=new Th(r);return{writer:n,out:o}}static async updateRootsInBytes(e,r){let n=no(e);await _h(n);let o=wx(r);if(Number(n.pos)!==o.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${o.length} bytes)`);return e.set(o,0),e}},Th=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function $T(){let t=OT(),{writer:e,iterator:r}=t;return{encoder:NT(e),iterator:r}}function XO(t){if(t===void 0)return[];if(!Array.isArray(t)){let r=se.asCID(t);if(!r)throw new TypeError("roots must be a single CID or an array of CIDs");return[r]}let e=[];for(let r of t){let n=se.asCID(r);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}async function Ih(t,e){let{writer:r,out:n}=Cu.create(e),o;(async()=>{try{for await(let a of t)await r.put(a)}catch(a){o=a}finally{await r.close()}})();let s=[];for await(let a of n)s.push(a);if(o!=null)throw o;let i=e!=null?[e]:[];return Object.assign(new Blob(s),{version:1,roots:i})}var Ch=class extends ReadableStream{constructor(e){let r=null,n=()=>r||(r=Tu.fromIterable(YO(e.stream())),r),o=null;super({async start(){o=(await n())[Symbol.asyncIterator]()},async pull(s){if(!o)throw new Error("missing blocks iterator");let{value:i,done:a}=await o.next();if(a)return s.close();s.enqueue(i)}}),this.getRoots=async()=>await(await n()).getRoots()}};function YO(t){return Symbol.asyncIterator in t?t:async function*(){let e=t.getReader();try{for(;;){let{done:r,value:n}=await e.read();if(r)return;yield n}}finally{e.releaseLock()}}()}var ZT=De(FT(),1);var Bu=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},xx=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},zT=t=>globalThis.DOMException===void 0?new xx(t):new DOMException(t),jT=t=>{let e=t.reason===void 0?zT("This operation was aborted."):t.reason;return e instanceof Error?e:zT(e)};function kx(t,e,r,n){let o,s=new Promise((i,a)=>{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){i(t);return}if(n={customTimers:{setTimeout,clearTimeout},...n},n.signal){let{signal:c}=n;c.aborted&&a(jT(c)),c.addEventListener("abort",()=>{a(jT(c))})}o=n.customTimers.setTimeout.call(void 0,()=>{if(typeof r=="function"){try{i(r())}catch(l){a(l)}return}let c=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,u=r instanceof Error?r:new Bu(c);typeof t.cancel=="function"&&t.cancel(),a(u)},e),(async()=>{try{i(await t)}catch(c){a(c)}finally{n.customTimers.clearTimeout.call(void 0,o)}})()});return s.clear=()=>{clearTimeout(o),o=void 0},s}function vx(t,e,r){let n=0,o=t.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;r(t[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var ps=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)},ln,Pu=class{constructor(){ln.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&ps(this,ln,"f")[this.size-1].priority>=r.priority){ps(this,ln,"f").push(n);return}let o=vx(ps(this,ln,"f"),n,(s,i)=>i.priority-s.priority);ps(this,ln,"f").splice(o,0,n)}dequeue(){let e=ps(this,ln,"f").shift();return e?.run}filter(e){return ps(this,ln,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return ps(this,ln,"f").length}};ln=new WeakMap;var Oe=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},W=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)},He,Uu,Ru,so,Oh,Nu,Ph,fr,Lu,Ot,Lh,$t,Ou,oo,Uh,WT,HT,GT,qT,VT,Rh,Sx,Ex,$h,KT,Nh,Mh=class extends Error{},ms=class extends ZT.default{constructor(e){var r,n,o,s;if(super(),He.add(this),Uu.set(this,void 0),Ru.set(this,void 0),so.set(this,0),Oh.set(this,void 0),Nu.set(this,void 0),Ph.set(this,0),fr.set(this,void 0),Lu.set(this,void 0),Ot.set(this,void 0),Lh.set(this,void 0),$t.set(this,0),Ou.set(this,void 0),oo.set(this,void 0),Uh.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:Pu,...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 \`${(s=(o=e.interval)===null||o===void 0?void 0:o.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);Oe(this,Uu,e.carryoverConcurrencyCount,"f"),Oe(this,Ru,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),Oe(this,Oh,e.intervalCap,"f"),Oe(this,Nu,e.interval,"f"),Oe(this,Ot,new e.queueClass,"f"),Oe(this,Lh,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,Oe(this,Uh,e.throwOnTimeout===!0,"f"),Oe(this,oo,e.autoStart===!1,"f")}get concurrency(){return W(this,Ou,"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})`);Oe(this,Ou,e,"f"),W(this,He,"m",$h).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:W(this,Uh,"f"),...r},new Promise((n,o)=>{W(this,Ot,"f").enqueue(async()=>{var s,i,a;Oe(this,$t,(i=W(this,$t,"f"),i++,i),"f"),Oe(this,so,(a=W(this,so,"f"),a++,a),"f");try{if(!((s=r.signal)===null||s===void 0)&&s.aborted)throw new Mh("The task was aborted.");let c=e({signal:r.signal});r.timeout&&(c=kx(Promise.resolve(c),r.timeout)),r.signal&&(c=Promise.race([c,W(this,He,"m",KT).call(this,r.signal)]));let u=await c;n(u),this.emit("completed",u)}catch(c){if(c instanceof Bu&&!r.throwOnTimeout){n();return}o(c),this.emit("error",c)}finally{W(this,He,"m",GT).call(this)}},r),this.emit("add"),W(this,He,"m",Rh).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return W(this,oo,"f")?(Oe(this,oo,!1,"f"),W(this,He,"m",$h).call(this),this):this}pause(){Oe(this,oo,!0,"f")}clear(){Oe(this,Ot,new(W(this,Lh,"f")),"f")}async onEmpty(){W(this,Ot,"f").size!==0&&await W(this,He,"m",Nh).call(this,"empty")}async onSizeLessThan(e){W(this,Ot,"f").size<e||await W(this,He,"m",Nh).call(this,"next",()=>W(this,Ot,"f").size<e)}async onIdle(){W(this,$t,"f")===0&&W(this,Ot,"f").size===0||await W(this,He,"m",Nh).call(this,"idle")}get size(){return W(this,Ot,"f").size}sizeBy(e){return W(this,Ot,"f").filter(e).length}get pending(){return W(this,$t,"f")}get isPaused(){return W(this,oo,"f")}};Uu=new WeakMap,Ru=new WeakMap,so=new WeakMap,Oh=new WeakMap,Nu=new WeakMap,Ph=new WeakMap,fr=new WeakMap,Lu=new WeakMap,Ot=new WeakMap,Lh=new WeakMap,$t=new WeakMap,Ou=new WeakMap,oo=new WeakMap,Uh=new WeakMap,He=new WeakSet,WT=function(){return W(this,Ru,"f")||W(this,so,"f")<W(this,Oh,"f")},HT=function(){return W(this,$t,"f")<W(this,Ou,"f")},GT=function(){var e;Oe(this,$t,(e=W(this,$t,"f"),e--,e),"f"),W(this,He,"m",Rh).call(this),this.emit("next")},qT=function(){W(this,He,"m",Ex).call(this),W(this,He,"m",Sx).call(this),Oe(this,Lu,void 0,"f")},VT=function(){let e=Date.now();if(W(this,fr,"f")===void 0){let r=W(this,Ph,"f")-e;if(r<0)Oe(this,so,W(this,Uu,"f")?W(this,$t,"f"):0,"f");else return W(this,Lu,"f")===void 0&&Oe(this,Lu,setTimeout(()=>{W(this,He,"m",qT).call(this)},r),"f"),!0}return!1},Rh=function(){if(W(this,Ot,"f").size===0)return W(this,fr,"f")&&clearInterval(W(this,fr,"f")),Oe(this,fr,void 0,"f"),this.emit("empty"),W(this,$t,"f")===0&&this.emit("idle"),!1;if(!W(this,oo,"f")){let e=!W(this,He,"a",VT);if(W(this,He,"a",WT)&&W(this,He,"a",HT)){let r=W(this,Ot,"f").dequeue();return r?(this.emit("active"),r(),e&&W(this,He,"m",Sx).call(this),!0):!1}}return!1},Sx=function(){W(this,Ru,"f")||W(this,fr,"f")!==void 0||(Oe(this,fr,setInterval(()=>{W(this,He,"m",Ex).call(this)},W(this,Nu,"f")),"f"),Oe(this,Ph,Date.now()+W(this,Nu,"f"),"f"))},Ex=function(){W(this,so,"f")===0&&W(this,$t,"f")===0&&W(this,fr,"f")&&(clearInterval(W(this,fr,"f")),Oe(this,fr,void 0,"f")),Oe(this,so,W(this,Uu,"f")?W(this,$t,"f"):0,"f"),W(this,He,"m",$h).call(this)},$h=function(){for(;W(this,He,"m",Rh).call(this););},KT=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new Mh("The task was aborted."))},{once:!0})})},Nh=async function(e,r){return new Promise(n=>{let o=()=>{r&&!r()||(this.off(e,o),n())};this.on(e,o)})};var n$=1024*1024*100,o$=3,Fh=class extends TransformStream{constructor(e={}){let r=e.shardSize??n$,n=[],o=null,s=0;super({async transform(i,a){o!=null&&(a.enqueue(await Ih(o)),o=null),n.length&&s+i.bytes.length>r&&(o=n,n=[],s=0),n.push(i),s+=i.bytes.length},async flush(i){o!=null&&i.enqueue(await Ih(o));let a=n.at(-1);a!=null&&i.enqueue(await Ih(n,e.rootCID??a.cid))}})}},zh=class extends TransformStream{constructor(e,r={}){let n=new ms({concurrency:r.concurrentRequests??o$}),o=new AbortController;super({async transform(s,i){n.add(async()=>{try{let a={...r,signal:o.signal},c=await sb(e,s,a),{version:u,roots:l,size:d}=s;i.enqueue({version:u,roots:l,cid:c,size:d})}catch(a){i.error(a),o.abort(a)}},{signal:o.signal}).catch(a=>console.error(a)),await n.onSizeLessThan(1)},async flush(){await n.onIdle()}})}};async function JT(t,e,r={}){return await _x(t,TT(e),r)}async function QT(t,e,r={}){return await _x(t,CT(e,r),r)}async function XT(t,e,r={}){let n=new Ch(e);return r.rootCID=r.rootCID??(await n.getRoots())[0],await _x(t,n,r)}async function _x(t,e,r={}){let n=[],o=null;if(await e.pipeThrough(new Fh(r)).pipeThrough(new zh(t,r)).pipeTo(new WritableStream({write(s){o=o||s.roots[0],n.push(s.cid),r.onShardStored&&r.onShardStored(s)}})),!o)throw new Error("missing root CID");return await ib(t,o,n,r),o}function YT(t,e){return e===void 0?C({}):t!==void 0&&e.endsWith("*")?t.startsWith(e.slice(0,-1))?C({}):ie(`${t} does not match ${e}`):t===e?C({}):ie(`${t} is different from ${e}`)}function de(t,e){return t.with===e.with?C({}):ie(`Can not derive ${t.can} with ${t.with} from ${e.with}`)}function Be(t,e,r){return e===void 0||e==="*"?C({}):String(t)===String(e)?C({}):ie(`Constrain violation: ${t} violates imposed ${r} constraint ${e}`)}var Ax=(t,e)=>t.with!==e.with?ie(`Expected 'with: "${e.with}"' instead got '${t.with}'`):e.nb.link&&`${e.nb.link}`!=`${t.nb.link}`?ie(`Link ${t.nb.link?`${t.nb.link}`:""} violates imposed ${e.nb.link} constraint.`):C({}),la=(t,e,r)=>Be(String(t),e===void 0?void 0:String(e),r),X=t=>t.error?t:void 0;var i$=ee.match({method:"web"}),a$=ee.match({method:"mailto"}),eC=T({can:"provider/add",with:a$,nb:Ne({provider:i$,consumer:ee.match({method:"key"})}),derives:(t,e)=>X(de(t,e))||X(Be(t.nb.provider,e.nb.provider,"provider"))||X(Be(t.nb.consumer,e.nb.consumer,"consumer"))||C({})});var hr={};F(hr,{Link:()=>pe,Schema:()=>x,add:()=>da,all:()=>u$,list:()=>ha,remove:()=>fa,store:()=>Dx});var Dx=T({can:"store/*",with:V.match({protocol:"did:"}),derives:de}),da=T({can:"store/add",with:V.match({protocol:"did:"}),nb:x.struct({link:pe,size:x.integer(),origin:pe.optional()}),derives:(t,e)=>{let r=Ax(t,e);return r.error?r:t.nb.size!==void 0&&e.nb.size!==void 0?t.nb.size>e.nb.size?ie(`Size constraint violation: ${t.nb.size} > ${e.nb.size}`):C({}):C({})}}),fa=T({can:"store/remove",with:V.match({protocol:"did:"}),nb:x.struct({link:pe}),derives:Ax}),ha=T({can:"store/list",with:V.match({protocol:"did:"}),nb:x.struct({cursor:x.string().optional(),size:x.integer().optional(),pre:x.boolean().optional()}),derives:(t,e)=>t.with!==e.with?ie(`Expected 'with: "${e.with}"' instead got '${t.with}'`):C({})}),u$=da.or(fa).or(ha);var pr={};F(pr,{Link:()=>pe,Schema:()=>x,add:()=>pa,all:()=>d$,list:()=>ya,remove:()=>ma,upload:()=>Tx});var Tx=T({can:"upload/*",with:V.match({protocol:"did:"}),derives:de}),l$=pe.match({code:Re.code,version:1}),pa=T({can:"upload/add",with:V.match({protocol:"did:"}),nb:x.struct({root:pe,shards:l$.array().optional()}),derives:(t,e)=>X(de(t,e))||X(Be(t.nb.root,e.nb.root,"root"))||X(Be(t.nb.shards,e.nb.shards,"shards"))||C({})}),ma=T({can:"upload/remove",with:V.match({protocol:"did:"}),nb:x.struct({root:pe}),derives:(t,e)=>X(de(t,e))||X(Be(t.nb.root,e.nb.root,"root"))||C({})}),ya=T({can:"upload/list",with:V.match({protocol:"did:"}),nb:x.struct({cursor:x.string().optional(),size:x.integer().optional(),pre:x.boolean().optional()})}),d$=pa.or(ma).or(ya);var $u=T({can:"*",with:V.match({protocol:"did:"}),derives:de});var jh=x.did({method:"key"}),tC=T({can:"space/*",with:jh,derives:de}),rC=da.or(ha).or(fa).or(pa).or(ya).or(ma).derive({to:T({can:"space/info",with:jh}),derives:de}),nC=T({can:"space/recover-validation",with:jh,nb:x.struct({identity:V.match({protocol:"mailto:"})})}),oC=T({can:"space/recover",with:x.did(),nb:x.struct({identity:V.match({protocol:"mailto:"})}),derives:(t,e)=>X(de(t,e))||X(YT(t.nb.identity,e.nb.identity))||C({})}),DX=T({can:"space/allocate",with:jh,nb:x.struct({size:x.integer()}),derives:(t,e)=>{let r=de(t,e);return r.ok?t.nb.size<=e.nb.size?C({}):ie(`Claimed size ${t.nb.size} escalates delegated size ${e.nb.size}`):r}});var BX=ee.match({method:"key"}),sC=V.uri(),iC=V.match({protocol:"mailto:"}),p$=ee.match({}),PX=T({can:"voucher/*",with:V.match({protocol:"did:"}),derives:de}),aC=T({can:"voucher/claim",with:V.match({protocol:"did:"}),nb:x.struct({product:sC,identity:iC,service:p$.optional()}),derives:(t,e)=>X(de(t,e))||X(Be(t.nb.product,e.nb.product,"product"))||X(Be(t.nb.identity,e.nb.identity,"identity"))||X(Be(t.nb.service,e.nb.service,"service"))||C({})}),cC=T({can:"voucher/redeem",with:V.match({protocol:"did:"}),nb:x.struct({product:sC,identity:iC,space:V.match({protocol:"did:"})}),derives:(t,e)=>X(de(t,e))||X(Be(t.nb.product,e.nb.product,"product"))||X(Be(t.nb.identity,e.nb.identity,"identity"))||X(Be(t.nb.space,e.nb.space,"account"))||C({})});var lC=ee.match({method:"mailto"}),dC=x.struct({can:x.string()}),y$=x.struct({iss:lC,att:dC.array()}),fC=T({can:"access/*",with:V.match({protocol:"did:"})}),hC=T({can:"access/authorize",with:ee.match({method:"key"}),nb:y$,derives:(t,e)=>X(de(t,e))||X(Be(t.nb.iss,e.nb.iss,"iss"))||X(mC(t.nb.att,e.nb.att))||C({})}),NX=T({can:"access/confirm",with:ee,nb:x.struct({iss:lC,aud:x.did(),att:dC.array()}),derives:(t,e)=>X(de(t,e))||X(Be(t.nb.iss,e.nb.iss,"iss"))||X(Be(t.nb.aud,e.nb.aud,"aud"))||X(mC(t.nb.att,e.nb.att))||C({})}),pC=T({can:"ucan/attest",with:V.match({protocol:"did:"}),nb:x.struct({proof:pe})}),OX=T({can:"access/claim",with:ee.match({method:"key"}).or(ee.match({method:"mailto"}))}),$X=T({can:"access/delegate",with:ee.match({method:"key"}),nb:x.struct({delegations:x.dictionary({value:x.Link.match()})}),derives:(t,e)=>X(de(t,e))||X(g$(t,e))||C({})});function g$(t,e){let r=yC(uC(t),new Set(uC(e)));return r.size>0?ie(`unauthorized nb.delegations ${[...r].join(", ")}`):C({})}var mC=(t,e)=>{let r=new Set(e.map(o=>o.can));if(r.has("*"))return C({});let n=yC(t.map(o=>o.can),r);return n.size>0?ie(`unauthorized nb.att.can ${[...n].join(", ")}`):C({})};function*uC(t){for(let e of Object.values(t.nb.delegations||{}))yield e.toString()}function yC(t,e){let r=new Set;for(let n of t)e.has(n)||r.add(n);return r}var b$=ee.match({method:"web"}),x$=ee.match({method:"key"}),jX=T({can:"consumer/has",with:b$,nb:Ne({consumer:x$}),derives:(t,e)=>X(de(t,e))||X(Be(t.nb.consumer,e.nb.consumer,"consumer"))||C({})});var v$=ee.match({method:"web"}),S$=ee.match({method:"mailto"}),qX=T({can:"customer/get",with:v$,nb:Ne({customer:S$}),derives:(t,e)=>X(de(t,e))||X(Be(t.nb.customer,e.nb.customer,"customer"))||C({})});var KX=T({can:"console/log",with:x.did(),nb:x.struct({value:x.unknown()}),derives:de}),ZX=T({can:"console/error",with:x.did(),nb:x.struct({error:x.unknown()}),derives:de});var gC=T({can:"offer/arrange",with:x.did(),nb:x.struct({pieceLink:x.link()}),derives:(t,e)=>X(de(t,e))||X(la(t.nb.pieceLink,e.nb.pieceLink,"nb.pieceLink"))||C({})});var D$=4114,T$=61697,wC=T({can:"aggregate/offer",with:x.did(),nb:x.struct({offer:x.link(),piece:x.struct({link:x.link({code:T$,version:1,multihash:{code:D$}}),size:x.integer()})}),derives:(t,e)=>X(de(t,e))||X(la(t.nb.offer,e.nb.offer,"nb.offer"))||X(la(t.nb.piece.link,e.nb.piece.link,"nb.piece.link"))||X(Be(t.nb.piece.size,e.nb.piece.size,"nb.piece.size"))||C({})}),bC=T({can:"aggregate/get",with:x.did(),nb:x.struct({subject:x.link()}),derives:(t,e)=>X(de(t,e))||X(la(t.nb.subject,e.nb.subject,"nb.subject"))||C({})});var eY=[$u.can,eC.can,tC.can,rC.can,oC.can,nC.can,Tx.can,pa.can,ma.can,ya.can,Dx.can,da.can,fa.can,ha.can,aC.can,cC.can,fC.can,hC.can,pC.can,wC.can,bC.can,gC.can];var I$=new TextEncoder,B$=new TextDecoder,xC=t=>I$.encode(t),kC=t=>B$.decode(t);var vC="did:",L$=vC.length,SC="did:key:",U$=SC.length,R$=237,N$=4613,O$=4608,$$=4609,M$=4610;var Bx=3357,Cx=Y.encodingLength(Bx),Fu=t=>{if(t.startsWith(vC))if(t.startsWith(SC)){let e=Le.decode(t.slice(U$));return F$(e)}else{let e=xC(t.slice(L$)),r=new Uint8Array(e.byteLength+Cx);return Y.encodeTo(Bx,r),r.set(e,Cx),new Mu(r)}else throw new RangeError(`Invalid DID "${t}", must start with 'did:'`)};var F$=t=>{let[e]=Y.decode(t),{buffer:r,byteOffset:n,byteLength:o}=t;switch(e){case O$:if(t.length>35)throw new RangeError("Only p256-pub compressed is supported.");case R$:case N$:case $$:case M$:return new Ix(r,n,o);case Bx:return new Mu(r,n,o);default:throw new RangeError(`Unsupported DID encoding, unknown multicode 0x${e.toString(16)}.`)}};var Mu=class extends Uint8Array{did(){let e=new Uint8Array(this.buffer,this.byteOffset+Cx);return`did:${kC(e)}`}toJSON(){return this.did()}},Ix=class extends Mu{did(){return`did:key:${Le.encode(this)}`}};var z$=new URL("https://up.web3.storage"),j$=Fu("did:web:web3.storage"),W$=$o({id:j$,codec:ir.outbound,channel:Ln.open({url:z$,method:"POST"})}),H$=new URL("https://up.web3.storage"),q$=Fu("did:web:web3.storage"),V$=$o({id:q$,codec:ir.outbound,channel:Ln.open({url:H$,method:"POST"})}),_C={access:W$,upload:V$};var Xt=class{constructor(e,r={}){w(this,"_agent");w(this,"_serviceConf");this._serviceConf=r.serviceConf??_C,this._agent=new Af(e,{servicePrincipal:this._serviceConf.access.id,url:this._serviceConf.access.channel.url,connection:this._serviceConf.access})}async _invocationConfig(e){let r=this._agent.currentSpace();if(!r)throw new Error("missing current space: use createSpace() or setCurrentSpace()");let n=this._agent.issuer,o=await this._agent.proofs(e.map(i=>({can:i,with:r}))),s=this._serviceConf.upload.id;return{issuer:n,with:r,proofs:o,audience:s}}};var zu,ys,gs=class{constructor(e,r={}){ke(this,zu,void 0);ke(this,ys,void 0);fe(this,zu,e),fe(this,ys,r)}name(){return $(this,ys).name}did(){return $(this,zu)}registered(){return!!$(this,ys).isRegistered}meta(){return $(this,ys)}};zu=new WeakMap,ys=new WeakMap;var Wu,ju=class extends Gt{constructor(r,n,o={}){super(r,n);ke(this,Wu,void 0);fe(this,Wu,o)}meta(){return $(this,Wu)}};Wu=new WeakMap;var Wh=class extends Xt{async add(e,r={}){let n=await this._invocationConfig([hr.add.can]);return r.connection=this._serviceConf.upload,qi.add(n,e,r)}async list(e={}){let r=await this._invocationConfig([hr.add.can]);return e.connection=this._serviceConf.upload,qi.list(r,e)}async remove(e,r={}){let n=await this._invocationConfig([hr.remove.can]);return r.connection=this._serviceConf.upload,qi.remove(n,e,r)}};var Hh=class extends Xt{async add(e,r,n={}){let o=await this._invocationConfig([pr.add.can]);return n.connection=this._serviceConf.upload,Vi.add(o,e,r,n)}async list(e={}){let r=await this._invocationConfig([pr.list.can]);return e.connection=this._serviceConf.upload,Vi.list(r,e)}async remove(e,r={}){let n=await this._invocationConfig([pr.remove.can]);return r.connection=this._serviceConf.upload,Vi.remove(n,e,r)}};var qh=class extends Xt{async info(e){return await this._agent.getSpaceInfo(e)}};var Vh=class extends Xt{async authorize(e,r){return _2(this._agent,e,r)}async claim(){return Gw(this._agent,this._agent.issuer.did(),{addProofs:!0})}};var Hu=class extends Xt{constructor(e,r){super(e,r),this.capability={access:new Vh(e,r),store:new Wh(e,r),upload:new Hh(e,r),space:new qh(e,r)}}async authorize(e,r){await this.capability.access.authorize(e,r)}async uploadFile(e,r={}){let n=await this._invocationConfig([hr.add.can,pr.add.can]);return r.connection=this._serviceConf.upload,JT(n,e,r)}async uploadDirectory(e,r={}){let n=await this._invocationConfig([hr.add.can,pr.add.can]);return r.connection=this._serviceConf.upload,QT(n,e,r)}async uploadCAR(e,r={}){let n=await this._invocationConfig([hr.add.can,pr.add.can]);return r.connection=this._serviceConf.upload,XT(n,e,r)}defaultProvider(){return this._agent.connection.id.did()}agent(){return this._agent.issuer}currentSpace(){let e=this._agent.currentSpace();return e?new gs(e,this._agent.spaces.get(e)):void 0}async setCurrentSpace(e){await this._agent.setCurrentSpace(e)}spaces(){return[...this._agent.spaces].map(([e,r])=>new gs(e,r))}async createSpace(e){let{did:r,meta:n}=await this._agent.createSpace(e);return new gs(r,n)}async registerSpace(e,r={}){r.provider=r.provider??this.defaultProvider(),await this._agent.registerSpace(e,r)}async addSpace(e){let{did:r,meta:n}=await this._agent.importSpaceFromDelegation(e);return new gs(r,n)}proofs(e){return this._agent.proofs(e)}async addProof(e){await this._agent.addProof(e)}delegations(e){let r=[];for(let{delegation:n,meta:o}of this._agent.delegationsWithMeta(e))r.push(new ju(n.root,n.blocks,o));return r}async createDelegation(e,r,n={}){let o=n.audienceMeta??{name:"agent",type:"device"},{root:s,blocks:i}=await this._agent.delegate({...n,abilities:r,audience:e,audienceMeta:o});return new ju(s,i,{audience:o})}};async function AC(t={}){let e=t.store??new If("w3up-client"),r=await e.load();if(r){let s=Kn.fromExport(r,{store:e});if(t.principal&&s.principal.did()!==t.principal.did())throw new Error(`store cannot be used with ${t.principal.did()}, stored principal and passed principal must match`);return new Hu(s,t)}let n=t.principal??await Nw(),o=await Kn.create({principal:n},{store:e});return new Hu(o,t)}var Gh="0123456789abcdef",Kh=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 s=new Uint8Array(16);return s[0]=e/2**40,s[1]=e/2**32,s[2]=e/2**24,s[3]=e/2**16,s[4]=e/2**8,s[5]=e,s[6]=112|r>>>8,s[7]=r,s[8]=128|n>>>24,s[9]=n>>>16,s[10]=n>>>8,s[11]=n,s[12]=o>>>24,s[13]=o>>>16,s[14]=o>>>8,s[15]=o,new t(s)}static parse(e){var r,n,o,s;let i;switch(e.length){case 32:i=(r=/^[0-9a-f]{32}$/i.exec(e))===null||r===void 0?void 0:r[0];break;case 36:i=(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:i=(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:i=(s=/^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||s===void 0?void 0:s.slice(1,6).join("");break;default:break}if(i){let a=new Uint8Array(16);for(let c=0;c<16;c+=4){let u=parseInt(i.substring(2*c,2*c+8),16);a[c+0]=u>>>24,a[c+1]=u>>>16,a[c+2]=u>>>8,a[c+3]=u}return new t(a)}else throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let r=0;r<this.bytes.length;r++)e+=Gh.charAt(this.bytes[r]>>>4),e+=Gh.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+=Gh.charAt(this.bytes[r]>>>4),e+=Gh.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}},Px=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??G$()}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 Kh.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,Kh.ofInner(e)}},G$=()=>{if(typeof crypto<"u"&&typeof crypto.getRandomValues<"u")return new Lx;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)}},Lx=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++]}},DC,TC=()=>K$().toString(),K$=()=>(DC||(DC=new Px)).generate();function CC(t,e=1/0,r=!1){let n=[],o=!1;async function s(){if(o||n.length===0)return;o=!0;let i=n.splice(0,e),a=i.map(c=>c.task);if(r){let c=a.map(async(u,l)=>{try{let d=await t([u]);i[l].resolve(d)}catch(d){i[l].reject(d)}});await Promise.all(c)}else try{let c=await t(a);i.forEach(u=>u.resolve(c))}catch(c){i.forEach(u=>u.reject(c))}o=!1,s()}return{push(i){return new Promise((a,c)=>{n.push({task:i,resolve:a,reject:c}),s()})}}}var Ur,pt=class{constructor(e){ke(this,Ur,new Map);e&&fe(this,Ur,new Map(e.map(r=>[r.cid.toString(),r.bytes])))}async get(e){let r=$(this,Ur).get(e.toString());if(r)return{cid:e,bytes:r}}async put(e,r){$(this,Ur).set(e.toString(),r)}putSync(e,r){$(this,Ur).set(e.toString(),r)}async delete(e){$(this,Ur).delete(e.toString())}deleteSync(e){$(this,Ur).delete(e.toString())}*entries(){for(let[e,r]of $(this,Ur))yield{cid:br(e),bytes:r}}};Ur=new WeakMap;var qu,ws=class{constructor(...e){ke(this,qu,void 0);fe(this,qu,e)}async get(e){for(let r of $(this,qu)){let n=await r.get(e);if(n)return n}}};qu=new WeakMap;var Ux=class{constructor(e){w(this,"value");w(this,"next");this.value=e}},Rr,bs,xs,Vu=class{constructor(){ke(this,Rr,void 0);ke(this,bs,void 0);ke(this,xs,void 0);this.clear()}enqueue(e){let r=new Ux(e);$(this,Rr)?($(this,bs).next=r,fe(this,bs,r)):(fe(this,Rr,r),fe(this,bs,r)),ym(this,xs)._++}dequeue(){let e=$(this,Rr);if(e)return fe(this,Rr,$(this,Rr).next),ym(this,xs)._--,e.value}clear(){fe(this,Rr,void 0),fe(this,bs,void 0),fe(this,xs,0)}get size(){return $(this,xs)}*[Symbol.iterator](){let e=$(this,Rr);for(;e;)yield e.value,e=e.next}};Rr=new WeakMap,bs=new WeakMap,xs=new WeakMap;function Gu(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 Vu,r=0,n=()=>{r--,e.size>0&&e.dequeue()()},o=async(a,c,u)=>{r++;let l=(async()=>a(...u))();c(l);try{await l}catch{}n()},s=(a,c,u)=>{e.enqueue(o.bind(void 0,a,c,u)),(async()=>(await Promise.resolve(),r<t&&e.size>0&&e.dequeue()()))()},i=(a,...c)=>new Promise(u=>{s(a,u,c)});return Object.defineProperties(i,{activeCount:{get:()=>r},pendingCount:{get:()=>e.size},clearQueue:{value:()=>{e.clear()}}}),i}function Zh({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*Z$(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r],s=ve.asCID(n);s?yield[o.join("/"),s]:typeof n=="object"&&(yield*Rx(n,o))}else{let r=ve.asCID(e);r?yield[t.join("/"),r]:yield*Rx(e,t)}}function*Rx(t,e){if(t==null||t instanceof Uint8Array)return;let r=ve.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,o]of Object.entries(t)){let s=[...e,n];yield*Z$(s,o)}}function*J$(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r];yield o.join("/"),typeof n=="object"&&!ve.asCID(n)&&(yield*Nx(n,o))}else yield*Nx(e,t)}function*Nx(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"&&!ve.asCID(n)&&(yield*J$(o,n))}}function Q$(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(i=>`[${JSON.stringify(i)}]`).join("")}`);let s=ve.asCID(r);if(s)return{value:s,remaining:e.slice(n+1).join("/")}}return{value:r}}var Ku=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:Zh(),bytes:Zh(),value:Zh(),asBlock:Zh()})}links(){return Rx(this.value,[])}tree(){return Nx(this.value,[])}get(e="/"){return Q$(this.value,e.split("/").filter(Boolean))}};async function Nr({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),s=ve.create(1,e.code,o);return new Ku({value:t,bytes:n,cid:s})}async function io({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),s=ve.create(1,e.code,o);return new Ku({value:n,bytes:t,cid:s})}function X$({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 Ku({cid:e,bytes:t,value:o})}async function Jh({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),s=await r.digest(t);if(!bo.equals(e.multihash.bytes,s.bytes))throw new Error("CID hash does not match bytes");return X$({bytes:t,cid:e,value:o,codec:n})}var IC=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),kt=Co({name:"sha2-256",code:18,encode:IC("SHA-256")}),ree=Co({name:"sha2-512",code:19,encode:IC("SHA-512")});var ao={};F(ao,{code:()=>Zu,decode:()=>tM,encode:()=>eM,name:()=>Y$});var Y$="raw",Zu=85,eM=t=>jt(t),tM=t=>jt(t);async function ga(t,e){let r=0,n=Bn({roots:t});r+=n;for(let{cid:i,bytes:a}of e.entries())r+=Er({cid:i,bytes:a});let o=new Uint8Array(r),s=Pn(o,{headerSize:n});for(let i of t)s.addRoot(i);for(let{cid:i,bytes:a}of e.entries())s.write({cid:i,bytes:a});return s.close(),await Nr({value:s.bytes,hasher:kt,codec:ao})}async function BC(t){return await Nr({value:{fp:t},hasher:kt,codec:Te})}async function PC(t){let e=await t.getRoots(),r=await t.get(e[0]);if(!r)throw new Error("missing header block");let{value:n}=await io({bytes:r.bytes,hasher:kt,codec:Te});if(n&&n.fp===void 0)throw new Error("missing fp");let{fp:o}=n;return o}var ks={};F(ks,{code:()=>iM,crypto:()=>aM,decode:()=>sM,decrypt:()=>Yh,encode:()=>oM,encrypt:()=>ep,name:()=>cM});function Qh(){try{return window.crypto&&window.crypto.subtle?window.crypto:new Crypto}catch{return null}}var Ju=Qh();function Xh(t){let e=new Uint8Array(t);return t>0&&Ju.getRandomValues(e),e}var rM=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},nM=t=>{let e=t.byteLength-4;return(t[e]|t[e+1]<<8|t[e+2]<<16)+t[e+3]*16777216},LC=t=>{let e=t.map(s=>s instanceof ArrayBuffer?new Uint8Array(s):s),r=e.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r),o=0;for(let s of e)n.set(s,o),o+=s.length;return n},oM=({iv:t,bytes:e})=>LC([t,e]),sM=t=>{let e=t.subarray(0,12);return t=t.slice(12),{iv:e,bytes:t}},iM=3145728+1337;async function UC(t){return await Ju.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt","decrypt"])}var Yh=async({key:t,value:e})=>{let{bytes:r,iv:n}=e,o=await UC(t),s=await Ju.subtle.decrypt({name:"AES-GCM",iv:n,tagLength:128},o,r);r=new Uint8Array(s);let i=nM(r.subarray(0,4)),a=ve.decode(r.subarray(4,4+i));return r=r.subarray(4+i),{cid:a,bytes:r}},ep=async({key:t,cid:e,bytes:r})=>{let n=rM(e.bytes.byteLength),o=Xh(12),s=LC([n,e.bytes,r]);try{let i=await UC(t),a=await Ju.subtle.encrypt({name:"AES-GCM",iv:o,tagLength:128},i,s);r=new Uint8Array(a)}catch(i){throw console.log("ee",i),i}return{value:{bytes:r,iv:o}}},aM=t=>({encrypt:e=>ep({key:t,...e}),decrypt:e=>Yh({key:t,...e})}),cM="jchris@encrypted-block:aes-gcm";var Qu=t=>{let e=t.byteLength-4;return(t[e]|t[e+1]<<8|t[e+2]<<16)+t[e+3]*16777216};var Xu=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 Ss=(t,e)=>t===e?0:t>e?1:-1,RC=(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},vs=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 Es=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}},co=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 s=n[o];if(r(e,s.key)>-1)return[o,s]}return null}findMany(e,r,n=!1,o=!1){let{entries:s}=this,i=new Map;n?e=[...e]:e=e.sort(r);for(let a=s.length-1;a>-1&&e.length;a--){let c=s[a],u=[];for(;e.length;){let l=e[e.length-1];l=l.key?l.key:l;let d=r(l,c.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&&i.set(a,[c,u])}return i}findRange(e,r,n){let{entries:o}=this,s,i=0;for(let a=o.length-1;a>-1;a--){let c=o[a];if(n(r,c.key)>0){s=a;break}}for(let a=0;a<o.length;a++){let c=o[a],u=n(e,c.key);if(u===0){i=a;break}else if(u<0)break;i=a}return{first:i,last:s,entries:o.slice(i,s+1)}}},NC=t=>typeof t=="string"?t:JSON.stringify(t);function uM(t,e){return t.sort(({key:r},{key:n})=>e.compare(r,n))}async function lM(t,e,r){let n=[];for(let o of e){let{key:s,del:i}=o;if(r(s,t)<0)i||n.push(o);else break}return n}async function dM(t,e,{chunker:r,compare:n}){return await uo.from({entries:t.map(o=>new e.LeafEntryClass(o,e)).sort((o,s)=>n(o.key,s.key)),chunker:r,NodeClass:e.LeafClass,distance:0,opts:e})}async function fM(t,e,r,n){return await Promise.all(e.map(async o=>{let s=await o.encode();return r.blocks.push({block:s,node:o}),t.cache.set(o),new n.BranchEntryClass({key:o.key,address:await o.address},n)}))}async function hM(t,e,r,n){let o=e.root;e.blocks.push({block:await o.encode(),node:o}),t.cache.set(o);let s=n.opts,i=o.distance,a=o.entryList.startKey,c=await lM(a,r,t.compare);if(c.length){let u=await dM(c,s,t),l=await fM(t,u,e,s),p=[new s.BranchEntryClass({key:o.entryList.startKey,address:await o.address},s),...l].sort(({key:m},{key:b})=>s.compare(m,b)),f=await uo.from({...n,entries:p,chunker:t.chunker,NodeClass:s.BranchClass,distance:i+1}),h=[...f];for(;f.length>1;){let m=await Promise.all(f.map(async b=>new s.BranchEntryClass({key:b.key,address:await b.address},s)));f=await uo.from({...n,entries:m.sort(({key:b},{key:g})=>s.compare(b,g)),chunker:t.chunker,NodeClass:s.BranchClass,distance:i+1}),h=[...h,...f]}await Promise.all(h.map(async m=>{let b=await m.encode();t.cache.set(m),e.blocks.push({block:b,node:m})})),e.root=f[0],e.nodes=[...e.nodes,...h]}}var uo=class t{constructor({entryList:e,chunker:r,distance:n,getNode:o,compare:s,cache:i}){this.entryList=e,this.chunker=r,this.distance=n,this.getNode=o,this.compare=s,this.cache=i}get closed(){return this.entryList.closed}get key(){return this.entryList.startKey}async getEntry(e,r=new vs){return{result:await this._getEntry(e,r),cids:r}}async _getEntry(e,r){r.add(this);let n=this;for(;!n.isLeaf;){let i=n.entryList.find(e,this.compare);if(i===null)throw new Error("Not found");let[,a]=i;n=await this.getNode(await a.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[,s]=o;return s}async getAllEntries(e=new vs){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(s=>s._getAllEntries(e)).catch(async s=>{throw s});return Promise.all(r.map(n)).then(o=>o.flat())}}async*vis(e=new Set){let r=async s=>s.isLeaf?`Leaf [${s.entryList.entries.map(a=>`[${a.key},${JSON.stringify(a.value).replace(/"/g,"'")}]`).join(", ")}]`:`Branch [${s.entryList.entries.map(a=>`[${a.key}]`).join(", ")}]`,n=s=>s.toString().slice(0,4)+s.toString().slice(-4),o=async function*(s,i,a){let c=await s.address;if(!a.has(c)){a.add(c);let u=await r(s);yield` node [shape=ellipse fontname="Courier"]; ${n(c)} [label="${u}"];`,yield` ${n(i)} -> ${n(c)};`;for(let l of s.entryList.entries)if(l.address){let d=await l.address;try{let p=await s.getNode(d);yield*await o(p,c,a)}catch(p){yield` ${n(c)} -> ${n(d)};`,yield` node [shape=ellipse fontname="Courier"]; ${n(d)} [label="Error: ${p.message}"];`}}}};yield"digraph tree {",yield' node [shape=ellipse fontname="Courier"]; rootnode;';for await(let s of o(this,"rootnode",e))yield s;yield"}"}async getEntries(e,r=!1,n=new vs){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(([i])=>i);let s=[];for(let[i,a]of[...o.values()].reverse()){let c=this.getNode(await i.address);s.push(c.then(u=>u._getEntries(a.reverse(),!0,n)))}return s=await Promise.all(s),s.flat()}async getRangeEntries(e,r,n=new vs){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(c=>{let u=this.compare(e,c.key),l=this.compare(r,c.key);return u<=0&&l>=0});if(!o.length)return[];let s=async c=>this.getNode(await c.address).then(u=>u._getRangeEntries(e,r,n)),i=[s(o.shift())];if(!o.length)return i[0];let a=s(o.pop());for(;o.length;){let c=async u=>this.getNode(await u.address).then(async l=>l._getAllEntries(n));i.push(c(o.shift()))}return i.push(a),Promise.all(i).then(c=>c.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:s,LeafEntryClass:i}=r,{entries:a,previous:c}=this.processLeafEntries(e,o,i,r),u={...n,entries:a,NodeClass:s,distance:0},l=await t.from(u);return{nodes:l,previous:c,blocks:await Promise.all(l.map(async d=>{let p=await d.encode();return this.cache.set(d),{block:p,node:d}})),distance:0}}processLeafEntries(e,r,n,o){let s=[],i=[],a={},c=new Map;for(let{key:d,del:p,value:f}of e){let h=NC(d);p?typeof a[h]>"u"&&c.set(h,null):(a[h]={key:d,value:f},c.delete(h))}i=[...this.entryList.entries];for(let[d,[p]]of r){s.push(p);let f=NC(p.key);c.has(f)?c.set(f,d):(i[d]=new n(a[f],o),delete a[f])}let u=0;for(let[,d]of c)d!==null&&i.splice(d-u++,1);let l=Object.values(a).map(d=>new n(d,o));return i=i.concat(l).sort(({key:d},{key:p})=>o.compare(d,p)),{entries:i,previous:s}}async transactionBranch(e,r,n,o){let{BranchClass:s,BranchEntryClass:i}=r,a=0;for(let[h,[m,b]]of o){let g=this.getNode(await m.address).then(k=>k.transaction(b.reverse(),{...r,sorted:!0})).then(k=>({entry:m,keys:b,distance:a,...k}));o.set(h,g)}let c=[...this.entryList.entries],u={previous:[],blocks:[],nodes:[]};for(let[h,m]of o){let{nodes:b,previous:g,blocks:k,distance:E}=await m;a=E,c[h]=b,g.length&&(u.previous=u.previous.concat(g)),k.length&&(u.blocks=u.blocks.concat(k)),b.length&&(u.nodes=u.nodes.concat(b))}c=c.flat();let l=await this.handlePrepend(c,r,n,u,a);a++;let d=async h=>{if(h.isEntry)return h;let m=await h.encode();return u.blocks.push({block:m,node:h}),this.cache.set(h),new i(h,r)};c=await Promise.all(l.map(d));let p={...n,entries:c,NodeClass:s,distance:a},f=await t.from(p);return await Promise.all(f.map(async h=>{let m=await h.encode();u.blocks.push({block:m,node:h}),this.cache.set(h)})),u.nodes=f,{...u,distance:a}}async handlePrepend(e,r,n,o,s){let{BranchClass:i,LeafClass:a}=r,c=[],u=null;for(let l of e)if(u){let d=await this.mergeFirstLeftEntries(l,u,n,o,s);u=null;let p=d[0].address?i:a,f={...n,entries:d.sort(({key:m},{key:b})=>r.compare(m,b)),NodeClass:p,distance:s},h=await t.from(f);h[h.length-1].closed||(u=h.pop()),h.length&&(c=c.concat(h))}else!l.isEntry&&!l.closed?u=l:c.push(l);return u&&c.push(u),c}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,s){let i=n.opts,{LeafClass:a,BranchClass:c,BranchEntryClass:u}=i;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),p=async(f,h,m)=>await Promise.all(f.map(async b=>(h.blocks.push({block:await b.encode(),node:b}),this.cache.set(b),new u({key:b.key,address:await b.address},m))));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,s-1),m=l.shift();if(!m)return h;if(!m.address)throw new Error("unreachable existing leaf, no esf.address");let b=await this.getNodeFirstFromBlocks(o.blocks,await m.address);if(b.entryList.entries[0].address){if(h[0].address)return h.concat(b.entryList.entries);{let g=await t.from({...n,entries:h.sort(({key:P},{key:J})=>i.compare(P,J)),NodeClass:a,distance:s}),k=await p(g,o,i),E=await t.from({...n,entries:[...b.entryList.entries,...k,...l].sort(({key:P},{key:J})=>i.compare(P,J)),NodeClass:c,distance:s});return await p(E,o,i)}}else{let g=await d(h,b.entryList.entries),k=await t.from({...n,entries:g.sort(({key:_},{key:P})=>i.compare(_,P)),NodeClass:a,distance:s}),E=await p(k,o,i);return await d(E,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=uM(e,r),r.sorted=!0);let s={chunker:this.chunker,opts:r},i=await this.transaction(e,r);for(;i.nodes.length>1;){let a=i.nodes[0].distance+1,c=await Promise.all(i.nodes.map(async l=>{let d=await l.encode();return i.blocks.push({block:d,node:l}),this.cache.set(l),new r.BranchEntryClass(l,r)})),u=await t.from({...s,entries:c,NodeClass:o,distance:a});await Promise.all(u.map(async l=>{let d=await l.encode();this.cache.set(l),i.blocks.push({block:d,node:l})})),i.nodes=u}return i.root=i.nodes[0],n&&i.root&&await hM(this,i,e,s),i.blocks=i.blocks.map(({block:a})=>a),i}static async from({entries:e,chunker:r,NodeClass:n,distance:o,opts:s}){if(!e.every(c=>c.constructor.name===e[0].constructor.name))throw new Error("all entries must be of the same type");let i=[],a=[];for(let c of e)a.push(c),await r(c,o)&&(i.push(new co({entries:a,closed:!0})),a=[]);return a.length&&i.push(new co({entries:a,closed:!1})),i.map(c=>new n({entryList:c,chunker:r,distance:o,...s}))}},tp=class extends uo{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(s=>s.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 Nr(r),this.block}},wa=class extends tp{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}},ba=class extends tp{async encodeNode(){return{leaf:await Promise.all(this.entryList.entries.map(async r=>await r.encodeNode())),closed:this.closed}}get isLeaf(){return!0}},rp=async function*(t){let{LeafClass:e,LeafEntryClass:r,BranchClass:n,BranchEntryClass:o,list:s,chunker:i,compare:a,...c}=t;s=s.map(d=>new r(d,c)),c.compare=a;let u=await uo.from({entries:s,chunker:i,NodeClass:e,distance:0,opts:c});yield*u;let l=1;for(;u.length>1;){let d=async f=>new o({key:f.key,address:await f.address},c),p=await Promise.all(u.map(d));u=await uo.from({entries:p,chunker:i,NodeClass:n,distance:l,opts:c}),yield*u,l++}};var Ox=({bytes:t},{bytes:e})=>RC(t,e),np=class extends Es{constructor(e){super({address:e,key:e}),this.cid=e}encodeNode(){return this.cid}identity(){let e=this.cid.multihash.bytes;return Qu(e)}},op=class extends Es{async identity(){let{multihash:{bytes:e}}=await this.address;return Qu(e)}},sp=class extends wa{},ip=class extends ba{},OC=(t,e,r,n,o)=>{let s=a=>{let{value:c}=a,u={chunker:r,cache:e,block:a,getNode:i,codec:n,hasher:o,compare:Ox},l,d;if(c.leaf)l=c.leaf.map(h=>new np(h)),d=ip;else if(c.branch){let[h,m]=c.branch;u.distance=h,l=m.map(([b,g])=>new op({key:b,address:g})),d=sp}else throw new Error("Unknown block data, does not match schema");let p=new co({entries:l,closed:c.closed}),f=new d({entryList:p,...u});return e.set(f),f},i=a=>e.has(a)?e.get(a):t(a).then(c=>s(c));return i},$C=({get:t,cache:e,chunker:r,list:n,codec:o,hasher:s,sorted:i})=>{i||(n=n.sort(Ox));let a=OC(t,e,r,o,s);return rp({list:n,codec:o,hasher:s,chunker:r,getNode:a,sorted:i,compare:Ox,cache:e,LeafClass:ip,LeafEntryClass:np,BranchClass:sp,BranchEntryClass:op})},MC=({cid:t,get:e,cache:r,chunker:n,codec:o,hasher:s,...i})=>OC(e,r,n,o,s,i)(t);var FC=async function*({get:t,cids:e,hasher:r,key:n,cache:o,chunker:s,root:i}){let a=new Set,c;for(let f of e){let h=await t(f);if(!h)throw new Error("missing cid: "+f.toString());let m=await ep({...h,key:n}),b=await Nr({...m,codec:ks,hasher:r});yield b,a.add(b.cid.toString()),h.cid.equals(i)&&(c=b.cid)}if(!c)throw new Error("cids does not include root");let u=[...a].map(f=>ve.parse(f)),l;for await(let f of $C({list:u,get:t,cache:o,chunker:s,hasher:r,codec:Te})){let h=await f.block;yield h,l=h}if(!l)throw new Error("missing last block");let d=[c,l.cid];yield await Nr({value:d,codec:Te,hasher:r})},zC=async function*({root:t,get:e,key:r,cache:n,chunker:o,hasher:s}){let i=async b=>e(b).then(async g=>g?await io({...g,codec:Te,hasher:s}):void 0),a=async b=>e(b).then(async g=>g?await io({...g,codec:ks,hasher:s}):void 0),c=await i(t);if(!c)throw new Error("missing root");if(!c.bytes)throw new Error("missing bytes");let{value:[u,l]}=c,d=await e(u);if(!d)throw new Error("missing root block");let p=await MC({cid:l,get:i,cache:n,chunker:o,codec:ks,hasher:s}),{result:f}=await p.getAllEntries(),h=async b=>{if(!b)throw new Error("missing block");b.value||(b=await io({...b,codec:ks,hasher:s}));let{bytes:g,cid:k}=await Yh({...b,key:r}).catch(_=>{throw _});return await Jh({cid:k,bytes:g,hasher:s,codec:ks})},m=[];for(let{cid:b}of f)d.cid.equals(b)||m.push(a(b).then(h));yield*m,yield h(d)};var xa={has:()=>!1,get:()=>{throw new Error("Cannot ask for entries from nocache")},set:()=>{}};var jC=Xu(30);function WC(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 HC(t,e,r){let n=WC(t),o=n.buffer.slice(0,n.byteLength),s=new pt,i=[];for(let{cid:u}of r.entries())i.push(u);let a=null;for await(let u of FC({cids:i,get:r.get.bind(r),key:o,hasher:kt,chunker:jC,cache:xa,root:e}))await s.put(u.cid,u.bytes),a=u;if(!a)throw new Error("no blocks encrypted");return await ga([a.cid],s)}async function qC(t,e){let n=(await e.getRoots())[0];return await pM(n,e.get.bind(e),t)}async function pM(t,e,r){let n=WC(r),o=n.buffer.slice(0,n.byteLength),s=new pt,i=null;for await(let a of zC({root:t,get:e,key:o,hasher:kt,chunker:jC,cache:xa}))await s.put(a.cid,a.bytes),i=a;if(!i)throw new Error("no blocks decrypted");return{blocks:s,root:i.cid}}var $x="0.13.2";var VC=$x.match(/^([^.]*\.[^.]*)/);if(!VC)throw new Error("invalid version: "+$x);var Fx=VC[0],Mx=class{constructor(e){w(this,"STORAGE_VERSION",Fx);w(this,"name");this.name=e}},ka=class extends Mx{constructor(){super(...arguments);w(this,"tag","header-base")}makeHeader({car:r,key:n}){return jl({car:r,key:n})}parseHeader(r){return Wl(r)}},ap=class{constructor(e){w(this,"tag","rwal-base");w(this,"STORAGE_VERSION",Fx);w(this,"loader");w(this,"ready");w(this,"walState",{operations:[],noLoaderOps:[],fileOperations:[]});w(this,"processing");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=[],s=[...this.walState.noLoaderOps],i=Gu(5);if(r.length+n.length+s.length!==0){for(let a of s){let c=i(async()=>{let u=await this.loader.carStore.load(a.car).catch(()=>null);if(!u)throw new Error(`missing car ${a.car.toString()}`);await this.loader.remoteCarStore.save(u),this.walState.noLoaderOps=this.walState.noLoaderOps.filter(l=>l!==a)});o.push(c)}for(let a of r){let c=i(async()=>{let u=await this.loader.carStore.load(a.car).catch(()=>null);if(!u)throw new Error(`missing car ${a.car.toString()}`);await this.loader.remoteCarStore.save(u),this.walState.operations=this.walState.operations.filter(l=>l!==a)});o.push(c)}if(n.length){let a=this.loader;for(let{cid:c,public:u}of n){let l=i(async()=>{let d=await a.fileStore.load(c);await a.remoteFileStore?.save(d,{public:u}),this.walState.fileOperations=this.walState.fileOperations.filter(p=>p.cid!==c)});o.push(l)}}try{let c=(await Promise.allSettled(o)).filter(u=>u.status==="rejected");if(c.length)throw console.error("error uploading",c),c[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}},va=class{constructor(e){w(this,"tag","car-base");w(this,"STORAGE_VERSION",Fx);w(this,"loader");this.loader=e}};var Sa=class extends va{constructor(r,n,o="data"){super(r);w(this,"tag","car-browser-s3");w(this,"connection");w(this,"type");this.connection=n,this.type=o}prefix(){return`fp.${this.loader.name}.${this.STORAGE_VERSION}.${this.loader.keyId}`}async load(r){let n=await this.connection.dataDownload({type:this.type,name:this.prefix(),car:r.toString()});if(!n)throw new Error(`missing remote car ${r.toString()}`);return{cid:r,bytes:n}}async save(r,n){let o={type:this.type,name:this.prefix(),car:r.cid.toString(),size:r.bytes.length.toString()};return await this.connection.dataUpload(r.bytes,o,n)}async remove(r){throw new Error("not implemented")}},cp=class extends ka{constructor(r,n){super(r);w(this,"tag","header-browser-ls");w(this,"connection");w(this,"subscribers",new Map);this.connection=n}onLoad(r,n){let o=this.subscribers.get(r)||[];return o.push(n),this.subscribers.set(r,o),()=>{let s=this.subscribers.get(r)||[],i=s.indexOf(n);i>-1&&s.splice(i,1)}}prefix(){return`fp.${this.name}.${this.STORAGE_VERSION}`}async load(r="main"){let n=await this.connection.metaDownload({name:this.prefix(),branch:r});if(!n)return null;let o=this.dbMetasForByteHeads(n),s=this.subscribers.get(r)||[];for(let i of s)await i(o);return o}async save(r,n="main"){let o=new TextEncoder().encode(this.makeHeader(r)),s=await this.connection.metaUpload(o,{name:this.prefix(),branch:n});if(!s)return null;let i=this.dbMetasForByteHeads(s),a=this.subscribers.get(n)||[];for(let c of a)await c(i);return i}dbMetasForByteHeads(r){return r.map(n=>{let o=new TextDecoder().decode(n);return this.parseHeader(o)})}};var mM=(t,e)=>e.some(r=>t instanceof r),GC,KC;function yM(){return GC||(GC=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function gM(){return KC||(KC=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var ZC=new WeakMap,jx=new WeakMap,JC=new WeakMap,zx=new WeakMap,Hx=new WeakMap;function wM(t){let e=new Promise((r,n)=>{let o=()=>{t.removeEventListener("success",s),t.removeEventListener("error",i)},s=()=>{r(Or(t.result)),o()},i=()=>{n(t.error),o()};t.addEventListener("success",s),t.addEventListener("error",i)});return e.then(r=>{r instanceof IDBCursor&&ZC.set(r,t)}).catch(()=>{}),Hx.set(e,t),e}function bM(t){if(jx.has(t))return;let e=new Promise((r,n)=>{let o=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",i),t.removeEventListener("abort",i)},s=()=>{r(),o()},i=()=>{n(t.error||new DOMException("AbortError","AbortError")),o()};t.addEventListener("complete",s),t.addEventListener("error",i),t.addEventListener("abort",i)});jx.set(t,e)}var Wx={get(t,e,r){if(t instanceof IDBTransaction){if(e==="done")return jx.get(t);if(e==="objectStoreNames")return t.objectStoreNames||JC.get(t);if(e==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Or(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 QC(t){Wx=t(Wx)}function xM(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...r){let n=t.call(up(this),e,...r);return JC.set(n,e.sort?e.sort():[e]),Or(n)}:gM().includes(t)?function(...e){return t.apply(up(this),e),Or(ZC.get(this))}:function(...e){return Or(t.apply(up(this),e))}}function kM(t){return typeof t=="function"?xM(t):(t instanceof IDBTransaction&&bM(t),mM(t,yM())?new Proxy(t,Wx):t)}function Or(t){if(t instanceof IDBRequest)return wM(t);if(zx.has(t))return zx.get(t);let e=kM(t);return e!==t&&(zx.set(t,e),Hx.set(e,t)),e}var up=t=>Hx.get(t);function YC(t,e,{blocked:r,upgrade:n,blocking:o,terminated:s}={}){let i=indexedDB.open(t,e),a=Or(i);return n&&i.addEventListener("upgradeneeded",c=>{n(Or(i.result),c.oldVersion,c.newVersion,Or(i.transaction),c)}),r&&i.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),o&&c.addEventListener("versionchange",u=>o(u.oldVersion,u.newVersion,u))}).catch(()=>{}),a}var vM=["get","getKey","getAll","getAllKeys","count"],SM=["put","add","delete","clear"],qx=new Map;function XC(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(qx.get(e))return qx.get(e);let r=e.replace(/FromIndex$/,""),n=e!==r,o=SM.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||vM.includes(r)))return;let s=async function(i,...a){let c=this.transaction(i,o?"readwrite":"readonly"),u=c.store;return n&&(u=u.index(a.shift())),(await Promise.all([u[r](...a),o&&c.done]))[0]};return qx.set(e,s),s}QC(t=>({...t,get:(e,r,n)=>XC(e,r)||t.get(e,r,n),has:(e,r)=>!!XC(e,r)||t.has(e,r)}));var Ea=class extends va{constructor(){super(...arguments);w(this,"tag","car-browser-idb");w(this,"idb",null)}async _withDB(r){if(!this.idb){let n=`fp.${this.STORAGE_VERSION}.${this.loader.keyId}.${this.loader.name}`;this.idb=await YC(n,1,{upgrade(o){o.createObjectStore("cars")}})}return await r(this.idb)}async load(r){return await this._withDB(async n=>{let s=await n.transaction(["cars"],"readonly").objectStore("cars").get(r.toString());if(!s)throw new Error(`missing idb block ${r.toString()}`);return{cid:r,bytes:s}})}async save(r){return await this._withDB(async n=>{let o=n.transaction(["cars"],"readwrite");return await o.objectStore("cars").put(r.bytes,r.cid.toString()),await o.done})}async remove(r){return await this._withDB(async n=>{let o=n.transaction(["cars"],"readwrite");return await o.objectStore("cars").delete(r.toString()),await o.done})}},lp=class extends ap{constructor(){super(...arguments);w(this,"tag","wal-browser-ls")}headerKey(r){return`fp.${this.STORAGE_VERSION}.wal.${this.loader.name}.${r}`}async load(r="main"){try{let n=localStorage.getItem(this.headerKey(r));return n?Wl(n):null}catch{return null}}async save(r,n="main"){try{let o=jl(r);localStorage.setItem(this.headerKey(n),o)}catch{}}},dp=class extends ka{constructor(){super(...arguments);w(this,"tag","header-browser-ls")}headerKey(r){return`fp.${this.STORAGE_VERSION}.meta.${this.name}.${r}`}async load(r="main"){try{let n=localStorage.getItem(this.headerKey(r));return n?[this.parseHeader(n)]:null}catch{return null}}async save(r,n="main"){try{let o=this.headerKey(n),s=this.makeHeader(r);return localStorage.setItem(o,s),null}catch{return null}}};function tI(t,e){return t.some(r=>r.equals(e))}function eI(t,e=[]){let r=new Map;for(let n of t)tI(e,n)||r.set(n.toString(),n);return[...r.values()]}function EM(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var _a=class{constructor(e,r){w(this,"name");w(this,"opts",{});w(this,"remoteMetaLoading");w(this,"remoteMetaStore");w(this,"remoteCarStore");w(this,"remoteWAL");w(this,"metaStore");w(this,"carStore");w(this,"carLog",[]);w(this,"carReaders",new Map);w(this,"ready");w(this,"key");w(this,"keyId");w(this,"getBlockCache",new Map);w(this,"committing");this.name=e,this.opts=r||this.opts,this.ready=this.initializeStores().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)})}_connectRemoteMeta(e){let r=new cp(this.name,e);return r.onLoad("main",async n=>{n&&await this.handleDbMetasFromStore(n)}),this.remoteMetaStore=r,e}_connectRemoteStorage(e){return this.remoteCarStore=new Sa(this,e),e}connectRemote(e,r){return e.loader=this,this._connectRemoteMeta(e),this._connectRemoteStorage(r||e),this.remoteMetaLoading=this.remoteMetaStore.load("main").then(()=>{}),e.loaded=Promise.all([this.ready,this.remoteMetaLoading]).then(()=>{this.remoteWAL?._process()}),e}async snapToCar(e){await this.ready,typeof e=="string"&&(e=ve.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),tI(this.carLog,e.car))return;let r=await this.loadCarHeaderFromMeta(e);await this.getMoreReaders(r.cars),this.carLog=[...eI([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 PC(r)}async _getKey(){return this.key?this.key:(this.opts.public||(Qh()?await this.setKey(EM(Xh(32))):console.warn("missing crypto module, using public mode")),this.key)}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),s=[];if(o.files)s=o.files;else{let l=await BC(o);await e.put(l.cid,l.bytes),s=[l.cid]}let i=n.public?null:await this._getKey(),{cid:a,bytes:c}=i?await HC(i,s[0],e):await ga(s,e);if(Vx(r))return await this.fileStore.save({cid:a,bytes:c}),await this.remoteWAL.enqueueFile(a,n.public),a;await this.carStore.save({cid:a,bytes:c});let u={car:a,key:i||null};if(await this.remoteWAL.enqueue(u,n),await this.metaStore.save(u),n.compact){let l=o;this.carLog=[...eI([a,...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(a);return a}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 s=await this.loadCar(o);if(!s)throw new Error(`missing car reader ${o.toString()}`);let i=await s.get(e);if(i)return i;throw new Error(`block not in reader: ${e.toString()}`)})).catch(()=>{});return n&&this.getBlockCache.set(r,n),n}async initializeStores(){this.metaStore=new dp(this.name),this.carStore=new Ea(this),this.remoteWAL=new lp(this)}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 s=e.toString();return this.carReaders.has(s)||this.carReaders.set(s,(async()=>{let i=null;try{i=await r.load(e)}catch{if(n){let l=await n.load(e);l&&(await r.save(l),i=l)}}if(!i)throw new Error(`missing car file ${s}`);let a=await hs.fromBytes(i.bytes),c=o?Promise.resolve(a):this.ensureDecryptedReader(a);return this.carReaders.set(s,c),c})().catch(i=>{throw this.carReaders.delete(s),i})),this.carReaders.get(s)}async ensureDecryptedReader(e){let r=await this._getKey();if(!r)return e;let{blocks:n,root:o}=await qC(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=Qh();if(!r)throw new Error("missing crypto module");let n=r.subtle,s=new TextEncoder().encode(e),i=await n.digest("SHA-256",s),a=Array.from(new Uint8Array(i));this.keyId=a.map(c=>c.toString(16).padStart(2,"0")).join("")}async getMoreReaders(e){let r=Gu(5),n=e.filter(o=>!this.carReaders.has(o.toString()));await Promise.all(n.map(o=>r(()=>this.loadCar(o))))}};w(_a,"defaultHeader");var Aa=De(aI(),1);var fp=class extends Es{async identity(){let e=await this.codec.encode(await this.encodeNode()),r=await this.hasher.encode(e);return Qu(r)}},_s=class extends fp{constructor(e,r){super(e,r),this.value=e.value}encodeNode(){return[this.key,this.value]}},As=class extends fp{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]}},cI=async(t,e)=>{let{result:r,cids:n}=await t.getEntry(e);return{result:r.value,cids:n}},uI=async(t,e)=>{let{result:r,cids:n}=await t.getEntries(e);return{result:r.map(o=>o.value),cids:n}},Ds=class extends ba{get(e){return cI(this,e)}getMany(e){return uI(this,e)}bulk(e,r={},n=!0){return super.bulk(e,{...lI,...r},n)}},Ts=class extends wa{get(e){return cI(this,e)}getMany(e){return uI(this,e)}bulk(e,r={},n=!0){return super.bulk(e,{...lI,...r},n)}},lI={LeafClass:Ds,LeafEntryClass:_s,BranchClass:Ts,BranchEntryClass:As},dI=(t,e,r,n,o,s,i)=>{let a=i.LeafClass||Ds,c=i.LeafEntryClass||_s,u=i.BranchClass||Ts,l=i.BranchEntryClass||As,d=async f=>e.has(f)?e.get(f):t(f).then(h=>p(h)),p=PM({chunker:r,cache:e,getNode:d,codec:n,hasher:o,compare:s,LeafEntryClass:c,LeafClass:a,BranchEntryClass:l,BranchClass:u});return d},fI=({get:t,cache:e,chunker:r,list:n,codec:o,hasher:s,sorted:i,compare:a,...c})=>{i||(n=n.sort(({key:d},{key:p})=>a(d,p)));let u=dI(t,e,r,o,s,a,c),l={list:n,codec:o,hasher:s,chunker:r,getNode:u,sorted:i,compare:a,cache:e,LeafClass:c.LeafClass||Ds,LeafEntryClass:c.LeafEntryClass||_s,BranchClass:c.BranchClass||Ts,BranchEntryClass:c.BranchEntryClass||As};return rp(l)},hI=({cid:t,get:e,cache:r,chunker:n,codec:o,hasher:s,compare:i,...a})=>dI(e,r,n,o,s,i,a)(t);function PM({chunker:t,cache:e,getNode:r,codec:n,hasher:o,compare:s,LeafEntryClass:i,LeafClass:a,BranchEntryClass:c,BranchClass:u}){let l={codec:n,hasher:o};return d=>{let{value:p}=d,f={chunker:t,cache:e,block:d,getNode:r,codec:n,hasher:o,compare:s},h,m;if(p.leaf)h=p.leaf.map(([k,E])=>new i({key:k,value:E},l)),m=a;else if(p.branch){let[k,E]=p.branch;f.distance=k,h=E.map(([_,P])=>new c({key:_,address:P},l)),m=u}else throw new Error("Unknown block data, does not match schema");let b=new co({entries:h,closed:p.closed}),g=new m({entryList:b,...f});return e.set(g),g}}var LM=(t,e)=>{let[r,n]=t,[o,s]=e,i=Ss(r,o);return i!==0?i:UM(n,s)},UM=(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)?Ss(t,e):1},pI=async(t,e)=>{let r=[e,NaN],n=[e,1/0],{result:o,cids:s}=await t.getRangeEntries(r,n);return{result:o.map(i=>{let[a,c]=i.key;return{id:c,key:a,row:i.value}}),cids:s}},mI=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(i=>{let[a,c]=i.key;return{id:c,key:a,row:i.value}}),cids:o}},Kx=class extends Ds{get(e){return pI(this,e)}range(e,r){return mI(this,e,r)}bulk(e,r={},n=!0){return super.bulk(e,{...Jx,...r},n)}},Zx=class extends Ts{get(e){return pI(this,e)}range(e,r){return mI(this,e,r)}bulk(e,r={},n=!0){return super.bulk(e,{...Jx,...r},n)}},RM=Kx,NM=Zx,Jx={LeafClass:RM,BranchClass:NM,LeafEntryClass:_s,BranchEntryClass:As},yI={...Jx,compare:LM},gI=t=>(t={...yI,...t},fI(t)),Qx=t=>(t={...yI,...t},hI(t));var Cs=class{constructor(){w(this,"cid",null);w(this,"root",null)}},$M=(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:Ss(t,e)},MM=(t,e)=>{let[r,n]=t,[o,s]=e,i=Ss(r,o);return i!==0?i:$M(n,s)},Yx={cache:xa,chunker:Xu(30),codec:Te,hasher:kt,compare:MM},e0={cache:xa,chunker:Xu(30),codec:Te,hasher:kt,compare:Ss};function wI(t,e){let r=[];return t.forEach(({key:n,value:o,del:s})=>{if(s||!o)return;let i=!1,a=e({_id:n,...o},(c,u)=>{i=!0,!(typeof c>"u")&&r.push({key:[Aa.default.encode(c),n],value:u||null})});!i&&a&&r.push({key:[Aa.default.encode(a),n],value:null})}),r}function Xx(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 Jh({cid:n,bytes:o,hasher:kt,codec:Te})}}async function t0(t,e,r,n){if(!r.length)return e;if(!e.root)if(e.cid)e.root=await Qx({cid:e.cid,get:Xx(t),...n});else{let i=null,a=null;for await(let c of await gI({get:Xx(t),list:r,...n})){let u=await c.block;await t.put(u.cid,u.bytes),i=u,a=c}if(!a||!i)throw new Error("failed to create index");return{root:a,cid:i.cid}}let{root:o,blocks:s}=await e.root.bulk(r);if(o){for await(let i of s)await t.put(i.cid,i.bytes);return{root:o,cid:(await o.block).cid}}else return{root:null,cid:null}}async function r0(t,e,r){return await Qx({cid:e,get:Xx(t),...r})}async function Is(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),s=o?{_id:n.id,...o.doc}:null;return{...n,doc:s}}))),{rows:e.result.map(n=>(n.key=Aa.default.decode(n.key),n.row&&!n.value&&(n.value=n.row,delete n.row),n))}}function n0(t){return t.map(e=>Aa.default.encode(e))}function o0(t){return Aa.default.encode(t)}function Da({_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 hp(t,e,r,n);t.indexers.set(e,o)}return t.indexers.get(e)}var hp=class{constructor(e,r,n,o){w(this,"blocks");w(this,"crdt");w(this,"name",null);w(this,"mapFn",null);w(this,"mapFnString","");w(this,"byKey",new Cs);w(this,"byId",new Cs);w(this,"indexHead");w(this,"includeDocsDefault",!1);w(this,"initError",null);w(this,"ready");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(s=>s.toString()).join()!==n.head.map(s=>s.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=FM(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 Is(this.crdt,{result:[]},e);if(this.includeDocsDefault&&e.includeDocs===void 0&&(e.includeDocs=!0),e.range){let{result:o,...s}=await this.byKey.root.range(...n0(e.range));return await Is(this.crdt,{result:o,...s},e)}if(e.key){let o=o0(e.key);return await Is(this.crdt,await this.byKey.root.get(o),e)}if(Array.isArray(e.keys))return{rows:(await Promise.all(e.keys.map(async s=>{let i=o0(s);return(await Is(this.crdt,await this.byKey.root.get(i),e)).rows}))).flat()};if(e.prefix){Array.isArray(e.prefix)||(e.prefix=[e.prefix]);let o=[...e.prefix,NaN],s=[...e.prefix,1/0],i=n0([o,s]);return await Is(this.crdt,await this.byKey.root.range(...i),e)}let{result:r,...n}=await this.byKey.root.getAllEntries();return await Is(this.crdt,{result:r.map(({key:[o,s],value:i})=>({key:o,id:s,value:i})),...n},e)}_resetIndex(){this.byId=new Cs,this.byKey=new Cs,this.indexHead=void 0}async _hydrateIndex(){this.byId.root&&this.byKey.root||!this.byId.cid||!this.byKey.cid||(this.byId.root=await r0(this.blocks,this.byId.cid,e0),this.byKey.root=await r0(this.blocks,this.byKey.cid,Yx))}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 c=e.map(({key:l})=>l),{result:u}=await this.byId.root.getMany(c);n=u.map(l=>({key:l,del:!0})),o=u.map(l=>({key:l[1],del:!0}))}let s=wI(e,this.mapFn),i=s.map(({key:c})=>({key:c[1],value:c})),a=new Map;for(let[c,u]of this.crdt.indexers)u.indexHead&&a.set(c,{byId:u.byId.cid,byKey:u.byKey.cid,head:u.indexHead,map:u.mapFnString,name:u.name});return await this.blocks.transaction(async c=>(this.byId=await t0(c,this.byId,o.concat(i),e0),this.byKey=await t0(c,this.byKey,n.concat(s),Yx),this.indexHead=r,{byId:this.byId.cid,byKey:this.byKey.cid,head:r,map:this.mapFnString,name:this.name}),a)}};function FM(t){return e=>{if(e[t])return e[t]}}var yp=class yp extends _a{constructor(r,n,o){super(r,o);w(this,"crdt");w(this,"defaultHeader",yp.defaultHeader);this.crdt=n}async _applyCarHeader(r){for(let[n,o]of Object.entries(r.indexes))Da({_crdt:this.crdt},n,void 0,o)}makeCarHeader({indexes:r},n,o=!1){return o?{indexes:r,cars:[],compact:n}:{indexes:r,cars:n,compact:[]}}};w(yp,"defaultHeader",{cars:[],compact:[],indexes:new Map});var pp=yp,gp=class gp extends _a{constructor(r,n,o){super(r,o);w(this,"defaultHeader",gp.defaultHeader);w(this,"clock");w(this,"remoteFileStore");w(this,"fileStore");this.clock=n}async initializeStores(){await super.initializeStores(),this.fileStore=new Ea(this)}_connectRemoteStorage(r){return super._connectRemoteStorage(r),this.remoteFileStore=new Sa(this,r,"file"),r}async loadFileCar(r,n=!1){if(!this.fileStore)throw new Error("missing fileStore");return await this.storesLoadCar(r,this.fileStore,this.remoteFileStore,n)}async _applyCarHeader(r,n=!1){n?await this.clock.applyHead(null,r.head,this.clock.head):await this.clock.applyHead(null,r.head,[])}makeCarHeader(r,n,o=!1){if(Vx(r)){let s=[];for(let[,i]of Object.entries(r.files))s.push(i.cid);return{files:s}}else{let{head:s}=r;return o?{head:s,cars:[],compact:n}:{head:s,cars:n,compact:[]}}}};w(gp,"defaultHeader",{cars:[],compact:[],head:[]});var mp=gp;function Vx(t){return t&&t.files!==void 0}var lo=class extends pt{constructor(r){super();w(this,"parent");this.parent=r}async get(r){return this.parent.get(r)}async superGet(r){return super.get(r)}},wp=class{constructor(e,r,n){w(this,"ready");w(this,"name",null);w(this,"loader",null);w(this,"opts",{});w(this,"transactions",new Set);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 lo(this);this.transactions.add(n);let o=await e(n),{car:s,done:i}=await r(n,o);return s?{...i,car:s}:i}},bp=class extends wp{constructor(e,r,n){e?super(e,new pp(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}))}},xp=class extends wp{constructor(e,r,n){e?super(e,new mp(e,r,n),n):super(null)}async transaction(e,r,n={noLoader:!1}){return this.executeTransaction(e,async(o,s)=>({car:await this.loader?.commit(o,s,n),done:s}))}},kp=class{constructor(e){w(this,"blocks");w(this,"loader",null);w(this,"cids",new Set);this.blocks=e,this.loader=e.loader}async get(e){return this.cids.add(e),await this.blocks.get(e)}};async function Yu(t,e,r){let n=new $r(t),o=new Map(e.map(i=>[i.toString(),i]));if(o.has(r.toString()))return e;let s=!1;for(let i of e)await bI(n,r,i)&&(o.delete(i.toString()),o.set(r.toString(),r),s=!0);if(s)return[...o.values()];for(let i of e)if(await bI(n,i,r))return e;return e.concat(r)}var Bs=class extends Qt{constructor({cid:e,value:r,bytes:n,prefix:o}){super({cid:e,value:r,bytes:n}),this.prefix=o}static create(e,r){return zM({data:e,parents:r??[]})}},$r=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 el(r.bytes)}};async function zM(t){let{cid:e,bytes:r}=await xh({value:t,codec:Te,hasher:ue});return new Qt({cid:e,value:t,bytes:r})}async function el(t){let{cid:e,value:r}=await kh({bytes:t,codec:Te,hasher:ue});return new Qt({cid:e,value:r,bytes:t})}async function bI(t,e,r){if(e.toString()===r.toString())return!0;let[{value:n},{value:o}]=await Promise.all([t.get(e),t.get(r)]),s=[...n.parents],i=new Set;for(;s.length;){let a=s.shift();if(!a)break;if(a.toString()===r.toString())return!0;if(o.parents.some(u=>a.toString()===u.toString())||i.has(a.toString()))continue;i.add(a.toString());let{value:c}=await t.get(a);s.push(...c.parents)}return!1}async function*s0(t,e,r={}){let n=r.renderNodeLabel??(c=>jM(c.cid)),o=new $r(t);yield"digraph clock {",yield' node [shape=point fontname="Courier"]; head;';let s=await Promise.all(e.map(c=>o.get(c))),i=[],a=new Set;for(let c of s){a.add(c.cid.toString()),yield` node [shape=oval fontname="Courier"]; ${c.cid} [label="${n(c)}"];`,yield` head -> ${c.cid};`;for(let u of c.value.parents)yield` ${c.cid} -> ${u};`;i.push(...c.value.parents)}for(;i.length;){let c=i.shift();if(!c)break;if(a.has(c.toString()))continue;a.add(c.toString());let u=await o.get(c);yield` node [shape=oval]; ${c} [label="${n(u)}" fontname="Courier"];`;for(let l of u.value.parents)yield` ${c} -> ${l};`;i.push(...u.value.parents)}yield"}"}var jM=t=>`${String(t).slice(0,4)}..${String(t).slice(-4)}`;var Ps=class extends Qt{constructor({cid:e,value:r,bytes:n,prefix:o}){super({cid:e,value:r,bytes:n}),this.prefix=o}static create(){return Mr([])}};async function Mr(t,e){let{cid:r,bytes:n}=await xh({value:t,codec:Te,hasher:ue});return new Ps({cid:r,value:t,bytes:n,prefix:e??""})}async function xI(t,e){let{cid:r,value:n}=await kh({bytes:t,codec:Te,hasher:ue});if(!Array.isArray(n))throw new Error(`invalid shard: ${r}`);return new Ps({cid:r,value:n,bytes:t,prefix:e??""})}var Ls=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 xI(n.bytes,r)}};function i0(t,e){if(!t.length)return[e];let r=[];for(let[n,[o,s]]of t.entries()){if(e[0]===o){if(Array.isArray(e[1]))Array.isArray(s)&&s[1]!=null&&e[1][1]==null?r.push([o,[e[1][0],s[1]]]):r.push(e);else{let i=Array.isArray(s)?[o,[s[0],e[1]]]:e;r.push(i)}for(let i=n+1;i<t.length;i++)r.push(t[i]);return r}if(n===0&&e[0]<o){r.push(e);for(let i=n;i<t.length;i++)r.push(t[i]);return r}if(n>0&&e[0]>t[n-1][0]&&e[0]<o){r.push(e);for(let i=n;i<t.length;i++)r.push(t[i]);return r}r.push([o,s])}return r.push(e),r}function kI(t,e){let r=t.findIndex(([s])=>e===s);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 s=t.filter(i=>i[0].startsWith(o));if(s.length>1)return{prefix:o,matches:s};if(o=o.slice(0,-1),!o.length)break}if(n++,n>=t.length&&(n=0),n===r)return}}var vp=64,HM=512*1024;async function tl(t,e,r,n,o={}){let s=new Ls(t),i=await s.get(e),a=await Sp(s,i,r),c=a[a.length-1],u=r.slice(c.prefix.length),l=[u,n],d=[];if(u.length>vp){let h=Array.from(Array(Math.ceil(u.length/vp)),(b,g)=>{let k=g*vp;return{prefix:c.prefix+u.slice(0,k),skey:u.slice(k,k+vp)}}),m=await Mr([[h[h.length-1].skey,n]],h[h.length-1].prefix);d.push(m);for(let b=h.length-2;b>0;b--)m=await Mr([[h[b].skey,[m.cid]]],h[b].prefix),d.push(m);l=[h[0].skey,[m.cid]]}let p=i0(c.value,l),f=await Mr(p,c.prefix);if(f.bytes.length>(o.maxShardSize??HM)){let h=kI(p,l[0]);if(!h)throw new Error("shard limit reached");let{prefix:m,matches:b}=h,g=await Mr(b.filter(([_])=>_!==m).map(([_,P])=>[_.slice(m.length),P]),c.prefix+m);d.push(g);let k,E=b.find(([_])=>_===m);if(E){if(Array.isArray(E[1]))throw new Error(`expected "${m}" to be a shard value but found a shard link`);k=[g.cid,E[1]]}else k=[g.cid];p=p.filter(_=>b.every(P=>_[0]!==P[0])),p=i0(p,[m,k]),f=await Mr(p,c.prefix)}d.push(f);for(let h=a.length-2;h>=0;h--){let m=a[h],b=f.prefix.slice(m.prefix.length),g=m.value.map(k=>{let[E,_]=k;if(E!==b)return k;if(!Array.isArray(_))throw new Error(`"${b}" is not a shard link in: ${m.cid}`);return _[1]==null?[E,[f.cid]]:[E,[f.cid,_[1]]]});f=await Mr(g,m.prefix),d.push(f)}return{root:d[d.length-1].cid,additions:d,removals:a}}async function vI(t,e,r){let n=new Ls(t),o=await n.get(e),s=await Sp(n,o,r),i=s[s.length-1],a=r.slice(i.prefix.length),c=i.value.find(([u])=>u===a);if(c)return Array.isArray(c[1])?c[1][1]:c[1]}async function a0(t,e,r){let n=new Ls(t),o=await n.get(e),s=await Sp(n,o,r),i=s[s.length-1],a=r.slice(i.prefix.length),c=i.value.findIndex(([h])=>h===a);if(c===-1)return{root:e,additions:[],removals:[]};let u=i.value[c];if(Array.isArray(u[1])&&u[1][1]==null)return{root:e,additions:[],removals:[]};let l=[],d=[...s],p=[...i.value];if(Array.isArray(u[1]))p[c]=[u[0],[u[1][0]]];else for(p.splice(c,1);!p.length;){let h=s[s.length-1],m=s[s.length-2];if(!m)break;s.pop(),p=m.value.filter(b=>Array.isArray(b[1])?b[1][0].toString()!==h.cid.toString():!0)}let f=await Mr(p,s[s.length-1].prefix);l.push(f);for(let h=s.length-2;h>=0;h--){let m=s[h],b=f.prefix.slice(m.prefix.length),g=m.value.map(k=>{let[E,_]=k;if(E!==b)return k;if(!Array.isArray(_))throw new Error(`"${b}" is not a shard link in: ${m.cid}`);return _[1]==null?[E,[f.cid]]:[E,[f.cid,_[1]]]});f=await Mr(g,m.prefix),l.push(f)}return{root:l[l.length-1].cid,additions:l,removals:d}}async function*SI(t,e,r={}){let{prefix:n}=r,o=new Ls(t),s=await o.get(e);yield*async function*i(a){for(let c of a.value){let u=a.prefix+c[0];if(Array.isArray(c[1])){if(c[1][1]&&(!n||n&&u.startsWith(n))&&(yield[u,c[1][1]]),n&&(n.length<=u.length&&!u.startsWith(n)||n.length>u.length&&!n.startsWith(u)))continue;yield*i(await o.get(c[1][0],u))}else{if(n&&!u.startsWith(n))continue;yield[u,c[1]]}}}(s)}async function Sp(t,e,r){for(let[n,o]of e.value){if(r===n)return[e];if(r.startsWith(n)&&Array.isArray(o)){let s=await Sp(t,await t.get(o[0],e.prefix+n),r.slice(n.length));return[e,...s]}}return[e]}async function EI(t,e,r,n,o){let s=new pt;if(t=new ws(s,t),!e.length){let g=await Ps.create();s.putSync(g.cid,g.bytes);let k=await tl(t,g.cid,r,n,o),E={type:"put",root:k.root,key:r,value:n},_=await Bs.create(E,e);return e=await Yu(t,e,_.cid),{root:k.root,additions:[g,...k.additions],removals:k.removals,head:e,event:_}}let i=new $r(t),a=await u0(i,e);if(!a)throw new Error("failed to find common ancestor event");let c=await i.get(a),{root:u}=c.value.data,l=await AI(i,e,a),d=new Map,p=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 k=g.data.type==="put"?await tl(t,u,g.data.key,g.data.value):await a0(t,u,g.data.key);u=k.root;for(let E of k.additions)s.putSync(E.cid,E.bytes),d.set(E.cid.toString(),E);for(let E of k.removals)p.set(E.cid.toString(),E)}let f=await tl(t,u,r,n,o);for(let g of f.additions)s.putSync(g.cid,g.bytes),d.set(g.cid.toString(),g);for(let g of f.removals)p.set(g.cid.toString(),g);let h={type:"put",root:f.root,key:r,value:n},m=await Bs.create(h,e);s.putSync(m.cid,m.bytes),e=await Yu(t,e,m.cid);let b=f.root.toString();for(let g of p.keys())d.has(g)&&g!==b&&(d.delete(g),p.delete(g));return{root:f.root,additions:[...d.values()],removals:[...p.values()],head:e,event:m}}async function Ta(t,e){if(!e.length)throw new Error("cannot determine root of headless clock");let r=new pt;t=new ws(r,t);let n=new $r(t);if(e.length===1){let d=await n.get(e[0]),{root:p}=d.value.data;return{root:p,additions:[],removals:[]}}let o=await u0(n,e);if(!o)throw new Error("failed to find common ancestor event");let s=await n.get(o),{root:i}=s.value.data,a=await AI(n,e,o),c=new Map,u=new Map;for(let{value:d}of a){if(!["put","del"].includes(d.data.type))throw new Error(`unknown event type: ${d.data.type}`);let p=d.data.type==="put"?await tl(t,i,d.data.key,d.data.value):await a0(t,i,d.data.key);i=p.root;for(let f of p.additions)r.putSync(f.cid,f.bytes),c.set(f.cid.toString(),f);for(let f of p.removals)u.set(f.cid.toString(),f)}let l=i.toString();for(let d of u.keys())c.has(d)&&d!==l&&(c.delete(d),u.delete(d));return{root:i,additions:[...c.values()],removals:[...u.values()]}}async function _I(t,e,r){if(!e.length)return;let n=await Ta(t,e);return n.additions.length&&(t=new ws(new pt(n.additions),t)),vI(t,n.root,r)}async function*c0(t,e,r){if(!e.length)return;let n=await Ta(t,e);n.additions.length&&(t=new ws(new pt(n.additions),t)),yield*SI(t,n.root,r)}async function u0(t,e){if(!e.length)return;let r=e.map(n=>[n]);for(;;){let n=!1;for(let o of r){let s=await VM(t,o[o.length-1]);if(!s)continue;n=!0,o.push(s);let i=GM(r);if(i)return i}if(!n)return}}async function VM(t,e){let{value:r}=await t.get(e);return r.parents.length?r.parents.length===1?r.parents[0]:u0(t,r.parents):e}function GM(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(s=>String(s)===String(r)),!n))break;if(n)return r}}async function AI(t,e,r){if(e.length===1&&String(e[0])===String(r))return[];let n=new Map,o=await Promise.all(e.map(i=>DI(t,i,r)));for(let i of o)for(let{event:a,depth:c}of i){let u=n.get(a.cid.toString());u?u.weight+=c:n.set(a.cid.toString(),{event:a,weight:c})}let s=new Map;for(let{event:i,weight:a}of n.values()){let c=s.get(a);c?c.push(i):s.set(a,[i])}return Array.from(s).sort((i,a)=>a[0]-i[0]).flatMap(([,i])=>i.sort((a,c)=>String(a.cid)<String(c.cid)?-1:1))}async function DI(t,e,r,n=0){let o=await t.get(e),s=[{event:o,depth:n}],{parents:i}=o.value;if(i.length===1&&String(i[0])===String(r))return s;let a=await Promise.all(i.map(c=>DI(t,c,r,n+1)));return s.concat(...a)}var Bp=De(Fr(),1);function ZM(t){return t[Symbol.asyncIterator]!=null}function JM(t){if(ZM(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 II=JM;var hB=De(Fr(),1);var BI=0,QM="identity",PI=jt,XM=t=>xo(BI,PI(t)),LI={code:BI,name:QM,encode:PI,digest:XM};var UI=De(Fr(),1);var YM=async(t,e,r,n,o,s,i,a)=>{let c=await i.get(t,a),u=Ge(c),l=u,d=r;for(;n.length>0;){let p=n[0];if(p in l){n.shift(),d=`${d}/${p}`;let f=ve.asCID(l[p]);if(f!=null)return{entry:{type:"object",name:e,path:r,cid:t,node:c,depth:s,size:BigInt(c.length),content:async function*(){yield u}},next:{cid:f,name:p,path:d,toResolve:n}};l=l[p]}else throw(0,UI.default)(new Error(`No property named ${p} found in cbor node ${t}`),"ERR_NO_PROP")}return{entry:{type:"object",name:e,path:r,cid:t,node:c,depth:s,size:BigInt(c.length),content:async function*(){yield u}}}},RI=YM;var NI=De(Fr(),1);var mt=class extends Event{constructor(e,r){super(e),this.detail=r}};function eF(t,e,r,n){let o=BigInt(t.length),s=BigInt(e+o);return r>=s||n<e?new Uint8Array(0):(n>=e&&n<s&&(t=t.subarray(0,Number(n-e))),r>=e&&r<s&&(t=t.subarray(Number(r-e))),t)}var Us=eF;var rl=De(Fr(),1),tF=(t,e=0,r=t)=>{let n=BigInt(t),o=BigInt(e??0),s=BigInt(r);if(s!==n&&(s=o+s),s>n&&(s=n),o<0n)throw(0,rl.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(o>n)throw(0,rl.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(s<0n)throw(0,rl.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(s>n)throw(0,rl.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:o,end:s}},Ca=tF;var rF=t=>{async function*e(r={}){let{start:n,end:o}=Ca(t.length,r.offset,r.length),s=Us(t,0n,n,o);r.onProgress?.(new mt("unixfs:exporter:progress:identity",{bytesRead:BigInt(s.byteLength),totalBytes:o-n,fileSize:BigInt(t.byteLength)})),yield s}return e},nF=async(t,e,r,n,o,s,i,a)=>{if(n.length>0)throw(0,NI.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let c=Rl(t.multihash.bytes);return{entry:{type:"identity",name:e,path:r,cid:t,content:rF(c.digest),depth:s,size:BigInt(c.digest.length),node:c.digest}}},OI=nF;var $I=De(Fr(),1);var oF=t=>{async function*e(r={}){let{start:n,end:o}=Ca(t.length,r.offset,r.length),s=Us(t,0n,n,o);r.onProgress?.(new mt("unixfs:exporter:progress:raw",{bytesRead:BigInt(s.byteLength),totalBytes:o-n,fileSize:BigInt(t.byteLength)})),yield s}return e},sF=async(t,e,r,n,o,s,i,a)=>{if(n.length>0)throw(0,$I.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let c=await i.get(t,a);return{entry:{type:"raw",name:e,path:r,cid:t,content:oF(c),depth:s,size:BigInt(c.length),node:c}}},MI=sF;var il=De(Fr(),1);var m0=De(Fr(),1);var l0=De(Kf(),1),FI=De(kb(),1),zI=De(sn(),1),d0=De(Vf(),1),jI=De(wb(),1);function iF(){zI.default._configure(),l0.default._configure(FI.default),d0.default._configure(jI.default)}iF();var WI=["uint64","int64","sint64","fixed64","sfixed64"];function aF(t){for(let e of WI){if(t[e]==null)continue;let r=t[e];t[e]=function(){return BigInt(r.call(this).toString())}}return t}function f0(t){return aF(new l0.default(t))}function cF(t){for(let e of WI){if(t[e]==null)continue;let r=t[e];t[e]=function(n){return r.call(this,n.toString())}}return t}function h0(){return cF(d0.default.create())}function nl(t,e){let r=f0(t instanceof Uint8Array?t:t.subarray());return e.decode(r)}function ol(t,e){let r=h0();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var Ia;(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"})(Ia||(Ia={}));function Ep(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function p0(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}let r=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return Ep("enum",Ia.VARINT,r,n)}function sl(t,e){return Ep("message",Ia.LENGTH_DELIMITED,t,e)}var mr;(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=()=>p0(r)}(e=t.DataType||(t.DataType={}));let n;t.codec=()=>(n==null&&(n=sl((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.Type!=null&&(s.uint32(8),t.DataType.codec().encode(o.Type,s)),o.Data!=null&&(s.uint32(18),s.bytes(o.Data)),o.filesize!=null&&(s.uint32(24),s.uint64(o.filesize)),o.blocksizes!=null)for(let a of o.blocksizes)s.uint32(32),s.uint64(a);o.hashType!=null&&(s.uint32(40),s.uint64(o.hashType)),o.fanout!=null&&(s.uint32(48),s.uint64(o.fanout)),o.mode!=null&&(s.uint32(56),s.uint32(o.mode)),o.mtime!=null&&(s.uint32(66),_p.codec().encode(o.mtime,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={blocksizes:[]},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.Type=t.DataType.codec().decode(o);break;case 2:i.Data=o.bytes();break;case 3:i.filesize=o.uint64();break;case 4:i.blocksizes.push(o.uint64());break;case 5:i.hashType=o.uint64();break;case 6:i.fanout=o.uint64();break;case 7:i.mode=o.uint32();break;case 8:i.mtime=_p.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return i})),n),t.encode=o=>ol(o,t.codec()),t.decode=o=>nl(o,t.codec())})(mr||(mr={}));var _p;(function(t){let e;t.codec=()=>(e==null&&(e=sl((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={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let i=r.uint32();switch(i>>>3){case 1:o.Seconds=r.int64();break;case 2:o.FractionalNanoseconds=r.fixed32();break;default:r.skipType(i&7);break}}return o})),e),t.encode=r=>ol(r,t.codec()),t.decode=r=>nl(r,t.codec())})(_p||(_p={}));var HI;(function(t){let e;t.codec=()=>(e==null&&(e=sl((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={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let i=r.uint32();switch(i>>>3){case 1:o.MimeType=r.string();break;default:r.skipType(i&7);break}}return o})),e),t.encode=r=>ol(r,t.codec()),t.decode=r=>nl(r,t.codec())})(HI||(HI={}));var qI={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},uF=["directory","hamt-sharded-directory"],VI=parseInt("0644",8),GI=parseInt("0755",8),Ba=class t{constructor(e={type:"file"}){w(this,"type");w(this,"data");w(this,"blockSizes");w(this,"hashType");w(this,"fanout");w(this,"mtime");w(this,"_mode");w(this,"_originalMode");let{type:r,data:n,blockSizes:o,hashType:s,fanout:i,mtime:a,mode:c}=e;if(r!=null&&!Object.values(qI).includes(r))throw(0,m0.default)(new Error("Type: "+r+" is not valid"),"ERR_INVALID_TYPE");this.type=r??"file",this.data=n,this.hashType=s,this.fanout=i,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}static unmarshal(e){let r=mr.decode(e),n=new t({type:qI[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}set mode(e){e==null?this._mode=this.isDirectory()?GI:VI:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return uF.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=mr.DataType.Raw;break;case"directory":e=mr.DataType.Directory;break;case"file":e=mr.DataType.File;break;case"metadata":e=mr.DataType.Metadata;break;case"symlink":e=mr.DataType.Symlink;break;case"hamt-sharded-directory":e=mr.DataType.HAMTShard;break;default:throw(0,m0.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===VI&&!this.isDirectory()&&(n=void 0),n===GI&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),mr.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 QI=De(JI(),1);var Rs=class t{constructor(e,r,n=0){this._options=e,this._popCount=0,this._parent=r,this._posAtParent=n,this._children=new QI.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,s,i)=>(s!=null&&(s instanceof t?o.push(s.serialize(e,r)):o.push(e(s,i))),o),n))}async asyncTransform(e,r){return await XI(this,e,r)}toJSON(){return this.serialize(pF,mF)}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"?Xr(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(hF);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 hF(t){return!!t}function pF(t,e){return t.key}function mF(t){return t}async function XI(t,e,r){let n=[];for(let o of t._children.compactArray())if(o instanceof Rs)await XI(o,e,r);else{let s=await e(o);n.push({bitField:t._children.bitField(),children:s})}return await r(n)}var yF=[255,254,252,248,240,224,192,128],gF=[1,3,7,15,31,63,127,255],Ap=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],s=this._currentBitPos+1,i=Math.min(s,r),a=wF(o,s-i,i);n=(n<<i)+a,r-=i,this._currentBitPos-=i,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 wF(t,e,r){let n=bF(e,r);return(t&n)>>>e}function bF(t,e){return yF[t]&gF[Math.min(e+t-1,7)]}function YI(t){function e(r){return r instanceof Dp?r:new Dp(r,t)}return e}var Dp=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],s=Math.min(o.availableBits(),r),i=o.take(s);n=(n<<s)+i,r-=s,this._availableBits-=s,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?ew([this._value,Uint8Array.from([this._depth])]):this._value,r=await this._hashFn(e),n=new Ap(r);this._buffers.push(n),this._availableBits+=n.availableBits()}};function eB(t){if(t==null||t.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:t.bits??8,hash:YI(t.hashFn)};return new Rs(e)}var xF=async function(t){return(await aT.encode(t)).slice(0,8).reverse()},kF=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 Rs({hash:r._options.hash,bits:r._options.bits},e,o));return}await r.put(n.Name.substring(2),!0)}))},tB=t=>t.toString(16).toUpperCase().padStart(2,"0").substring(0,2),vF=t=>{let e=t.bucket,r=[];for(;e._parent!=null;)r.push(e),e=e._parent;return r.push(e),r.reverse()},rB=async(t,e,r,n,o)=>{if(n==null){let l=eB({hashFn:xF});n={rootBucket:l,hamtDepth:1,lastBucket:l}}await kF(t.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),i=tB(s.pos),a=vF(s);a.length>n.hamtDepth&&(n.lastBucket=a[n.hamtDepth],i=tB(n.lastBucket._posAtParent));let c=t.Links.find(l=>{if(l.Name==null)return!1;let d=l.Name.substring(0,2),p=l.Name.substring(2);return!(d!==i||p!==""&&p!==e)});if(c==null)return;if(c.Name!=null&&c.Name.substring(2)===e)return c.Hash;n.hamtDepth++;let u=await r.get(c.Hash,o);return t=Cr(u),rB(t,e,r,n,o)},nB=rB;function SF(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 Tp=SF;function EF(t){return t[Symbol.asyncIterator]!=null}function _F(t,e){if(EF(t))return async function*(){for await(let a of t)await e(a)&&(yield a)}();let r=Tp(t),{value:n,done:o}=r.next();if(o===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){await s&&(yield n);for await(let a of r)await e(a)&&(yield a)}();let i=e;return function*(){s===!0&&(yield n);for(let a of r)i(a)&&(yield a)}()}var oB=_F;function AF(t){return t[Symbol.asyncIterator]!=null}function DF(t,e){if(AF(t))return async function*(){for await(let a of t)yield e(a)}();let r=Tp(t),{value:n,done:o}=r.next();if(o===!0)return function*(){}();let s=e(n);if(typeof s.then=="function")return async function*(){yield await s;for await(let a of r)yield e(a)}();let i=e;return function*(){yield s;for(let a of r)yield i(a)}()}var Pa=DF;var Cp=globalThis.CustomEvent??Event;async function*Ns(t,e={}){let r=e.concurrency??1/0;r<1&&(r=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,s=[],i=ft(),a=ft(),c=!1,u,l=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let h of t){if(s.length===r&&(i=ft(),await i.promise),l)break;let m={done:!1};s.push(m),h().then(b=>{m.done=!0,m.ok=!0,m.value=b,o.dispatchEvent(new Cp("task-complete"))},b=>{m.done=!0,m.err=b,o.dispatchEvent(new Cp("task-complete"))})}c=!0,o.dispatchEvent(new Cp("task-complete"))}catch(h){u=h,o.dispatchEvent(new Cp("task-complete"))}});function d(){return n?s[0]?.done:!!s.find(h=>h.done)}function*p(){for(;s.length>0&&s[0].done;){let h=s[0];if(s.shift(),h.ok)yield h.value;else throw l=!0,i.resolve(),h.err;i.resolve()}}function*f(){for(;d();)for(let h=0;h<s.length;h++)if(s[h].done){let m=s[h];if(s.splice(h,1),h--,m.ok)yield m.value;else throw l=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(d()||(a=ft(),await a.promise),u!=null)throw u;if(n?yield*p():yield*f(),c&&s.length===0)break}}var Ip=class{constructor(e){w(this,"buffer");w(this,"mask");w(this,"top");w(this,"btm");w(this,"next");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}},La=class{constructor(e={}){w(this,"size");w(this,"hwm");w(this,"head");w(this,"tail");this.hwm=e.splitLimit??16,this.head=new Ip(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 Ip(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 y0=class extends Error{constructor(r,n){super(r??"The operation was aborted");w(this,"type");w(this,"code");this.type="aborted",this.code=n??"ABORT_ERR"}};function Ua(t={}){return TF(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 TF(t,e){e=e??{};let r=e.onEnd,n=new La,o,s,i,a=ft(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((b,g)=>{s=k=>{s=null,n.push(k);try{b(t(n))}catch(E){g(E)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ft()})}},u=b=>s!=null?s(b):(n.push(b),o),l=b=>(n=new La,s!=null?s({error:b}):(n.push({error:b}),o)),d=b=>{if(i)return o;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:b})},p=b=>i?o:(i=!0,b!=null?l(b):u({done:!0})),f=()=>(n=new La,p(),{done:!0}),h=b=>(p(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:f,throw:h,push:d,end:p,get readableLength(){return n.size},onEmpty:async b=>{let g=b?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let k,E;g!=null&&(k=new Promise((_,P)=>{E=()=>{P(new y0)},g.addEventListener("abort",E)}));try{await Promise.race([a.promise,k])}finally{E!=null&&g!=null&&g?.removeEventListener("abort",E)}}},r==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(b){return m.throw(b),r!=null&&(r(b),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:d,end(b){return m.end(b),r!=null&&(r(b),r=void 0),o},get readableLength(){return m.readableLength}},o}function CF(t){return t[Symbol.asyncIterator]!=null}function IF(...t){let e=[];for(let r of t)CF(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=Ua({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 sB=IF;function Ra(t,...e){if(t==null)throw new Error("Empty pipeline");if(g0(t)){let n=t;t=()=>n.source}else if(aB(t)||iB(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&g0(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++)g0(r[n])&&(r[n]=PF(r[n]));return BF(...r)}var BF=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},iB=t=>t?.[Symbol.asyncIterator]!=null,aB=t=>t?.[Symbol.iterator]!=null,g0=t=>t==null?!1:t.sink!=null&&t.source!=null,PF=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=Ua({objectMode:!0});r.then(()=>{n.end()},i=>{n.end(i)});let o,s=t.source;if(iB(s))o=async function*(){yield*s,n.end()};else if(aB(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return sB(n,o())}return t.source};var LF=(t,e,r,n,o,s,i)=>{async function*a(c={}){let u=c.offset??0,l=c.length??e.Links.length,d=e.Links.slice(u,l);c.onProgress?.(new mt("unixfs:exporter:walk:directory",{cid:t})),yield*Ra(d,p=>Pa(p,f=>async()=>{let h=f.Name??"",m=`${n}/${h}`;return(await o(f.Hash,h,m,[],s+1,i,c)).entry}),p=>Ns(p,{ordered:!0}),p=>oB(p,f=>f!=null))}return a},cB=LF;var Os=De(Fr(),1);async function uB(t,e,r,n,o,s,i){if(e instanceof Uint8Array){let u=Us(e,n,o,s);r.push(u);return}if(e.Data==null)throw(0,Os.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=Ba.unmarshal(e.Data)}catch(u){throw(0,Os.default)(u,"ERR_NOT_UNIXFS")}if(a.data!=null){let u=a.data,l=Us(u,n,o,s);r.push(l),n+=BigInt(l.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw(0,Os.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,p=d+a.blockSizes[u];if((o>=d&&o<p||s>=d&&s<=p||o<d&&s>p)&&c.push({link:l,blockStart:n}),n=p,n>s)break}await Ra(c,u=>Pa(u,l=>async()=>{let d=await t.get(l.link.Hash,i);return{...l,block:d}}),u=>Ns(u,{ordered:!0}),async u=>{for await(let{link:l,block:d,blockStart:p}of u){let f;switch(l.Hash.code){case Qn:f=Cr(d);break;case Zu:f=d;break;default:r.end((0,Os.default)(new Error(`Unsupported codec: ${l.Hash.code}`),"ERR_NOT_UNIXFS"));return}let h=new ms({concurrency:1});h.on("error",m=>{r.end(m)}),h.add(async()=>{i.onProgress?.(new mt("unixfs:exporter:walk:file",{cid:l.Hash})),await uB(t,f,r,p,o,s,i)}),await h.onIdle()}}),n>=s&&r.end()}var UF=(t,e,r,n,o,s,i)=>{async function*a(c={}){let u=r.fileSize();if(u===void 0)throw new Error("File was a directory");let{start:l,end:d}=Ca(u,c.offset,c.length);if(d===0n)return;let p=0n,f=d-l,h=Ua();c.onProgress?.(new mt("unixfs:exporter:walk:file",{cid:t})),uB(i,e,h,0n,l,d,c).catch(m=>{h.end(m)});for await(let m of h)if(m!=null){if(p+=BigInt(m.byteLength),p>f)throw h.end(),(0,Os.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");p===f&&h.end(),c.onProgress?.(new mt("unixfs:exporter:progress:unixfs:file",{bytesRead:p,totalBytes:f,fileSize:u})),yield m}if(p<f)throw(0,Os.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return a},w0=UF;var RF=(t,e,r,n,o,s,i)=>{function a(c={}){return c.onProgress?.(new mt("unixfs:exporter:walk:hamt-sharded-directory",{cid:t})),lB(e,n,o,s,i,c)}return a};async function*lB(t,e,r,n,o,s){let i=t.Links,a=Ra(i,c=>Pa(c,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,s);return{entries:d.entry==null?[]:[d.entry]}}else{let d=await o.get(u.Hash,s);return t=Cr(d),s.onProgress?.(new mt("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:lB(t,e,r,n,o,s)}}}),c=>Ns(c,{ordered:!0}));for await(let{entries:c}of a)yield*c}var dB=RF;var NF=(t,e)=>t.Links.find(n=>n.Name===e)?.Hash,OF={raw:w0,file:w0,directory:cB,"hamt-sharded-directory":dB,metadata:(t,e,r,n,o,s,i)=>()=>[],symlink:(t,e,r,n,o,s,i)=>()=>[]},$F=async(t,e,r,n,o,s,i,a)=>{let c=await i.get(t,a),u=Cr(c),l,d;if(e==null&&(e=t.toString()),u.Data==null)throw(0,il.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{l=Ba.unmarshal(u.Data)}catch(f){throw(0,il.default)(f,"ERR_NOT_UNIXFS")}if(r==null&&(r=e),n.length>0){let f;if(l?.type==="hamt-sharded-directory"?f=await nB(u,n[0],i):f=NF(u,n[0]),f==null)throw(0,il.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let h=n.shift(),m=`${r}/${h}`;d={cid:f,toResolve:n,name:h??"",path:m}}let p=OF[l.type](t,u,l,r,o,s,i);if(p==null)throw(0,il.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return l.isDirectory()?{entry:{type:"directory",name:e,path:r,cid:t,content:p,unixfs:l,depth:s,node:u,size:l.fileSize()},next:d}:{entry:{type:"file",name:e,path:r,cid:t,content:p,unixfs:l,depth:s,node:u,size:l.fileSize()},next:d}},fB=$F;var MF={[Qn]:fB,[Zu]:MI,[Tt]:RI,[LI.code]:OI},pB=async(t,e,r,n,o,s,i)=>{let a=MF[t.code];if(a==null)throw(0,hB.default)(new Error(`No resolver for code ${t.code}`),"ERR_NO_RESOLVER");return a(t,e,r,n,pB,o,s,i)},mB=pB;var FF=(t="")=>(t.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),zF=t=>{if(t instanceof Uint8Array)return{cid:ve.decode(t),toResolve:[]};let e=ve.asCID(t);if(e!=null)return{cid:e,toResolve:[]};if(typeof t=="string"){t.indexOf("/ipfs/")===0&&(t=t.substring(6));let r=FF(t);return{cid:ve.parse(r[0]),toResolve:r.slice(1)}}throw(0,Bp.default)(new Error(`Unknown path type ${t}`),"ERR_BAD_PATH")};async function*jF(t,e,r={}){let{cid:n,toResolve:o}=zF(t),s=n.toString(),i=s,a=o.length;for(;;){let c=await mB(n,s,i,o,a,e,r);if(c.entry==null&&c.next==null)throw(0,Bp.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");if(c.entry!=null&&(yield c.entry),c.next==null)return;o=c.next.toResolve,n=c.next.cid,s=c.next.name,i=c.next.path}}async function yB(t,e,r={}){let n=await II(jF(t,e,r));if(n==null)throw(0,Bp.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");return n}var WF=Sh(),HF=Lr({fileChunkEncoder:ao,smallFileEncoder:ao,chunker:lu(1024*1024),fileLayout:oa(1024)});async function gB(t){let e=qF(t),r=await VF(e);return{cid:r.at(-1).cid,blocks:r}}async function wB(t,e,r){let n=await yB(e.toString(),t,{length:r.size}),o=[];for await(let s of n.content())o.push(s);return new File(o,n.name,{type:r.type,lastModified:0})}function qF(t){let{readable:e,writable:r}=new TransformStream({},WF),n=Eu({writable:r,settings:HF}),o=new b0("",t);return(async()=>(await o.finalize(n),await n.close()))(),e}async function VF(t){let e=[];return await t.pipeTo(new WritableStream({write(r){e.push(r)}})),e}var al,b0=class{constructor(e,r){ke(this,al,void 0);w(this,"name");this.name=e,fe(this,al,r)}async finalize(e){let r=fs(e);return await $(this,al).stream().pipeTo(new WritableStream({async write(n){await r.write(n)}})),await r.close()}};al=new WeakMap;async function kB(t,e,r,n){let o;for(let s of r){let i=await GF(t,s);o=await EI(t,e,s.key,i,n);let a=o.root.toString();o.additions.some(u=>u.cid.toString()===a)||await t.get(o.root)||(console.error(`missing root in additions: ${o.additions.length} ${a} 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 GF(t,e){let r;e.del?r={del:!0}:(await KF(t,e.value),r={doc:e.value});let n=await Nr({value:r,hasher:kt,codec:Te});return t.putSync(n.cid,n.bytes),n.cid}async function KF(t,e){e._files&&await bB(t,e._files),e._publicFiles&&await bB(t,e._publicFiles,!0)}async function bB(t,e,r=!1){let n=t.parent,o=new lo(n);n.transactions.add(o);let s=[],i=0;for(let a in e)if(File===e[a].constructor){let c=e[a];i+=c.size;let{cid:u,blocks:l}=await gB(c);s.push(a);for(let d of l)o.putSync(d.cid,d.bytes);e[a]={cid:u,type:c.type,size:c.size}}if(i>1024*1024*1)throw new Error("Sync limit for files in a single update is 1MB");if(s.length){let a=await n.loader?.commit(o,{files:e},{public:r});if(a)for(let c of s)e[c]={car:a,...e[c]}}}async function vB(t,e,r){if(!e.length)throw new Error("Getting from an empty database");let n=await _I(t,e,r);if(!n)throw new Error(`Missing key ${r}`);return await S0(t,n)}function v0(t,{doc:e}){e&&(e._files&&xB(t,e._files),e._publicFiles&&xB(t,e._publicFiles,!0))}function xB(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 s=t.loader;o.file=async()=>await wB({get:async i=>{let c=await(await s.loadFileCar(o.car,r)).get(i);if(!c)throw new Error(`Missing block ${i.toString()}`);return c.bytes}},o.cid,o)}e[n]=o}}async function S0(t,e){let r=await t.get(e);if(!r)throw new Error(`Missing linked block ${e.toString()}`);let{value:n}=await io({bytes:r.bytes,hasher:kt,codec:Te});return v0(t,n),n}var x0=class extends $r{async get(e){try{return await super.get(e)}catch(r){return console.error("missing event",e.toString(),r),{value:null}}}};async function cl(t,e,r,n){let o=n.dirty?new x0(t):new $r(t);return{result:(await k0(t,o,e,r,[],new Set,new Set,n.limit||1/0)).reverse(),head:e}}async function k0(t,e,r,n,o=[],s,i,a){if(a<=0)return o;let c=r.map(u=>u.toString());for(let u of n)if(c.includes(u.toString()))return o;for(let u of r){if(i.has(u.toString()))continue;i.add(u.toString());let{value:l}=await e.get(u);if(!l)continue;let{key:d,value:p}=l.data;if(s.has(d))l.parents&&(o=await k0(t,e,l.parents,n,o,s,i,a));else{s.add(d);let f=await S0(t,p);o.push({key:d,value:f.doc,del:f.del}),a--,l.parents&&(o=await k0(t,e,l.parents,n,o,s,i,a))}}return o}async function*SB(t,e){for await(let[r,n]of c0(t,e)){let o=await S0(t,n);yield{key:r,value:o.doc,del:o.del}}}async function*EB(t,e){for await(let r of s0(t,e))yield r}async function _B(t,e){let r=new kp(t),n=new lo(t);for await(let[,s]of c0(r,e))if(!await r.get(s))throw new Error("Missing block: "+s.toString());for await(let s of s0(r,e));let o=await Ta(r,e);for(let{cid:s,bytes:i}of[...o.additions,...o.removals])n.putSync(s,i);await cl(r,e,[],{});for(let s of r.cids){let i=await t.get(s);if(!i)throw new Error("Missing block: "+s.toString());await n.put(s,i.bytes)}await t.commitCompaction(n,e)}var Pp=class{constructor(){w(this,"head",[]);w(this,"zoomers",new Set);w(this,"watchers",new Set);w(this,"blocks",null)}setHead(e){this.head=e}async applyHead(e,r,n,o=null){let s=this.head.sort((u,l)=>u.toString().localeCompare(l.toString()));if(r=r.sort((u,l)=>u.toString().localeCompare(l.toString())),s.toString()===r.toString()){this.watchers.forEach(u=>u(o||[]));return}let i=n.sort((u,l)=>u.toString().localeCompare(l.toString()));if(s.toString()===i.toString()){this.setHead(r),this.watchers.forEach(u=>u(o||[]));return}let a=async(u,l)=>{if(u instanceof lo)return await l(u);if(!this.blocks)throw new Error("missing blocks");return await this.blocks.transaction(l,void 0,{noLoader:!0})},{head:c}=await a(e,async u=>{let l=this.head;for(let p of r)l=await Yu(u,l,p);let d=await Ta(u,l);for(let{cid:p,bytes:f}of[...d.additions,...d.removals])u.putSync(p,f);return{head:l}});this.watchers.size&&!o&&(o=(await cl(this.blocks,c,n,{})).result),this.setHead(c),this.zoomers.forEach(u=>u()),this.watchers.forEach(u=>u(o||[]))}onTick(e){this.watchers.add(e)}onZoom(e){this.zoomers.add(e)}};var Lp=class{constructor(e,r){w(this,"name");w(this,"opts",{});w(this,"ready");w(this,"blocks");w(this,"indexBlocks");w(this,"indexers",new Map);w(this,"clock",new Pp);this.name=e||null,this.opts=r||this.opts,this.blocks=new xp(this.name,this.clock,this.opts),this.clock.blocks=this.blocks,this.indexBlocks=new bp(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:s}=await kB(n,this.clock.head,e,r);return e=e.map(({key:i,value:a,del:c})=>(v0(this.blocks,{doc:a}),{key:i,value:a,del:c})),await this.clock.applyHead(n,s,o,e),{head:s}})}async allDocs(){await this.ready;let e=[];for await(let r of SB(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 EB(this.blocks,this.clock.head))e.push(r);return e.join(`
|
15
|
-
`)}async get(e){await this.ready;let r=await vB(this.blocks,this.clock.head,e);return r.del?null:r}async changes(e=[],r={}){return await this.ready,await cl(this.blocks,this.clock.head,e,r)}async compact(){if(await this.ready,!(this.blocks.loader&&this.blocks.loader.carLog.length<2))return await _B(this.blocks,this.clock.head)}};var fo=class{constructor(e,r){w(this,"name");w(this,"opts",{});w(this,"_listeners",new Set);w(this,"_crdt");w(this,"_writeQueue");this.name=e||null,this.opts=r||this.opts,this._crdt=new Lp(e,this.opts),this._crdt.clock.onTick(n=>{this._notify(n)}),this._writeQueue=CC(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||TC(),s=await this._writeQueue.push({key:o,value:n});return{id:o,clock:s?.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:i,value:a,del:c})=>({key:i,value:c?{_id:i,_deleted:!0}:{_id:i,...a}})),clock:o}}subscribe(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}async query(e,r={}){return await(typeof e=="string"?Da({_crdt:this._crdt},e):Da({_crdt:this._crdt},ZF(e.toString()),e)).query(r)}async compact(){await this._crdt.compact()}connect(e){return Up.ipfs(this,e)}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],s={car:o.car.toString()};o.key&&(s.key=o.key.toString()),this.name&&(s.name=this.name);let i=new URL("/import#"+new URLSearchParams(s).toString(),r);return console.log("Import to dashboard: "+i.toString()),i}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)})}}};w(fo,"databases",new Map);function E0(t,e){if(!fo.databases.has(t)){let r=new fo(t,e);["get","put","del","changes","subscribe","query","compact","connect","getDashboardURL","openDashboard"].forEach(n=>{r[n]=r[n].bind(r)}),fo.databases.set(t,r)}return fo.databases.get(t)}function ZF(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}var ul={};F(ul,{Delegation:()=>po,View:()=>po,allows:()=>rz,create:()=>D0,delegate:()=>js,exportDAG:()=>A0,importDAG:()=>oz,isDelegation:()=>zs,isLink:()=>tz,view:()=>T0});var dn={};F(dn,{code:()=>Tt,contentType:()=>QF,decode:()=>Ge,encode:()=>$s,link:()=>AB,name:()=>rc,write:()=>XF});var QF="application/vnd.ipld.dag-cbor",Rp=(t,e)=>{if(e.has(t))throw new TypeError("Can not encode circular structure");if(t===void 0&&e.size===0||t===null||typeof t=="symbol"&&e.size===0)return null;if(Se(t)||ArrayBuffer.isView(t))return t;if(Array.isArray(t)){e.add(t);let r=[];for(let n of t)r.push(n===void 0||typeof n=="symbol"?null:Rp(n,e));return r}if(typeof t.toJSON=="function"){e.add(t);let r=t.toJSON();return Rp(r,e)}if(typeof t=="object"){e.add(t);let r={};for(let[n,o]of Object.entries(t))o!==void 0&&typeof o!="symbol"&&(r[n]=Rp(o,e));return r}return t},$s=t=>tr(Rp(t,new Set)),AB=async(t,{hasher:e=ue}={})=>Fe(Tt,await e.digest(t)),XF=async(t,e)=>{let r=$s(t);return{cid:await AB(r,e),bytes:r}};var Ms=function*(t){t&&typeof t=="object"&&"iterateIPLDBlocks"in t&&typeof t.iterateIPLDBlocks=="function"&&(yield*t.iterateIPLDBlocks())},DB=(t=[])=>{let e=new Map;return Op(t,e),e},YF=_o.code,ho=(t,e,r)=>{if(t.multihash.code===YF)return{cid:t,bytes:t.multihash.digest};let n=e.get(`${t}`);return n||(r===void 0?Fs(t):r)};var Fs=t=>{throw new Error(`Block for the ${t} is not found`)},Np=async(t,e,r={})=>{let n=r.codec||dn,o=r.hasher||ue,s=n.encode(t),i=await o.digest(s),a=Fe(n.code,i);return e.set(a.toString(),{bytes:s,cid:a}),{bytes:s,cid:a,data:t}},ez=({cid:t,bytes:e},r)=>(r.set(t.toString(),{bytes:e,cid:t}),{bytes:e,cid:t}),Op=(t,e)=>{for(let r of t)ez(r,e)};var tz=Se,zs=t=>!Se(t),rz=(...t)=>{let e={};for(let r of t)for(let{with:n,can:o,nb:s}of TB(r)){let i=e[n]||(e[n]={});(i[o]||(i[o]=[])).push({...s})}return e},TB=function*({issuer:t,capabilities:e,proofs:r}){for(let n of e)if(n.with==="ucan:*"){yield{...n,with:t.did()};for(let o of r)if(zs(o))for(let s of TB(o)){let i=nz(s.can,n.can);i&&(yield{...s,can:i,nb:{...s.nb,...Object(n.nb)}})}}else yield n},nz=(t,e)=>t==="*"?e:e==="*"||e.endsWith("/*")&&t.startsWith(e.slice(0,-1))?t:t.endsWith("/*")&&e.startsWith(t.slice(0,-1))?e:t===e?t:null,po=class{constructor(e,r=new Map){this.root=e,this.blocks=r,Object.defineProperties(this,{blocks:{enumerable:!1}})}get attachedLinks(){let e=new Set,r=this.data;for(let n of r.capabilities){let o=iz(n);for(let s of o)e.add(`${s}`)}for(let n of r.facts)if(Se(n))e.add(`${n}`);else{let o=Object.values(n).filter(s=>Se(s));for(let s of o)e.add(`${s}`)}return e}get version(){return this.data.version}get signature(){return this.data.signature}get cid(){return this.root.cid}link(){return this.root.cid}get asCID(){return this.cid}get bytes(){return this.root.bytes}get data(){let e=$p(this.root);return Object.defineProperties(this,{data:{value:e,enumerable:!1}}),e}attach(e){if(!this.attachedLinks.has(`${e.cid.link()}`))throw new Error(`given block with ${e.cid} is not an attached link`);this.blocks.set(`${e.cid}`,e)}export(){return A0(this.root,this.blocks,this.attachedLinks)}iterateIPLDBlocks(){return A0(this.root,this.blocks,this.attachedLinks)}get proofs(){return sz(this)}get issuer(){return this.data.issuer}get audience(){return this.data.audience}get capabilities(){return this.data.capabilities}get expiration(){return this.data.expiration}get notBefore(){return this.data.notBefore}get nonce(){return this.data.nonce}get facts(){return this.data.facts}iterate(){return CB(this)}delegate(){return this}buildIPLDView(){return this}toJSON(){return{...this.data.toJSON(),"/":this.cid.toString(),prf:this.proofs.map(e=>zs(e)?e:{"/":e.toString()})}}},CB=function*(t){for(let e of t.proofs)zs(e)&&(yield*CB(e),yield e)},_0=new WeakMap,$p=({bytes:t})=>{let e=_0.get(t);if(!e){let r=ql(t);return _0.set(t,r),r}return e},js=async({issuer:t,audience:e,proofs:r=[],attachedBlocks:n=new Map,...o},s)=>{let i=[],a=new Map;for(let p of r)if(!zs(p))i.push(p);else{i.push(p.cid);for(let f of p.export())a.set(f.cid.toString(),f)}let c=await gi({...o,issuer:t,audience:e,proofs:i}),{cid:u,bytes:l}=await Vl(c,s);_0.set(u,c);let d=new po({cid:u,bytes:l},a);Object.defineProperties(d,{proofs:{value:r}});for(let p of n.values())d.attach(p);return d},A0=function*(t,e,r){for(let n of $p(t).proofs){let o=e.get(`${n}`);o&&(yield*IB(o,e))}for(let n of r.values()){let o=e.get(n);o&&(yield o)}yield t},IB=function*(t,e){for(let r of $p(t).proofs){let n=e.get(`${r}`);n&&(yield*IB(n,e))}yield t},oz=t=>{let e=[];for(let n of t)e.push([n.cid.toString(),n]);let r=e.pop();if(r){let[,n]=r;return new po(n,new Map(e))}else throw new RangeError("Empty DAG can not be turned into a delegation")},D0=({root:t,blocks:e})=>new po(t,e),T0=({root:t,blocks:e},r)=>{let n=ho(t,e,null);return n?D0({root:n,blocks:e}):r},sz=t=>{let e=[],{root:r,blocks:n}=t;for(let o of $p(r).proofs){let s=n.get(o.toString());e.push(s?D0({root:s,blocks:n}):o)}return Object.defineProperty(t,"proofs",{value:e}),e};function iz(t){let e=[];function r(n){for(let o in n){let s=n[o];Se(s)?e.push(s):s&&typeof s=="object"&&r(s)}}return r(t),e}var Ws={};F(Ws,{Invocation:()=>Mp,create:()=>BB,invoke:()=>ll,view:()=>I0});var ll=t=>new C0(t),BB=({root:t,blocks:e})=>new Mp(t,e),I0=({root:t,blocks:e},r)=>{let n=ho(t,e,null);return n==null?r!==void 0?r:Fs(t):BB({root:n,blocks:e})},C0=class{constructor({issuer:e,audience:r,capability:n,proofs:o=[],expiration:s,lifetimeInSeconds:i,notBefore:a,nonce:c,facts:u=[]}){this.issuer=e,this.audience=r,this.proofs=o,this.capabilities=[n],this.expiration=s,this.lifetimeInSeconds=i,this.notBefore=a,this.nonce=c,this.facts=u,this.attachedBlocks=new Map}attach(e){this.attachedBlocks.set(`${e.cid}`,e)}delegate(){return js(this)}buildIPLDView(){return js(this)}async execute(e){let r=this,[n]=await e.execute(r);return n}},Mp=class extends po{};var zr={};F(zr,{MessageSchema:()=>HB,build:()=>Nz,view:()=>Oz});var dl={};F(dl,{issue:()=>cz,view:()=>zp});var zp=({root:t,blocks:e},r)=>{let n=ho(t,e,null);if(n==null)return r!==void 0?r:Fs(t);let o=Ge(n.bytes);return new Fp({root:{...n,data:o},store:e})},Fp=class{constructor({root:e,store:r,ran:n,issuer:o,signature:s,proofs:i}){this.store=r,this.root=e,this._ran=n,this._signature=s,this._proofs=i,this._issuer=o}get ran(){let e=this._ran;if(e)return e;{let r=I0({root:this.root.data.ocm.ran,blocks:this.store},this.root.data.ocm.ran);return this._ran=r,r}}get proofs(){let e=this._proofs;if(e)return e;{let{store:r,root:n}=this,{prf:o}=n.data.ocm,s=[];if(o)for(let i of o){let a=T0({root:i,blocks:r},i);s.push(a)}return this._proofs=s,s}}get meta(){return this.root.data.ocm.meta}get issuer(){let e=this._issuer;if(e)return e;{let{iss:r}=this.root.data.ocm;if(r){let n=Ue(r);return this._issuer=n,n}}}get out(){return this.root.data.ocm.out}get fx(){return this.root.data.ocm.fx}get signature(){let e=this._signature;if(e)return e;{let r=hi(this.root.data.sig);return this._signature=r,r}}verifySignature(e){return this.signature.verify(e,$s(this.root.data.ocm))}buildIPLDView(){return this}*iterateIPLDBlocks(){let{ran:e,fx:r,proofs:n,root:o}=this;yield*Ms(e);for(let s of r.fork)yield*Ms(s);r.join&&(yield*Ms(r.join));for(let s of n)yield*Ms(s);yield o}},B0=class{constructor({issuer:e,result:r,ran:n,fx:o=az,proofs:s=[],meta:i={}}){this.issuer=e,this.result=r,this.ran=n,this.fx=o,this.proofs=s,this.meta=i}async buildIPLDView({hasher:e=ue,codec:r=dn}={}){let n=DB();Op(Ms(this.ran),n);for(let c of this.proofs)Op(Ms(c),n);let o={ran:this.ran.link(),out:this.result,fx:this.fx,meta:this.meta,iss:this.issuer.did(),prf:this.proofs.map(c=>c.link())},s=await this.issuer.sign($s(o)),a=await Np({ocm:o,sig:s},n,{hasher:e,codec:r});return new Fp({root:a,store:n,signature:s,proofs:this.proofs,ran:this.ran})}},az=Object.freeze({fork:Object.freeze([])}),cz=t=>new B0(t).buildIPLDView();var ct={};F(ct,{API:()=>ye,DID:()=>fk,Link:()=>fl,Text:()=>mk,URI:()=>St,and:()=>OB,array:()=>UB,boolean:()=>mz,dictionary:()=>ak,did:()=>rm,endsWith:()=>zB,enum:()=>fz,error:()=>$e,float:()=>vz,greaterThan:()=>MB,integer:()=>bz,intersection:()=>NB,lessThan:()=>$B,link:()=>qs,literal:()=>qp,memberError:()=>Hs,never:()=>uz,nullable:()=>LB,number:()=>yz,ok:()=>jp,optional:()=>Kp,or:()=>RB,refine:()=>jB,startsWith:()=>FB,string:()=>hn,struct:()=>Zp,text:()=>nm,tuple:()=>dz,typeError:()=>vt,unknown:()=>lz,uri:()=>dk,variant:()=>uk});var St={};F(St,{from:()=>Dz,match:()=>dk,read:()=>Az,uri:()=>_z});var jp=t=>{if(t==null)throw new TypeError(`ok(${t}) is not allowed, consider ok({}) instead`);return{ok:t}};var PB=t=>{throw new yr(t)};var yr=class extends Error{describe(){return this.toString()}get message(){return this.describe()}toJSON(){let{name:e,message:r,stack:n}=this;return{name:e,message:r,stack:n}}};var ye=class{constructor(e){this.settings=e}toString(){return`new ${this.constructor.name}()`}readWith(e,r){throw new Error("Abstract method readWith must be implemented by subclass")}read(e){return this.readWith(e,this.settings)}is(e){return!this.read(e)?.error}from(e){let r=this.read(e);if(r.error)throw r.error;return r.ok}optional(){return Kp(this)}nullable(){return LB(this)}array(){return UB(this)}or(e){return RB(this,e)}and(e){return OB(this,e)}refine(e){return jB(this,e)}brand(e){return this}default(e){let r=this.from(e);if(r===void 0)throw new Error("Value of type undefined is not a valid default");return new N0({reader:this,value:r})}},P0=class extends ye{toString(){return"never()"}read(e){return vt({expect:"never",actual:e})}},uz=()=>new P0,L0=class extends ye{read(e){return{ok:e}}toString(){return"unknown()"}},lz=()=>new L0,U0=class extends ye{readWith(e,r){let n=r.read(e);return n.error?e===null?{ok:null}:{error:new Gp({causes:[n.error,vt({expect:"null",actual:e}).error]})}:n}toString(){return`${this.settings}.nullable()`}},LB=t=>new U0(t),R0=class extends ye{optional(){return this}readWith(e,r){let n=r.read(e);return n.error&&e===void 0?{ok:void 0}:n}toString(){return`${this.settings}.optional()`}},N0=class extends ye{optional(){return this}readWith(e,{reader:r,value:n}){if(e===void 0)return{ok:n};{let o=r.read(e);return o.error||o.ok!==void 0?o:{ok:n}}}toString(){return`${this.settings.reader}.default(${JSON.stringify(this.settings.value)})`}get value(){return this.settings.value}},Kp=t=>new R0(t),O0=class extends ye{readWith(e,r){if(!Array.isArray(e))return vt({expect:"array",actual:e});let n=[];for(let[o,s]of e.entries()){let i=r.read(s);if(i.error)return Hs({at:o,cause:i.error});n.push(i.ok)}return{ok:n}}get element(){return this.settings}toString(){return`array(${this.element})`}},UB=t=>new O0(t),$0=class extends ye{readWith(e,r){if(!Array.isArray(e))return vt({expect:"array",actual:e});if(e.length!==this.shape.length)return $e(`Array must contain exactly ${this.shape.length} elements`);let n=[];for(let[o,s]of r.entries()){let i=s.read(e[o]);if(i.error)return Hs({at:o,cause:i.error});n[o]=i.ok}return{ok:n}}get shape(){return this.settings}toString(){return`tuple([${this.shape.map(e=>e.toString()).join(", ")}])`}},dz=t=>new $0(t),M0=class t extends ye{readWith(e,{key:r,value:n}){if(typeof e!="object"||e===null||Array.isArray(e))return vt({expect:"dictionary",actual:e});let o={};for(let[s,i]of Object.entries(e)){let a=r.read(s);if(a.error)return Hs({at:s,cause:a.error});let c=n.read(i);if(c.error)return Hs({at:s,cause:c.error});c.ok!==void 0&&(o[a.ok]=c.ok)}return{ok:o}}get key(){return this.settings.key}get value(){return this.settings.value}partial(){let{key:e,value:r}=this.settings;return new t({key:e,value:Kp(r)})}toString(){return`dictionary(${this.settings})`}},ak=({value:t,key:e})=>new M0({value:t,key:e||hn()}),F0=class extends ye{readWith(e,{variants:r,type:n}){return r.has(e)?{ok:e}:vt({expect:n,actual:e})}toString(){return this.settings.type}},fz=t=>new F0({type:t.join("|"),variants:new Set(t)});var z0=class extends ye{readWith(e,r){let n=[];for(let o of r){let s=o.read(e);if(s.error)n.push(s.error);else return s}return{error:new Gp({causes:n})}}get variants(){return this.settings}toString(){return`union([${this.variants.map(e=>e.toString()).join(", ")}])`}},hz=t=>new z0(t),RB=(t,e)=>hz([t,e]),j0=class extends ye{readWith(e,r){let n=[];for(let o of r){let s=o.read(e);s.error&&n.push(s.error)}return n.length>0?{error:new ik({causes:n})}:{ok:e}}toString(){return`intersection([${this.settings.map(e=>e.toString()).join(",")}])`}},NB=t=>new j0(t),OB=(t,e)=>NB([t,e]),W0=class extends ye{readWith(e){switch(e){case!0:case!1:return{ok:e};default:return vt({expect:"boolean",actual:e})}}toString(){return"boolean()"}},pz=new W0,mz=()=>pz,Wp=class extends ye{greaterThan(e){return this.refine(MB(e))}lessThan(e){return this.refine($B(e))}refine(e){return new q0({base:this,schema:e})}},H0=class extends Wp{readWith(e){return typeof e=="number"?{ok:e}:vt({expect:"number",actual:e})}toString(){return"number()"}},ck=new H0,yz=()=>ck,q0=class extends Wp{readWith(e,{base:r,schema:n}){let o=r.read(e);return o.error?o:n.read(o.ok)}toString(){return`${this.settings.base}.refine(${this.settings.schema})`}},V0=class extends ye{readWith(e,r){return e<r?{ok:e}:$e(`Expected ${e} < ${r}`)}toString(){return`lessThan(${this.settings})`}},$B=t=>new V0(t),G0=class extends ye{readWith(e,r){return e>r?{ok:e}:$e(`Expected ${e} > ${r}`)}toString(){return`greaterThan(${this.settings})`}},MB=t=>new G0(t),gz={read(t){return Number.isInteger(t)?{ok:t}:vt({expect:"integer",actual:t})},toString(){return"Integer"}},wz=ck.refine(gz),bz=()=>wz,xz={read(t){return Number.isFinite(t)?{ok:t}:vt({expect:"Float",actual:t})},toString(){return"Float"}},kz=ck.refine(xz),vz=()=>kz,Hp=class extends ye{refine(e){let r=e;return new K0({base:this,schema:r})}startsWith(e){return this.refine(FB(e))}endsWith(e){return this.refine(zB(e))}toString(){return"string()"}},K0=class extends Hp{readWith(e,{base:r,schema:n}){let o=r.read(e);return o.error?o:n.read(o.ok)}toString(){return`${this.settings.base}.refine(${this.settings.schema})`}},Z0=class extends Hp{readWith(e){return typeof e=="string"?{ok:e}:vt({expect:"string",actual:e})}},Sz=new Z0,hn=()=>Sz,J0=class extends ye{readWith(e,r){return e.startsWith(r)?{ok:e}:$e(`Expect string to start with "${r}" instead got "${e}"`)}get prefix(){return this.settings}toString(){return`startsWith("${this.prefix}")`}},FB=t=>new J0(t),Q0=class extends ye{readWith(e,r){return e.endsWith(r)?{ok:e}:$e(`Expect string to end with "${r}" instead got "${e}"`)}get suffix(){return this.settings}toString(){return`endsWith("${this.suffix}")`}},zB=t=>new Q0(t),X0=class extends ye{readWith(e,{base:r,schema:n}){let o=r.read(e);return o.error?o:n.read(o.ok)}toString(){return`${this.settings.base}.refine(${this.settings.schema})`}},jB=(t,e)=>new X0({base:t,schema:e}),Y0=class extends ye{readWith(e,r){return e!==r?{error:new nk({expect:r,actual:e})}:{ok:r}}get value(){return this.settings}default(e=this.value){return super.default(e)}toString(){return`literal(${Vp(this.value)})`}},qp=t=>new Y0(t),ek=class t extends ye{readWith(e,r){if(typeof e!="object"||e===null||Array.isArray(e))return vt({expect:"object",actual:e});let n=e,o={},s=Object.entries(r);for(let[i,a]of s){let c=a.read(n[i]);if(c.error)return Hs({at:i,cause:c.error});c.ok!==void 0&&(o[i]=c.ok)}return{ok:o}}partial(){return new t(Object.fromEntries(Object.entries(this.shape).map(([e,r])=>[e,Kp(r)])))}get shape(){return this.settings}toString(){return["struct({ ",...Object.entries(this.shape).map(([e,r])=>`${e}: ${r}, `),"})"].join("")}create(e){return this.from(e||{})}extend(e){return new t({...this.shape,...e})}},Zp=t=>{let e={},r=Object.entries(t);for(let[n,o]of r)switch(typeof o){case"number":case"string":case"boolean":e[n]=qp(o);break;case"object":e[n]=o===null?qp(null):o;break;default:throw new Error(`Invalid struct field "${n}", expected schema or literal, instead got ${typeof o}`)}return new ek(e)},tk=class extends ye{readWith(e,r){if(typeof e!="object"||e===null||Array.isArray(e))return vt({expect:"object",actual:e});let n=Object.keys(e),[o]=n.length===1?n:[],s=o?r[o]:void 0;if(s){let i=s.read(e[o]);return i.error?Hs({at:o,cause:i.error}):{ok:{[o]:i.ok}}}else if(r._){let i=r._.read(e);return i.error?i:{ok:{_:i.ok}}}else return $e(o?`Expected an object with one of the these keys: ${Object.keys(r).sort().join(", ")} instead got object with key ${o}`:"Expected an object with a single key instead got object with keys "+n.sort().join(", "))}match(e,r){let n=this.read(e);if(n.error){if(r!==void 0)return[null,r];throw n.error}else{let[o]=Object.keys(n.ok),s=n.ok[o];return[o,s]}}create(e){return this.from(e)}},uk=t=>new tk(t),$e=t=>({error:new fn(t)}),fn=class extends yr{get name(){return"SchemaError"}describe(){return this.name}},rk=class extends fn{constructor({expect:e,actual:r}){super(),this.expect=e,this.actual=r}get name(){return"TypeError"}describe(){return`Expected value of type ${this.expect} instead got ${Vp(this.actual)}`}},vt=t=>({error:new rk(t)}),Vp=t=>{let e=typeof t;switch(e){case"boolean":case"string":return JSON.stringify(t);case"bigint":return`${t}n`;case"number":case"symbol":case"undefined":return String(t);case"object":return t===null?"null":Array.isArray(t)?"array":"object";default:return e}},nk=class extends fn{constructor({expect:e,actual:r}){super(),this.expect=e,this.actual=r}get name(){return"LiteralError"}describe(){return`Expected literal ${Vp(this.expect)} instead got ${Vp(this.actual)}`}},ok=class extends fn{constructor({at:e,cause:r}){super(),this.at=e,this.cause=r}get name(){return"ElementError"}describe(){return[`Array contains invalid element at ${this.at}:`,Jp(this.cause.message)].join(`
|
16
|
-
`)}},sk=class extends fn{constructor({at:e,cause:r}){super(),this.at=e,this.cause=r}get name(){return"FieldError"}describe(){return[`Object contains invalid field "${this.at}":`,Jp(this.cause.message)].join(`
|
17
|
-
`)}},Hs=({at:t,cause:e})=>typeof t=="string"?{error:new sk({at:t,cause:e})}:{error:new ok({at:t,cause:e})},Gp=class extends fn{constructor({causes:e}){super(),this.causes=e}get name(){return"UnionError"}describe(){let{causes:e}=this;return["Value does not match any type of the union:",...e.map(r=>Jp(r.message))].join(`
|
18
|
-
`)}},ik=class extends fn{constructor({causes:e}){super(),this.causes=e}get name(){return"IntersectionError"}describe(){let{causes:e}=this;return["Value does not match following types of the intersection:",...e.map(r=>Jp(r.message))].join(`
|
19
|
-
`)}},Ez=(t,e=" ")=>`${e}${t.split(`
|
20
|
-
`).join(`
|
21
|
-
${e}`)}`,Jp=t=>Ez(`- ${t}`);var Xp=class extends ye{readWith(e,{protocol:r}={}){if(typeof e!="string"&&!(e instanceof URL))return $e(`Expected URI but got ${e===null?"null":typeof e}`);try{let n=new URL(String(e));return r!=null&&n.protocol!==r?$e(`Expected ${r} URI instead got ${n.href}`):{ok:n.href}}catch{return $e("Invalid URI")}}},lk=new Xp({}),_z=()=>lk,Az=t=>lk.read(t),dk=t=>new Xp(t),Dz=t=>lk.from(t);var fl={};F(fl,{create:()=>Fe,createLegacy:()=>ai,isLink:()=>Se,link:()=>Tz,match:()=>qs,optional:()=>Iz,parse:()=>br,read:()=>Cz,schema:()=>em});var Yp=class extends ye{readWith(e,{code:r,multihash:n={},version:o}){if(e==null)return $e(`Expected link but got ${e} instead`);if(Se(e)){if(r!=null&&e.code!==r)return $e(`Expected link to be CID with 0x${r.toString(16)} codec`);if(n.code!=null&&e.multihash.code!==n.code)return $e(`Expected link to be CID with 0x${n.code.toString(16)} hashing algorithm`);if(o!=null&&e.version!==o)return $e(`Expected link to be CID version ${o} instead of ${e.version}`);let[s,i]=n.digest!=null?[Ve.baseEncode(n.digest),Ve.baseEncode(e.multihash.digest)]:["",""];return s!==i?$e(`Expected link with "${s}" hash digest instead of "${i}"`):{ok:e}}else return $e(`Expected link to be a CID instead of ${e}`)}},em=new Yp({}),Tz=()=>em,qs=(t={})=>new Yp(t),Cz=t=>em.read(t),Iz=()=>em.optional();var fk={};F(fk,{did:()=>Bz,from:()=>Lz,match:()=>rm,read:()=>Pz});var tm=class extends ye{readWith(e,r){let n=r?`did:${r}:`:"did:";return e.startsWith(n)?{ok:e}:$e(`Expected a ${n} but got "${e}" instead`)}},WB=hn().refine(new tm),Bz=()=>WB,Pz=t=>WB.read(t),rm=(t={})=>hn().refine(new tm(t.method)),Lz=t=>rm({}).from(t);var mk={};F(mk,{match:()=>nm,read:()=>Rz,text:()=>Uz});var hk=hn(),nm=t=>t?hk.refine(new pk(t.pattern)):hk,Uz=nm,Rz=t=>hk.read(t),pk=class extends ye{readWith(e,r){return r.test(e)?{ok:e}:$e(`Expected to match ${r} but got "${e}" instead`)}};var HB=uk({"ucanto/message@7.0.0":Zp({execute:qs().array().optional(),delegate:ak({key:hn(),value:qs()}).array().optional()})}),Nz=({invocations:t,receipts:e})=>new yk({invocations:t,receipts:e}).buildIPLDView(),Oz=({root:t,store:e},r)=>{let n=ho(t,e,null);if(n===null)return r!==void 0?r:Fs(t);let o=dn.decode(n.bytes),[s,i]=HB.match(o,r);switch(s){case"ucanto/message@7.0.0":return new om({root:{...n,data:o},store:e});default:return i}},yk=class{constructor({invocations:e,receipts:r}){this.invocations=e,this.receipts=r}async buildIPLDView(e){let r=new Map,{invocations:n,...o}=await $z(this.invocations||[],r),{receipts:s,...i}=await Mz(this.receipts||[],r),a=await Np({"ucanto/message@7.0.0":{...o,...i}},r,e);return new om({root:a,store:r},{receipts:s,invocations:n})}},$z=async(t,e)=>{let r=[],n=[];for(let o of t){let s=await o.buildIPLDView();n.push(s.link()),r.push(s);for(let i of s.iterateIPLDBlocks())e.set(`${i.cid}`,i)}return{invocations:r,...n.length>0?{execute:n}:{}}},Mz=async(t,e)=>{if(t.length===0)return{};let r=new Map,n={};for(let[o,s]of t.entries()){let i=await s.buildIPLDView();for(let c of i.iterateIPLDBlocks())e.set(`${c.cid}`,c);let a=`${i.ran.link()}`;a in n?r.set(`${a}@${o}`,i):(n[a]=i.root.cid,r.set(a,i))}return{receipts:r,report:n}},om=class{constructor({root:e,store:r},{invocations:n,receipts:o}={}){this.root=e,this.store=r,this._invocations=n,this._receipts=o}*iterateIPLDBlocks(){for(let e of this.invocations)yield*e.iterateIPLDBlocks();for(let e of this.receipts.values())yield*e.iterateIPLDBlocks();yield this.root}get(e,r){let o=(this.root.data["ucanto/message@7.0.0"].report||{})[`${e}`];return o?zp({root:o,blocks:this.store}):r!==void 0?r:PB(`Message does not include receipt for ${e}`)}get invocationLinks(){return this.root.data["ucanto/message@7.0.0"].execute||[]}get invocations(){let e=this._invocations;return e||(e=this.invocationLinks.map(r=>Ws.view({root:r,blocks:this.store}))),e}get receipts(){let e=this._receipts;if(!e){e=new Map;let r=this.root.data["ucanto/message@7.0.0"].report||{};for(let[n,o]of Object.entries(r)){let s=zp({root:o,blocks:this.store});e.set(`${s.ran.link()}`,s)}}return e}};var ut={};F(ut,{code:()=>qB,contentType:()=>Fz,createWriter:()=>jz,decode:()=>gk,encode:()=>VB,link:()=>GB,name:()=>zz,write:()=>Wz});var Fz="application/vnd.ipld.car",zz="CAR",qB=514,sm=class{constructor(e=[],r=0){this.written=new Set,this.blocks=e,this.byteLength=r}write(...e){for(let r of e){let n=r.cid.toString(Ve);this.written.has(n)||(this.blocks.push(r),this.byteLength+=Er(r),this.written.add(n))}return this}flush(...e){let r=[];for(let s of e.reverse()){let i=s.cid.toString(Ve);this.written.has(i)||(this.blocks.unshift(s),this.byteLength+=Er({cid:s.cid,bytes:s.bytes}),this.written.add(i)),r.unshift(s.cid)}this.byteLength+=Bn({roots:r});let n=new ArrayBuffer(this.byteLength),o=Pn(n,{roots:r});for(let s of this.blocks)o.write(s);return o.close()}},jz=()=>new sm,VB=({roots:t=[],blocks:e})=>{let r=new sm;return e&&r.write(...e.values()),r.flush(...t)},gk=t=>{let e=Vr.fromBytes(t),r=[],n=new Map;for(let o of e.getRoots()){let s=e.get(o);s&&r.push(s)}for(let o of e.blocks())n.set(o.cid.toString(),o);return{roots:r,blocks:n}},GB=async(t,{hasher:e=ue}={})=>Fe(qB,await e.digest(t)),Wz=async(t,e)=>{let r=VB(t),n=await GB(r,e);return{bytes:r,cid:n}};var KB=t=>new wk(t),wk=class{constructor(e){this.id=e.id,this.options=e,this.codec=e.codec,this.channel=e.channel,this.hasher=e.hasher||ue}async execute(...e){return Hz(e,this)}},Hz=async(t,e)=>{let r=await zr.build({invocations:t}),n=await e.codec.encode(r,e),o=await e.channel.request(n);try{let s=await e.codec.decode(o);return r.invocationLinks.map(a=>s.get(a))}catch(s){let{message:i,...a}=s,c=[];for await(let u of r.invocationLinks){let l=await dl.issue({ran:u,result:{error:{...a,message:i}},issuer:{did(){return e.id.did()},sign(){return st.createNonStandard("",new Uint8Array)}}});c.push(l)}return c}};var fse=ul.delegate;var pl={};F(pl,{codec:()=>ut,contentType:()=>am,inbound:()=>Yz,outbound:()=>ej,request:()=>Vs,response:()=>Gs});var Vs={};F(Vs,{codec:()=>ut,contentType:()=>Oa,decode:()=>Gz,encode:()=>Vz});var Oa=ut.contentType,qz=Object.freeze({"content-type":Oa,accept:Oa}),Vz=(t,e)=>{let r=new Map;for(let o of t.iterateIPLDBlocks())r.set(`${o.cid}`,o);let n=ut.encode({roots:[t.root],blocks:r});return{headers:e?.headers||qz,body:n}},Gz=async({headers:t,body:e})=>{let{roots:r,blocks:n}=ut.decode(e);return zr.view({root:r[0].cid,store:n})};var Gs={};F(Gs,{codec:()=>ut,contentType:()=>hl,decode:()=>Jz,encode:()=>Zz});var hl=ut.contentType,Kz=Object.freeze({"content-type":hl}),Zz=(t,e)=>{let r=new Map;for(let o of t.iterateIPLDBlocks())r.set(`${o.cid}`,o);let n=ut.encode({roots:[t.root],blocks:r});return{headers:Kz,body:n}},Jz=async({headers:t,body:e})=>{let{roots:r,blocks:n}=ut.decode(e);return zr.view({root:r[0].cid,store:n})};var im=t=>new bk(t),bk=class{accept({headers:e}){let r=e["content-type"]||e["Content-Type"],n=this.decoders[r];if(!n)return{error:{status:415,message:"The server cannot process the request because the payload format is not supported. Please check the content-type header and try again with a supported media type.",headers:{accept:Object.keys(this.decoders).join(", ")}}};let o=Xz(e.accept||e.Accept||"*/*");for(let{category:s,type:i}of o)for(let a of this.encoders)if((s==="*"||s===a.category)&&(i==="*"||i===a.type))return{ok:{...a,decoder:n}};return{error:{status:406,message:"The requested resource cannot be served in the requested content type. Please specify a supported content type using the Accept header.",headers:{accept:JB(Object.values(this.encoders))}}}}constructor({decoders:e={},encoders:r={}}){if(this.decoders=e,Object.keys(e).length===0)throw new Error("At least one decoder MUST be provided");if(this.encoders=Object.entries(r).map(([n,o])=>({...kk(n),encoder:o})).sort((n,o)=>o.preference-n.preference),this.encoders.length===0)throw new Error("At least one encoder MUST be provided")}},ZB=t=>new xk(t),xk=class{constructor({decoders:e={},encoders:r={}}){if(this.decoders=e,Object.keys(e).length===0)throw new Error("At least one decoder MUST be provided");if(this.encoders=Object.entries(r).map(([n,o])=>({...kk(n),encoder:o})).sort((n,o)=>o.preference-n.preference),this.acceptType=JB(this.encoders),this.encoders.length===0)throw new Error("At least one encoder MUST be provided");this.encoder=this.encoders[0].encoder}encode(e){return this.encoder.encode(e,{accept:this.acceptType})}decode(e){let{headers:r}=e,n=r["content-type"]||r["Content-Type"],o=this.decoders[n]||this.decoders["*/*"];switch(e.status){case 415:case 406:throw Object.assign(new RangeError(new TextDecoder().decode(e.body)),{status:e.status,headers:e.headers})}if(!o)throw Object.assign(TypeError(`Can not decode response with content-type '${n}' because no matching transport decoder is configured.`),{error:!0});return o.decode(e)}},kk=t=>{let[e="*/*",r=""]=t.trim().split(";"),[n="*",o="*"]=e.split("/"),s=new URLSearchParams(r),i=parseFloat(s.get("q")||"0");return{category:n,type:o,preference:isNaN(i)?0:i}},Qz=({category:t,type:e,preference:r})=>`${t}/${e}${r?`;q=${r}`:""}`,Xz=t=>t.split(",").map(kk).sort((e,r)=>r.preference-e.preference),JB=t=>t.map(Qz).join(", ");var am=ut.contentType,Yz=im({decoders:{[Oa]:Vs},encoders:{[hl]:Gs}}),ej=ZB({encoders:{[Oa]:Vs},decoders:{[hl]:Gs}});var cm={};F(cm,{open:()=>tj});var tj=({url:t,method:e="POST",fetch:r})=>{if(!r)if(typeof globalThis.fetch<"u")r=globalThis.fetch.bind(globalThis);else throw new TypeError("ucanto HTTP transport got undefined `fetch`. Try passing in a `fetch` implementation explicitly.");return new Sk({url:t,method:e,fetch:r})},Sk=class{constructor({url:e,fetch:r,method:n}){this.fetch=r,this.method=n,this.url=e}async request({headers:e,body:r}){let n=await this.fetch(this.url.href,{headers:e,body:r,method:this.method}),o=n.ok?await n.arrayBuffer():Ek.throw("HTTP Request failed",n);return{headers:n.headers.entries?Object.fromEntries(n.headers.entries()):{},body:new Uint8Array(o)}}},Ek=class extends Error{static throw(e,r){throw new this(e,r)}constructor(e,{url:r,status:n=500,statusText:o="Server error"}){super(e),this.name="HTTPError",this.url=r,this.status=n,this.statusText=o}};var bse=new TextEncoder,xse=new TextDecoder;var _k={};F(_k,{contentType:()=>QB,encode:()=>oj});var QB="application/cbor",nj=Object.freeze({"content-type":QB}),oj=(t,e)=>{let r=[];for(let o of t.receipts.values()){let s=o.out;s.ok?r.push(s.ok):r.push({...s.error,error:!0})}let n=$s(r);return{headers:nj,body:n}};var um={};F(um,{contentType:()=>sj,decode:()=>ij});var sj="application/car",ij=async({body:t})=>{let{roots:e,blocks:r}=gk(t),n=[];for(let{cid:s}of e){let i=Ws.view({root:s,blocks:r});n.push(i)}return await zr.build({invocations:n})};var{contentType:aj}=um;var vse=im({decoders:{[aj]:um,[am]:Vs},encoders:{"*/*;q=0.1":_k,[am]:Gs}});var ml=t=>t,XB=t=>Object.entries(t),YB=([t,...e])=>{let r=t.map(n=>[n]);for(let n of e){let o=r.splice(0);for(let s of n)for(let i of o)r.push([...i,s])}return r},Ak=(t,e)=>{let[r,n]=t.length<e.length?[new Set(t),new Set(e)]:[new Set(e),new Set(t)];for(let o of r)n.has(o)||r.delete(o);return[...r]};var yl=class extends yr{constructor(e,r,n){super(),this.claimed=e,this.delegated=r,this.cause=n,this.name=ml("EscalatedCapability")}describe(){return`Constraint violation: ${this.cause.message}`}},pn=class extends yr{constructor(e,r){super(),this.name=ml("InvalidClaim"),this.causes=e,this.context=r}describe(){return[`Can not derive ${this.context} from delegated capabilities:`,...this.causes.map(e=>Dk(e.message))].join(`
|
22
|
-
`)}get cause(){if(this.causes.length!==1)return this;{let[e]=this.causes,r=e.name==="InvalidClaim"?e.cause:e;return Object.defineProperties(this,{cause:{value:r}}),r}}};var mo=class extends yr{constructor(e,r){super(),this.name=ml("MalformedCapability"),this.capability=e,this.cause=r}describe(){return[`Encountered malformed '${this.capability.can}' capability: ${e8(this.capability)}`,Dk(this.cause.message)].join(`
|
23
|
-
`)}},$a=class extends yr{constructor(e){super(),this.name=ml("UnknownCapability"),this.capability=e}describe(){return`Encountered unknown capability: ${e8(this.capability)}`}};var e8=(t,e)=>JSON.stringify(t,(r,n)=>Se(n)?n.toString():n,e),lj=(t,e=" ")=>`${e}${t.split(`
|
24
|
-
`).join(`
|
25
|
-
${e}`)}`,Dk=t=>lj(`- ${t}`);var mn=({derives:t=kj,nb:e=dj,...r})=>new Tk({derives:t,nb:e,...r}),dj=ct.struct({}),fj=(t,e)=>new Ck(t,e),hj=(...t)=>new Ik(t),pj=({from:t,to:e,derives:r})=>new Bk(t,e,r),lm=class{match(e){return{error:new $a(e.capability)}}select(e){return xj(this,e)}derive({derives:e,to:r}){return pj({derives:e,to:r,from:this})}},gl=class extends lm{or(e){return fj(this,e)}and(e){return hj(this,e)}},Tk=class extends gl{constructor(e){super(),this.descriptor=e,this.schema=ct.struct({can:ct.literal(e.can),with:e.with,nb:e.nb})}create(e){let{descriptor:r,can:n}=this,o=r.nb,s=e.nb||{},i=r.with.read(e.with);if(i.error)throw Object.assign(new Error(`Invalid 'with' - ${i.error.message}`),{cause:i});let a=r.nb.read(s);if(a.error)throw Object.assign(new Error(`Invalid 'nb' - ${a.error.message}`),{cause:a});return t8({can:n,with:i.ok,nb:a.ok})}invoke({with:e,nb:r,...n}){return ll({...n,capability:this.create({with:e,nb:r})})}async delegate({nb:e={},with:r,...n}){let{descriptor:o,can:s}=this,i=o.nb,a=o.with.read(r);if(a.error)throw Object.assign(new Error(`Invalid 'with' - ${a.error.message}`),{cause:a});let c=o.nb.partial().read(e);if(c.error)throw Object.assign(new Error(`Invalid 'nb' - ${c.error.message}`),{cause:c});return js({capabilities:[t8({can:s,with:a.ok,nb:c.ok})],...n})}get can(){return this.descriptor.can}match(e){let r=wj(this.descriptor,e);return r.error?r:{ok:new Pk(e,r.ok,this.descriptor)}}toString(){return JSON.stringify({can:this.descriptor.can})}},t8=({can:t,with:e,nb:r})=>({can:t,with:e,...mj(r)?{}:{nb:r}}),mj=t=>{for(let e in t)return!1;return!0},Ck=class extends gl{constructor(e,r){super(),this.left=e,this.right=r}match(e){let r=this.left.match(e);if(r.error){let n=this.right.match(e);return n.error?n.error.name==="MalformedCapability"?n:r:n}else return r}toString(){return`${this.left.toString()}|${this.right.toString()}`}},Ik=class t extends lm{constructor(e){super(),this.selectors=e}match(e){let r=[];for(let n of this.selectors){let o=n.match(e);if(o.error)return o;r.push(o.ok)}return{ok:new dm(r)}}select(e){return r8(this,e)}and(e){return new t([...this.selectors,e])}toString(){return`[${this.selectors.map(String).join(", ")}]`}},Bk=class extends gl{constructor(e,r,n){super(),this.from=e,this.to=r,this.derives=n}create(e){return this.to.create(e)}invoke(e){return this.to.invoke(e)}delegate(e){return this.to.delegate(e)}get can(){return this.to.can}match(e){let r=this.to.match(e);return r.error?r:{ok:new Lk(r.ok,this.from,this.derives)}}toString(){return this.to.toString()}},Pk=class t{constructor(e,r,n){this.source=[e],this.value=r,this.descriptor=n}get can(){return this.value.can}get proofs(){let e=[this.source[0].delegation];return Object.defineProperties(this,{proofs:{value:e}}),e}prune(e){return e.canIssue(this.value,this.source[0].delegation.issuer.did())?null:this}select(e){let r=[],n=[],o=[];for(let s of e){let i=bj(this.descriptor,this.value,s);if(i.ok){let a=this.descriptor.derives(this.value,i.ok);a.error?n.push(new pn([new yl(this.value,i.ok,a.error)],this)):o.push(new t(s,i.ok,this.descriptor))}else switch(i.error.name){case"UnknownCapability":r.push(i.error.capability);break;case"MalformedCapability":default:n.push(new pn([i.error],this))}}return{matches:o,unknown:r,errors:n}}toString(){let{nb:e}=this.value;return JSON.stringify({can:this.descriptor.can,with:this.value.with,nb:e&&Object.keys(e).length>0?e:void 0})}},Lk=class t{constructor(e,r,n){this.selected=e,this.from=r,this.derives=n}get can(){return this.value.can}get source(){return this.selected.source}get proofs(){let e=[];for(let{delegation:r}of this.selected.source)e.push(r);return Object.defineProperties(this,{proofs:{value:e}}),e}get value(){return this.selected.value}prune(e){let r=this.selected.prune(e);return r?new t(r,this.from,this.derives):null}select(e){let{derives:r,selected:n,from:o}=this,{value:s}=n,i=n.select(e),a=o.select(e),c=[],u=[];for(let l of a.matches){let d=r(s,l.value);d.error?u.push(new pn([new yl(s,l.value,d.error)],this)):c.push(l)}return{unknown:Ak(i.unknown,a.unknown),errors:[...u,...i.errors,...a.errors.map(l=>new pn([l],this))],matches:[...i.matches.map(l=>new t(l,o,r)),...c]}}toString(){return this.selected.toString()}},dm=class t{constructor(e){this.matches=e}get selectors(){return this.matches}get source(){let e=[];for(let r of this.matches)e.push(...r.source);return Object.defineProperties(this,{source:{value:e}}),e}prune(e){let r=[];for(let n of this.matches){let o=n.prune(e);o&&r.push(o)}return r.length===0?null:new t(r)}get proofs(){let e=[];for(let{delegation:r}of this.source)e.push(r);return Object.defineProperties(this,{proofs:{value:e}}),e}get value(){let e=[];for(let r of this.matches)e.push(r.value);return Object.defineProperties(this,{value:{value:e}}),e}select(e){return r8(this,e)}toString(){return`[${this.matches.map(e=>e.toString()).join(", ")}]`}},yj=(t,e,r)=>{switch(t){case e:case"*":return e;default:return t.endsWith("/*")&&e.startsWith(t.slice(0,-1))?e:r}},gj=(t,e,r)=>{switch(t){case e:case"ucan:*":return e;default:return r}},wj=(t,e)=>{let{delegation:r}=e,n=e.capability;if(t.can!==n.can)return{error:new $a(n)};let o=t.with.read(n.with);if(o.error)return{error:new mo(n,o.error)};let s=t.nb.read(n.nb||{});return s.error?{error:new mo(n,s.error)}:{ok:new fm(t.can,o.ok,s.ok,r)}},bj=(t,e,{capability:r,delegation:n})=>{let o=yj(r.can,e.can,null);if(o==null)return{error:new $a(r)};let s=gj(r.with,e.with,r.with),i=t.with.read(s);if(i.error)return{error:new mo(r,i.error)};let a=t.nb.read({...e.nb,...r.nb});return a.error?{error:new mo(r,a.error)}:{ok:new fm(o,i.ok,a.ok,n)}},fm=class{constructor(e,r,n,o){this.can=e,this.with=r,this.delegation=o,this.nb=n}},xj=(t,e)=>{let r=[],n=[],o=[];for(let s of e){let i=t.match(s);if(i.error)switch(i.error.name){case"UnknownCapability":r.push(i.error.capability);break;case"MalformedCapability":default:o.push(new pn([i.error],i.error.capability))}else n.push(i.ok)}return{matches:n,errors:o,unknown:r}},r8=(t,e)=>{let r,n=[],o=[];for(let i of t.selectors){let a=i.select(e);r=r?Ak(r,a.unknown):a.unknown;for(let c of a.errors)o.push(new pn([c],t));n.push(a.matches)}let s=YB(n).map(i=>new dm(i));return{unknown:r||[],errors:o,matches:s}},kj=(t,e)=>{if(e.with.endsWith("*")){if(!t.with.startsWith(e.with.slice(0,-1)))return ct.error(`Resource ${t.with} does not match delegated ${e.with} `)}else if(e.with!==t.with)return ct.error(`Resource ${t.with} is not contained by ${e.with}`);let r=e.nb||{},n=t.nb||{},o=XB(r);for(let[s,i]of o)if(n[s]!=i)return ct.error(`${String(s)}: ${n[s]} violates ${i}`);return{ok:!0}};var Zse=mn({can:"clock/*",with:St.match({protocol:"did:"})}),Jse=mn({can:"clock/follow",with:St.match({protocol:"did:"}),nb:ct.struct({iss:St.match({protocol:"did:"}).optional(),with:St.match({protocol:"did:"}).optional()})}),Qse=mn({can:"clock/unfollow",with:St.match({protocol:"did:"}),nb:ct.struct({iss:St.match({protocol:"did:"}).optional(),with:St.match({protocol:"did:"}).optional()})}),Xse=mn({can:"clock/following",with:St.match({protocol:"did:"})}),n8=mn({can:"clock/head",with:St.match({protocol:"did:"})}),o8=mn({can:"clock/advance",with:St.match({protocol:"did:"}),nb:ct.struct({event:fl.match({version:1})})});var Sj="https://clock.web3.storage",Ej="did:web:clock.web3.storage";async function s8({issuer:t,with:e,proofs:r,audience:n},o,s){let i=s?.connection??a8(),a=s?.blocks?[Object.fromEntries(s.blocks.map(u=>[u.cid.toString(),u.cid]))]:[],c=o8.invoke({issuer:t,audience:n??i.id,with:e,nb:{event:o},proofs:r,facts:a});for(let u of s?.blocks??[])c.attach(u);return c.execute(i)}async function i8({issuer:t,with:e,proofs:r,audience:n},o){let s=o?.connection??a8();return await n8.invoke({issuer:t,audience:n??s.id,with:e,proofs:r}).execute(s)}function a8(t){let e=t?.serviceURL??new URL(Sj);return KB({id:t?.servicePrincipal??Fu(Ej),codec:pl.outbound,channel:cm.open({url:e,method:"POST"})})}var Uk=class extends gn{constructor(){super(...arguments);w(this,"eventBlocks",new pt);w(this,"parents",[])}issuer(r){let{issuer:n}=r._agent;if(!n.signatureAlgorithm)throw new Error("issuer not valid");return n}async dataDownload(r){Zs(r);let n=`https://${r.car}.ipfs.w3s.link/`,o=await fetch(n);if(o.ok)return new Uint8Array(await o.arrayBuffer());throw new Error(`Failed to download ${n}`)}async dataUpload(r,n,o){let s=await this.authorizedClient();if(!s)throw new Error("client not initialized");return Zs(n),n.type==="file"&&o.public&&await s.uploadCAR(new Blob([r])),await s.uploadFile(new Blob([r]))}async metaDownload(r){let n=await this.authorizedClient();if(r.branch!=="main")throw new Error("todo, implement space per branch");let o=await this.clockProofsForDb(),s=await i8({issuer:this.issuer(n),with:this.clockSpaceDIDForDb(),proofs:o});if(s.out.ok)return this.fetchAndUpdateHead(s.out.ok.head);throw console.log("w3clock error",s.out.error),new Error(`Failed to download ${r.name}`)}async metaUpload(r,n){let o=await this.authorizedClient();if(n.branch!=="main")throw new Error("todo, implement space per branch");let s=await this.clockProofsForDb(),i={dbMeta:r},a=await Bs.create(i,this.parents),c=new pt;await this.eventBlocks.put(a.cid,a.bytes),await c.put(a.cid,a.bytes);let{bytes:u}=await ga([a.cid],c);await o.uploadCAR(new Blob([u]));let l=[];for(let{bytes:m}of this.eventBlocks.entries())l.push(await el(m));let d=await s8({issuer:this.issuer(o),with:this.clockSpaceDIDForDb(),proofs:s},a.cid,{blocks:l}),{ok:p,error:f}=d.root.data?.ocm.out;if(f)throw new Error(JSON.stringify(f));this.parents=[a.cid];let h=p.head;return this.fetchAndUpdateHead(h)}async fetchAndUpdateHead(r){let n=[],o=this.eventBlocks;for(let s of r){let i=await o.get(s);if(i){let a=await el(i.bytes);n.push(a.value.data.dbMeta)}else{let a=`https://${s.toString()}.ipfs.w3s.link/`,c=await fetch(a,{redirect:"follow"});if(c.ok){let u=new Uint8Array(await c.arrayBuffer());await o.put(s,u);let l=await el(u);n.push(l.value.data.dbMeta)}else throw new Error(`Failed to download ${a}`)}}return this.parents=r,n}},Ma=class extends Uk{constructor(){super();w(this,"activated",null);w(this,"authorizing");w(this,"authorizingComplete");w(this,"authorizingFailed");this.authorizing=new Promise((r,n)=>{this.authorizingComplete=r,this.authorizingFailed=n}),this.ready=Promise.resolve().then(()=>this.initializeClient()),this.ready.then(()=>{this.activated&&this.authorizingComplete()}),this.authorizing.then(()=>{this.startBackgroundSync()})}async startBackgroundSync(){await new Promise(r=>setTimeout(r,1500)),await this.refresh().catch(async r=>{console.log("refresh error",r),await new Promise(n=>setTimeout(n,5e3))}),await this.startBackgroundSync()}async clockProofsForDb(){let r=await this.authorizedClient(),n=this.clockSpaceDIDForDb(),o=r.proofs([{can:"clock/*",with:n}]);if(!o.length)throw new Error("missing clock/* capability on account space");return o}};var hm=(t,e)=>{let r=t;r.type==="clock-space"?e(r.issuer,r.schema):r.type==="member-delegation"&&r.status==="applied"&&e(r.audience,r.schema)},pm=class extends Ma{constructor(){super();w(this,"accountDb");w(this,"client",null);w(this,"email",null);this.accountDb=E0("_connect-web3");let{_crdt:{blocks:{loader:r}}}=this.accountDb;r?.connectRemote(this),this.authorizing.then(()=>{this.serviceAccessRequests()})}async accountEmail(){let n=(await this.authorizedClient()).currentSpace(),{rows:o}=await this.accountDb.query("accountSpace",{key:n.did()});for(let s of o){let i=s.doc;if(i.email)return i.email}}async authorize(r){let n=this.client;await n.authorize(r,{capabilities:[{can:"clock/*"},{can:"space/*"},{can:"provider/add"},{can:"store/*"},{can:"upload/*"}]});let o=this.bestSpace(n);o||(o=await n.createSpace("_account")),await n.setCurrentSpace(o.did()),o.registered()||await n.registerSpace(r);let{rows:s}=await this.accountDb.query("accountSpace",{key:o.did()});for(let i of s){let a=i.doc;a.email||(a.email=r,await this.accountDb.put(a))}this.email=r,this.authorizingComplete()}async initializeClient(){this.client=await this.connectClient()}async authorizedClient(){return await this.authorizing,this.client}clockSpaceDIDForDb(){return this.client.currentSpace().did()}async connectClient(){let r=await AC(),n=this.bestSpace(r);return n&&n.registered()?(this.activated=!0,await r.setCurrentSpace(n.did())):this.activated=!1,r}bestSpace(r){return r.spaces().find(s=>s.registered())}encodeSpaceName(r){let n=encodeURIComponent(r.schema),o=encodeURIComponent(r.name);return`_clock/${n}/${o}`}async authorizedClockSpace(r){await this.loaded;let{rows:n}=await this.accountDb.query("clockName",{key:this.encodeSpaceName(r)});if(n.length){let o=n[0].doc,s=o.with;if(o.schema!==r.schema)throw new Error(`clock schema mismatch, expected ${r.schema} got ${o.schema}`);return await this.joinExistingSpace(o),s}else return await this.createNewSpace(r)}async createNewSpace(r){let n=this.client,o=this.encodeSpaceName(r);console.log("creating new clock space",this.email,this.encodeSpaceName(r));let s=await n.createSpace(o),i={type:"clock-space",...r,clockName:o,email:this.email,with:s.did(),accountSpace:n.currentSpace().did(),issuer:this.issuer(n).did(),ua:navigator.userAgent,created:Date.now()};return await this.accountDb.put(i),s.did()}async joinExistingSpace(r){if(!this.client.proofs([{can:"clock/*",with:r.with}]).length){console.log("requesting access for",r.schema,r.with);let s=this.issuer(this.client).did();await this.joinSchema(r.schema,s),await this.waitForAccess(r,s)}return console.log("joined existing space",r.with),r.with}async joinSchema(r,n){let o={_id:`schema-member/${r}/${n}`,type:"schema-member",member:n,schema:r,ua:navigator.userAgent};await this.accountDb.put(o)}async waitForAccess(r,n){let o=()=>{},s=new Promise(u=>{o=u}),a=(await this.accountDb.query((u,l)=>{let d=u;u.type==="member-delegation"&&d.audience&&d.status==="pending"&&l(d.audience)},{key:n,includeDocs:!0})).rows.map(u=>u.doc),c=!1;for(let u of a)await this.applyDelegation(u),u.status="applied",await this.accountDb.put(u),u.with===r.with&&(c=!0);if(c)o();else{let u=this.accountDb.subscribe(async l=>{for(let d of l){let p=d;p.type==="member-delegation"&&p.audience===n&&p.status==="pending"&&(await this.applyDelegation(p),p.status="applied",await this.accountDb.put(p),p.with===d.with&&(c=!0))}c&&(u(),o())})}return s}async applyDelegation(r){let n=await sr.extract(r.delegation);if(!n.ok)throw new Error("missing loadedDelegation");let o=this.client;if(await o.addProof(n.ok),!o.proofs([{can:"clock/*",with:r.with}]).length)throw new Error("failed granting clock/* capability");console.log("accepting delegation",r)}async serviceAccessRequests(){let{rows:r}=await this.accountDb.query(hm,{includeDocs:!0,key:this.issuer(this.client).did()}),n=[...new Set(r.map(({doc:u})=>u.schema))],{rows:o}=await this.accountDb.query((u,l)=>{let d=u;d.type==="schema-member"&&l(d.schema,d.member)},{keys:n}),s=new Set(o.map(({value:u})=>u));s.delete(this.issuer(this.client).did());let i=[...s],{rows:a}=await this.accountDb.query(hm,{includeDocs:!0,keys:i});for(let u of i)for(let l of r)a.find(p=>p.doc.with===l.doc.with&&p.key===u)||await this.delegateAccess(l.doc,u);return this.accountDb.subscribe(async u=>{for(let l of u){let d=l;if(d.type==="schema-member"){let p=d.member;if(p!==this.issuer(this.client).did()){let{rows:f}=await this.accountDb.query(hm,{includeDocs:!0,key:this.issuer(this.client).did()}),{rows:h}=await this.accountDb.query(hm,{includeDocs:!0,key:p});for(let m of f)h.find(g=>g.doc.with===m.doc.with&&g.key===p)||await this.delegateAccess(m.doc,p)}}}})}async delegateAccess(r,n){let o=this.client;if(!o.proofs([{can:"clock/*",with:r.with}]).length){console.log("missing clock/* capability, cannot delegate: "+r.with);return}let i={issuer:this.issuer(o),lifetimeInSeconds:60*60*24*365,audience:{did:()=>n},capabilities:[{can:"clock/*",with:r.with}],proofs:o.proofs()},a=`delegation/${r.with}/${n}`;if(await this.accountDb.get(a).catch(()=>null)){console.log("delegation already exists",a);return}console.log("delegating access",i);let l=await(await Lt(i)).archive();if(!l.ok)throw new Error("missing delegationCarBytes");let d={_id:a,type:"member-delegation",audience:n,with:r.with,schema:r.schema,status:"pending",delegation:l.ok};await this.accountDb.put(d)}};var wl=class extends Ma{constructor(r){super();w(this,"accountConnection");w(this,"authorized",null);w(this,"params");w(this,"clockSpaceDID");this.accountConnection=new pm,this.params=r}async authorize(r){return await this.accountConnection.authorize(r)}async accountEmail(){return await this.accountConnection.accountEmail()}async authorizedClient(){return await this.authorizing,this.accountConnection.authorizedClient()}clockSpaceDIDForDb(){return this.clockSpaceDID}async initializeClient(){await this.accountConnection.ready,this.authorized=this.accountConnection.activated,await this.accountConnection.authorizedClockSpace(this.params).then(r=>{this.clockSpaceDID=r,this.activated=!0}).catch(this.authorizingFailed)}};var Rk=class extends gn{constructor({metaUpload:e,metaDownload:r,dataUpload:n,dataDownload:o}){super(),this.metaUpload=e,this.metaDownload=r,this.dataUpload=n,this.dataDownload=o}},Fa=new Map,Up={s3:({_crdt:{blocks:{loader:t}}},{upload:e,download:r})=>{let n=new ja(e,r);return t.connectRemote(n),n},raw:({_crdt:{blocks:{loader:t}}},e)=>{let r=new Rk(e);return t.connectRemote(r),r},ipfs:(t,e)=>{let{name:r,_crdt:{blocks:{loader:n}}}=t;if(!r)throw new Error("database name is required");if(Fa.has(r))return Fa.get(r);!e&&location&&(e=location.origin);let o=new wl({name:r,schema:e});return n.connectRemote(o),Fa.set(r,o),o},hybrid:(t,e)=>{let{name:r,_crdt:{blocks:{loader:n}}}=t;if(!r)throw new Error("database name is required");if(Fa.has(r))return Fa.get(r);!e&&location&&(e=location.origin);let o=new wl({name:r,schema:e}),s={upload:"https://04rvvth2b4.execute-api.us-east-2.amazonaws.com/uploads",download:"https://sam-app-s3uploadbucket-e6rv1dj2kydh.s3.us-east-2.amazonaws.com"},i=new ja(s.upload,s.download);return n.connectRemote(o,i),Fa.set(r,o),o}};function Zs(t){let{type:e,name:r,car:n}=t;if(!r)throw new Error("name is required");if(!n)throw new Error("car is required");if(e!=="file"&&e!=="data")throw new Error("type must be file or data")}function gm(t){let{name:e,branch:r}=t;if(!e)throw new Error("name is required");if(!r)throw new Error("branch is required")}return m8(Aj);})();
|
1
|
+
"use strict";var Fireproof=(()=>{var gw=Object.create;var mn=Object.defineProperty;var ww=Object.getOwnPropertyDescriptor;var bw=Object.getOwnPropertyNames;var xw=Object.getPrototypeOf,kw=Object.prototype.hasOwnProperty;var vw=(t,e,r)=>e in t?mn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var H=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Q=(t,e)=>{for(var r in e)mn(t,r,{get:e[r],enumerable:!0})},Al=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of bw(e))!kw.call(t,o)&&o!==r&&mn(t,o,{get:()=>e[o],enumerable:!(n=ww(e,o))||n.enumerable});return t};var W=(t,e,r)=>(r=t!=null?gw(xw(t)):{},Al(e||!t||!t.__esModule?mn(r,"default",{value:t,enumerable:!0}):r,t)),Ew=t=>Al(mn({},"__esModule",{value:!0}),t);var k=(t,e,r)=>(vw(t,typeof e!="symbol"?e+"":e,r),r),_l=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)};var Z=(t,e,r)=>(_l(t,e,"read from private field"),r?r.call(t):e.get(t)),nt=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},fe=(t,e,r,n)=>(_l(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r);var ea=(t,e,r,n)=>({set _(o){fe(t,e,o,r)},get _(){return Z(t,e,n)}});var ad=H((mA,sd)=>{sd.exports=Ua;var id=128,v0=127,E0=~v0,S0=Math.pow(2,31);function Ua(t,e,r){if(Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw Ua.bytes=0,new RangeError("Could not encode varint");e=e||[],r=r||0;for(var n=r;t>=S0;)e[r++]=t&255|id,t/=128;for(;t&E0;)e[r++]=t&255|id,t>>>=7;return e[r]=t|0,Ua.bytes=r-n+1,e}});var ld=H((gA,ud)=>{ud.exports=Pa;var A0=128,cd=127;function Pa(t,n){var r=0,n=n||0,o=0,i=n,s,c=t.length;do{if(i>=c||o>49)throw Pa.bytes=0,new RangeError("Could not decode varint");s=t[i++],r+=o<28?(s&cd)<<o:(s&cd)*Math.pow(2,o),o+=7}while(s>=A0);return Pa.bytes=i-n,r}});var dd=H((wA,fd)=>{var _0=Math.pow(2,7),B0=Math.pow(2,14),C0=Math.pow(2,21),T0=Math.pow(2,28),I0=Math.pow(2,35),L0=Math.pow(2,42),D0=Math.pow(2,49),N0=Math.pow(2,56),U0=Math.pow(2,63);fd.exports=function(t){return t<_0?1:t<B0?2:t<C0?3:t<T0?4:t<I0?5:t<L0?6:t<D0?7:t<N0?8:t<U0?9:10}});var ni=H((bA,hd)=>{hd.exports={encode:ad(),decode:ld(),encodingLength:dd()}});var Zh=H(bc=>{bc.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"+sx(String(r),3)+"M"+String(n);return t>0?"F"+o:"D"+Yh(o)};bc.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?Yh(t):t).slice(2).split("M");return+((e?"-":"")+r[1]+"e"+String(Number(r[0])-500))};function Yh(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 sx(t,e){return" ".repeat(e-t.length).substr(0,e)+t}});var tp=H(ep=>{var ax={"?":"?@","!":"??",'"':"?%"};function cx(t){return/[!"]/.test(t)?t.replace(/[\?!"]/g,function(e){return ax[e]}):t}var ux={"?@":"?","??":"!","?%":'"'};function lx(t){return/\?[%\?@]/.test(t)?t.replace(/\?[%\?@]/g,function(e){return ux[e]}):t}ep.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):cx(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(lx(p)));for(var g=a-h,w=g;w<a;w++)s[w+1]=[],a=g,c=s[a]}return s[0][0]}}});var np=H(J=>{var fx=Zh(),dx=tp(),tB=J.flip=function(t){var e=t.toString(),r="";for(var n in e)r+=e[n]=="."?".":9-+e[n];return r};J.number=fx;J.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)}};J.encode=function(t){return J[typeof t].encode(t)};J.decode=function(t){if(t==="")return t;if(!rp[t[0]])throw new Error("no decoder for:"+JSON.stringify(t));return rp[t[0]](t)};J.object=dx.factory(J);J.boolean={encode:function(t){return t?"C":"B"},decode:function(t){return t==="C"}};J.undefined={encode:function(t){return"L"},decode:function(){}};var rp={A:J.object.decode,B:J.boolean.decode,C:J.boolean.decode,D:J.number.decode,F:J.number.decode,J:J.string.decode,K:J.object.decode,L:J.undefined.decode};J.buffer=!1;J.type="charwise"});var Fp=H((ZB,Pp)=>{"use strict";Pp.exports=qx;function qx(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 zp=H(Rp=>{"use strict";var Zi=Rp;Zi.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 Qr=new Array(64),Op=new Array(123);for(Oe=0;Oe<64;)Op[Qr[Oe]=Oe<26?Oe+65:Oe<52?Oe+71:Oe<62?Oe-4:Oe-59|43]=Oe++;var Oe;Zi.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++]=Qr[u>>2],a=(u&3)<<4,c=1;break;case 1:i[s++]=Qr[a|u>>4],a=(u&15)<<2,c=2;break;case 2:i[s++]=Qr[a|u>>6],i[s++]=Qr[u&63],c=0;break}s>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,i)),s=0)}return c&&(i[s++]=Qr[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 Mp="invalid encoding";Zi.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=Op[a])===void 0)throw Error(Mp);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(Mp);return n-o};Zi.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var Hp=H((t3,$p)=>{"use strict";$p.exports=es;function es(){this._listeners={}}es.prototype.on=function(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this};es.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};es.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 Qp=H((r3,Gp)=>{"use strict";Gp.exports=jp(jp);function jp(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,Vp),t.writeFloatBE=e.bind(null,qp);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,Wp),t.readFloatBE=r.bind(null,Kp)}(),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,Vp,0,4),t.writeDoubleBE=e.bind(null,qp,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,Wp,0,4),t.readDoubleBE=r.bind(null,Kp,4,0)}(),t}function Vp(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 qp(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 Wp(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function Kp(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}});var Jp=H((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 Yp=H(Xp=>{"use strict";var Vc=Xp;Vc.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};Vc.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))};Vc.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 ey=H((o3,Zp)=>{"use strict";Zp.exports=Wx;function Wx(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 ry=H((i3,ty)=>{"use strict";ty.exports=re;var to=lt();function re(t,e){this.lo=t>>>0,this.hi=e>>>0}var cr=re.zero=new re(0,0);cr.toNumber=function(){return 0};cr.zzEncode=cr.zzDecode=function(){return this};cr.length=function(){return 1};var Kx=re.zeroHash="\0\0\0\0\0\0\0\0";re.fromNumber=function(e){if(e===0)return cr;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 re(n,o)};re.from=function(e){if(typeof e=="number")return re.fromNumber(e);if(to.isString(e))if(to.Long)e=to.Long.fromString(e);else return re.fromNumber(parseInt(e,10));return e.low||e.high?new re(e.low>>>0,e.high>>>0):cr};re.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};re.prototype.toLong=function(e){return to.Long?new to.Long(this.lo|0,this.hi|0,!!e):{low:this.lo|0,high:this.hi|0,unsigned:!!e}};var Bt=String.prototype.charCodeAt;re.fromHash=function(e){return e===Kx?cr:new re((Bt.call(e,0)|Bt.call(e,1)<<8|Bt.call(e,2)<<16|Bt.call(e,3)<<24)>>>0,(Bt.call(e,4)|Bt.call(e,5)<<8|Bt.call(e,6)<<16|Bt.call(e,7)<<24)>>>0)};re.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)};re.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};re.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};re.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 lt=H(qc=>{"use strict";var D=qc;D.asPromise=Fp();D.base64=zp();D.EventEmitter=Hp();D.float=Qp();D.inquire=Jp();D.utf8=Yp();D.pool=ey();D.LongBits=ry();D.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node);D.global=D.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||qc;D.emptyArray=Object.freeze?Object.freeze([]):[];D.emptyObject=Object.freeze?Object.freeze({}):{};D.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};D.isString=function(e){return typeof e=="string"||e instanceof String};D.isObject=function(e){return e&&typeof e=="object"};D.isset=D.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};D.Buffer=function(){try{var t=D.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch{return null}}();D._Buffer_from=null;D._Buffer_allocUnsafe=null;D.newBuffer=function(e){return typeof e=="number"?D.Buffer?D._Buffer_allocUnsafe(e):new D.Array(e):D.Buffer?D._Buffer_from(e):typeof Uint8Array>"u"?e:new Uint8Array(e)};D.Array=typeof Uint8Array<"u"?Uint8Array:Array;D.Long=D.global.dcodeIO&&D.global.dcodeIO.Long||D.global.Long||D.inquire("long");D.key2Re=/^true|false|0|1$/;D.key32Re=/^-?(?:0|[1-9][0-9]*)$/;D.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;D.longToHash=function(e){return e?D.LongBits.from(e).toHash():D.LongBits.zeroHash};D.longFromHash=function(e,r){var n=D.LongBits.fromHash(e);return D.Long?D.Long.fromBits(n.lo,n.hi,r):n.toNumber(!!r)};function ny(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}D.merge=ny;D.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)};function oy(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&&ny(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}D.newError=oy;D.ProtocolError=oy("ProtocolError");D.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]}};D.oneOfSetter=function(e){return function(r){for(var n=0;n<e.length;++n)e[n]!==r&&delete this[e[n]]}};D.toJSONOptions={longs:String,enums:String,bytes:String,json:!0};D._configure=function(){var t=D.Buffer;if(!t){D._Buffer_from=D._Buffer_allocUnsafe=null;return}D._Buffer_from=t.from!==Uint8Array.from&&t.from||function(r,n){return new t(r,n)},D._Buffer_allocUnsafe=t.allocUnsafe||function(r){return new t(r)}}});var rs=H((a3,cy)=>{"use strict";cy.exports=O;var De=lt(),Wc,ts=De.LongBits,iy=De.base64,sy=De.utf8;function ro(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}function Gc(){}function Gx(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function O(){this.len=0,this.head=new ro(Gc,0,0),this.tail=this.head,this.states=null}var ay=function(){return De.Buffer?function(){return(O.create=function(){return new Wc})()}:function(){return new O}};O.create=ay();O.alloc=function(e){return new De.Array(e)};De.Array!==Array&&(O.alloc=De.pool(O.alloc,De.Array.prototype.subarray));O.prototype._push=function(e,r,n){return this.tail=this.tail.next=new ro(e,r,n),this.len+=r,this};function Qc(t,e,r){e[r]=t&255}function Qx(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}function Jc(t,e){this.len=t,this.next=void 0,this.val=e}Jc.prototype=Object.create(ro.prototype);Jc.prototype.fn=Qx;O.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new Jc((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this};O.prototype.int32=function(e){return e<0?this._push(Xc,10,ts.fromNumber(e)):this.uint32(e)};O.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)};function Xc(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}O.prototype.uint64=function(e){var r=ts.from(e);return this._push(Xc,r.length(),r)};O.prototype.int64=O.prototype.uint64;O.prototype.sint64=function(e){var r=ts.from(e).zzEncode();return this._push(Xc,r.length(),r)};O.prototype.bool=function(e){return this._push(Qc,1,e?1:0)};function Kc(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}O.prototype.fixed32=function(e){return this._push(Kc,4,e>>>0)};O.prototype.sfixed32=O.prototype.fixed32;O.prototype.fixed64=function(e){var r=ts.from(e);return this._push(Kc,4,r.lo)._push(Kc,4,r.hi)};O.prototype.sfixed64=O.prototype.fixed64;O.prototype.float=function(e){return this._push(De.float.writeFloatLE,4,e)};O.prototype.double=function(e){return this._push(De.float.writeDoubleLE,8,e)};var Jx=De.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]};O.prototype.bytes=function(e){var r=e.length>>>0;if(!r)return this._push(Qc,1,0);if(De.isString(e)){var n=O.alloc(r=iy.length(e));iy.decode(e,n,0),e=n}return this.uint32(r)._push(Jx,r,e)};O.prototype.string=function(e){var r=sy.length(e);return r?this.uint32(r)._push(sy.write,r,e):this._push(Qc,1,0)};O.prototype.fork=function(){return this.states=new Gx(this),this.head=this.tail=new ro(Gc,0,0),this.len=0,this};O.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 ro(Gc,0,0),this.len=0),this};O.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};O.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};O._configure=function(t){Wc=t,O.create=ay(),Wc._configure()}});var Yc=H((c3,ly)=>{"use strict";ly.exports=Ze;var uy=rs();(Ze.prototype=Object.create(uy.prototype)).constructor=Ze;var Ct=lt();function Ze(){uy.call(this)}Ze._configure=function(){Ze.alloc=Ct._Buffer_allocUnsafe,Ze.writeBytesBuffer=Ct.Buffer&&Ct.Buffer.prototype instanceof Uint8Array&&Ct.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++]}};Ze.prototype.bytes=function(e){Ct.isString(e)&&(e=Ct._Buffer_from(e,"base64"));var r=e.length>>>0;return this.uint32(r),r&&this._push(Ze.writeBytesBuffer,r,e),this};function Xx(t,e,r){t.length<40?Ct.utf8.write(t,e,r):e.utf8Write?e.utf8Write(t,r):e.write(t,r)}Ze.prototype.string=function(e){var r=Ct.Buffer.byteLength(e);return this.uint32(r),r&&this._push(Xx,r,e),this};Ze._configure()});var os=H((u3,yy)=>{"use strict";yy.exports=X;var et=lt(),eu,hy=et.LongBits,Yx=et.utf8;function Re(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function X(t){this.buf=t,this.pos=0,this.len=t.length}var fy=typeof Uint8Array<"u"?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new X(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new X(e);throw Error("illegal buffer")},py=function(){return et.Buffer?function(r){return(X.create=function(o){return et.Buffer.isBuffer(o)?new eu(o):fy(o)})(r)}:fy};X.create=py();X.prototype._slice=et.Array.prototype.subarray||et.Array.prototype.slice;X.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,Re(this,10);return e}}();X.prototype.int32=function(){return this.uint32()|0};X.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(e&1)|0};function Zc(){var t=new hy(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 Re(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 Re(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")}X.prototype.bool=function(){return this.uint32()!==0};function ns(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}X.prototype.fixed32=function(){if(this.pos+4>this.len)throw Re(this,4);return ns(this.buf,this.pos+=4)};X.prototype.sfixed32=function(){if(this.pos+4>this.len)throw Re(this,4);return ns(this.buf,this.pos+=4)|0};function dy(){if(this.pos+8>this.len)throw Re(this,8);return new hy(ns(this.buf,this.pos+=4),ns(this.buf,this.pos+=4))}X.prototype.float=function(){if(this.pos+4>this.len)throw Re(this,4);var e=et.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e};X.prototype.double=function(){if(this.pos+8>this.len)throw Re(this,4);var e=et.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e};X.prototype.bytes=function(){var e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw Re(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)};X.prototype.string=function(){var e=this.bytes();return Yx.read(e,0,e.length)};X.prototype.skip=function(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Re(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Re(this);while(this.buf[this.pos++]&128);return this};X.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};X._configure=function(t){eu=t,X.create=py(),eu._configure();var e=et.Long?"toLong":"toNumber";et.merge(X.prototype,{int64:function(){return Zc.call(this)[e](!1)},uint64:function(){return Zc.call(this)[e](!0)},sint64:function(){return Zc.call(this).zzDecode()[e](!1)},fixed64:function(){return dy.call(this)[e](!0)},sfixed64:function(){return dy.call(this)[e](!1)}})}});var tu=H((l3,wy)=>{"use strict";wy.exports=ur;var gy=os();(ur.prototype=Object.create(gy.prototype)).constructor=ur;var my=lt();function ur(t){gy.call(this,t)}ur._configure=function(){my.Buffer&&(ur.prototype._slice=my.Buffer.prototype.slice)};ur.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))};ur._configure()});var xy=H((f3,by)=>{"use strict";by.exports=no;var ru=lt();(no.prototype=Object.create(ru.EventEmitter.prototype)).constructor=no;function no(t,e,r){if(typeof t!="function")throw TypeError("rpcImpl must be a function");ru.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!e,this.responseDelimited=!!r}no.prototype.rpcCall=function t(e,r,n,o,i){if(!o)throw TypeError("request must be specified");var s=this;if(!i)return ru.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}};no.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}});var vy=H(ky=>{"use strict";var Zx=ky;Zx.Service=xy()});var Sy=H((h3,Ey)=>{"use strict";Ey.exports={}});var By=H(_y=>{"use strict";var he=_y;he.build="minimal";he.Writer=rs();he.BufferWriter=Yc();he.Reader=os();he.BufferReader=tu();he.util=lt();he.rpc=vy();he.roots=Sy();he.configure=Ay;function Ay(){he.util._configure(),he.Writer._configure(he.BufferWriter),he.Reader._configure(he.BufferReader)}Ay()});var Ty=H((y3,Cy)=>{"use strict";Cy.exports=By()});var _m=H((yo,As)=>{(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,v=3432918353,E=461845907,T=0;T<w;T=T+4)b=f[T]|f[T+1]<<8|f[T+2]<<16|f[T+3]<<24,b=o(b,v),b=i(b,15),b=o(b,E),g^=b,g=i(g,13),g=o(g,5)+3864292196;switch(b=0,p){case 3:b^=f[T+2]<<16;case 2:b^=f[T+1]<<8;case 1:b^=f[T],b=o(b,v),b=i(b,15),b=o(b,E),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,v=h,E=h,T=0,U=0,A=0,P=0,le=597399067,Mo=2869860233,Oo=951274213,Ro=2716044179,M=0;M<w;M=M+16)T=f[M]|f[M+1]<<8|f[M+2]<<16|f[M+3]<<24,U=f[M+4]|f[M+5]<<8|f[M+6]<<16|f[M+7]<<24,A=f[M+8]|f[M+9]<<8|f[M+10]<<16|f[M+11]<<24,P=f[M+12]|f[M+13]<<8|f[M+14]<<16|f[M+15]<<24,T=o(T,le),T=i(T,15),T=o(T,Mo),g^=T,g=i(g,19),g+=b,g=o(g,5)+1444728091,U=o(U,Mo),U=i(U,16),U=o(U,Oo),b^=U,b=i(b,17),b+=v,b=o(b,5)+197830471,A=o(A,Oo),A=i(A,17),A=o(A,Ro),v^=A,v=i(v,15),v+=E,v=o(v,5)+2530024501,P=o(P,Ro),P=i(P,18),P=o(P,le),E^=P,E=i(E,13),E+=g,E=o(E,5)+850148119;switch(T=0,U=0,A=0,P=0,p){case 15:P^=f[M+14]<<16;case 14:P^=f[M+13]<<8;case 13:P^=f[M+12],P=o(P,Ro),P=i(P,18),P=o(P,le),E^=P;case 12:A^=f[M+11]<<24;case 11:A^=f[M+10]<<16;case 10:A^=f[M+9]<<8;case 9:A^=f[M+8],A=o(A,Oo),A=i(A,17),A=o(A,Ro),v^=A;case 8:U^=f[M+7]<<24;case 7:U^=f[M+6]<<16;case 6:U^=f[M+5]<<8;case 5:U^=f[M+4],U=o(U,Mo),U=i(U,16),U=o(U,Oo),b^=U;case 4:T^=f[M+3]<<24;case 3:T^=f[M+2]<<16;case 2:T^=f[M+1]<<8;case 1:T^=f[M],T=o(T,le),T=i(T,15),T=o(T,Mo),g^=T}return g^=f.length,b^=f.length,v^=f.length,E^=f.length,g+=b,g+=v,g+=E,b+=g,v+=g,E+=g,g=s(g),b=s(b),v=s(v),E=s(E),g+=b,g+=v,g+=E,b+=g,v+=g,E+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(v>>>0).toString(16)).slice(-8)+("00000000"+(E>>>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],v=[0,0],E=[0,0],T=[2277735313,289559509],U=[1291169091,658871167],A=0;A<w;A=A+16)v=[f[A+4]|f[A+5]<<8|f[A+6]<<16|f[A+7]<<24,f[A]|f[A+1]<<8|f[A+2]<<16|f[A+3]<<24],E=[f[A+12]|f[A+13]<<8|f[A+14]<<16|f[A+15]<<24,f[A+8]|f[A+9]<<8|f[A+10]<<16|f[A+11]<<24],v=a(v,T),v=u(v,31),v=a(v,U),g=d(g,v),g=u(g,27),g=c(g,b),g=c(a(g,[0,5]),[0,1390208809]),E=a(E,U),E=u(E,33),E=a(E,T),b=d(b,E),b=u(b,31),b=c(b,g),b=c(a(b,[0,5]),[0,944331445]);switch(v=[0,0],E=[0,0],p){case 15:E=d(E,l([0,f[A+14]],48));case 14:E=d(E,l([0,f[A+13]],40));case 13:E=d(E,l([0,f[A+12]],32));case 12:E=d(E,l([0,f[A+11]],24));case 11:E=d(E,l([0,f[A+10]],16));case 10:E=d(E,l([0,f[A+9]],8));case 9:E=d(E,[0,f[A+8]]),E=a(E,U),E=u(E,33),E=a(E,T),b=d(b,E);case 8:v=d(v,l([0,f[A+7]],56));case 7:v=d(v,l([0,f[A+6]],48));case 6:v=d(v,l([0,f[A+5]],40));case 5:v=d(v,l([0,f[A+4]],32));case 4:v=d(v,l([0,f[A+3]],24));case 3:v=d(v,l([0,f[A+2]],16));case 2:v=d(v,l([0,f[A+1]],8));case 1:v=d(v,[0,f[A]]),v=a(v,T),v=u(v,31),v=a(v,U),g=d(g,v)}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 yo<"u"?(typeof As<"u"&&As.exports&&(yo=As.exports=r),yo.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)})(yo)});var Mu=H(($3,Bm)=>{Bm.exports=_m()});var rt=H((_C,tg)=>{"use strict";function eg(t,e){for(let r in e)Object.defineProperty(t,r,{value:e[r],enumerable:!0,configurable:!0});return t}function $2(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 eg(t,r)}catch{r.message=t.message,r.stack=t.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(t)),eg(new o,r)}}tg.exports=$2});var vg=H((fT,kg)=>{"use strict";kg.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(nv,0),a=~(4294967295<<i+1),u=xg(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(ov),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(iv)}};function nv(t,e){return t+xg(e)}function xg(t){let e=t;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function ov(t,e){return t[0]-e[0]}function iv(t){return t[1]}});var Vg=H((S4,hl)=>{"use strict";var Jv=Object.prototype.hasOwnProperty,ue="~";function Ao(){}Object.create&&(Ao.prototype=Object.create(null),new Ao().__proto__||(ue=!1));function Xv(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function jg(t,e,r,n,o){if(typeof r!="function")throw new TypeError("The listener must be a function");var i=new Xv(r,n||t,o),s=ue?ue+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 Hs(t,e){--t._eventsCount===0?t._events=new Ao:delete t._events[e]}function se(){this._events=new Ao,this._eventsCount=0}se.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(ue?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e};se.prototype.listeners=function(e){var r=ue?ue+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};se.prototype.listenerCount=function(e){var r=ue?ue+e:e,n=this._events[r];return n?n.fn?1:n.length:0};se.prototype.emit=function(e,r,n,o,i,s){var c=ue?ue+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};se.prototype.on=function(e,r,n){return jg(this,e,r,n,!1)};se.prototype.once=function(e,r,n){return jg(this,e,r,n,!0)};se.prototype.removeListener=function(e,r,n,o){var i=ue?ue+e:e;if(!this._events[i])return this;if(!r)return Hs(this,i),this;var s=this._events[i];if(s.fn)s.fn===r&&(!o||s.once)&&(!n||s.context===n)&&Hs(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:Hs(this,i)}return this};se.prototype.removeAllListeners=function(e){var r;return e?(r=ue?ue+e:e,this._events[r]&&Hs(this,r)):(this._events=new Ao,this._eventsCount=0),this};se.prototype.off=se.prototype.removeListener;se.prototype.addListener=se.prototype.on;se.prefixed=ue;se.EventEmitter=se;typeof hl<"u"&&(hl.exports=se)});var yE={};Q(yE,{DataStore:()=>Qn,Database:()=>Pt,Index:()=>Mi,Loader:()=>Yt,MetaStore:()=>Gn,STORAGE_VERSION:()=>Jn,cidListIncludes:()=>gc,encodeCarFile:()=>Vn,encodeCarHeader:()=>tc,fireproof:()=>hE,index:()=>Wr,parseCarFile:()=>rc,toHexString:()=>Xh});var zo="0123456789abcdef",$o=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+=zo.charAt(this.bytes[r]>>>4),e+=zo.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+=zo.charAt(this.bytes[r]>>>4),e+=zo.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}},ta=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??Sw()}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 $o.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,$o.ofInner(e)}},Sw=()=>{if(typeof crypto<"u"&&typeof crypto.getRandomValues<"u")return new ra;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)}},ra=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++]}},Bl,Cl=()=>Aw().toString(),Aw=()=>(Bl||(Bl=new ta)).generate();function Tl(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 _w=Dl,Il=128,Bw=127,Cw=~Bw,Tw=Math.pow(2,31);function Dl(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Tw;)e[r++]=t&255|Il,t/=128;for(;t&Cw;)e[r++]=t&255|Il,t>>>=7;return e[r]=t|0,Dl.bytes=r-n+1,e}var Iw=na,Lw=128,Ll=127;function na(t,n){var r=0,n=n||0,o=0,i=n,s,c=t.length;do{if(i>=c)throw na.bytes=0,new RangeError("Could not decode varint");s=t[i++],r+=o<28?(s&Ll)<<o:(s&Ll)*Math.pow(2,o),o+=7}while(s>=Lw);return na.bytes=i-n,r}var Dw=Math.pow(2,7),Nw=Math.pow(2,14),Uw=Math.pow(2,21),Pw=Math.pow(2,28),Fw=Math.pow(2,35),Mw=Math.pow(2,42),Ow=Math.pow(2,49),Rw=Math.pow(2,56),zw=Math.pow(2,63),$w=function(t){return t<Dw?1:t<Nw?2:t<Uw?3:t<Pw?4:t<Fw?5:t<Mw?6:t<Ow?7:t<Rw?8:t<zw?9:10},Hw={encode:_w,decode:Iw,encodingLength:$w},jw=Hw,gn=jw;var wn=(t,e=0)=>[gn.decode(t,e),gn.decode.bytes],mr=(t,e,r=0)=>(gn.encode(t,e,r),e),gr=t=>gn.encodingLength(t);var kE=new Uint8Array(0);var Nl=(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},ot=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 Ul=t=>new TextEncoder().encode(t),Pl=t=>new TextDecoder().decode(t);var Ft=(t,e)=>{let r=e.byteLength,n=gr(t),o=n+gr(r),i=new Uint8Array(o+r);return mr(t,i,0),mr(r,i,n),i.set(e,o),new wr(t,r,e,i)},br=t=>{let e=ot(t),[r,n]=wn(e),[o,i]=wn(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new wr(r,o,s,e)},Fl=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Nl(t.bytes,r.bytes)}},wr=class{constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};var ua={};Q(ua,{base58btc:()=>He,base58flickr:()=>Qw});function Vw(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 v=(b-g)*l+1>>>0,E=new Uint8Array(v);g!==b;){for(var T=h[g],U=0,A=v-1;(T!==0||U<w)&&A!==-1;A--,U++)T+=256*E[A]>>>0,E[A]=T%c>>>0,T=T/c>>>0;if(T!==0)throw new Error("Non-zero carry");w=U,g++}for(var P=v-w;P!==v&&E[P]===0;)P++;for(var le=a.repeat(p);P<v;++P)le+=t.charAt(E[P]);return le}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,v=new Uint8Array(b);h[p];){var E=r[h.charCodeAt(p)];if(E===255)return;for(var T=0,U=b-1;(E!==0||T<g)&&U!==-1;U--,T++)E+=c*v[U]>>>0,v[U]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");g=T,p++}if(h[p]!==" "){for(var A=b-g;A!==b&&v[A]===0;)A++;for(var P=new Uint8Array(w+(b-A)),le=w;A!==b;)P[le++]=v[A++];return P}}}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 qw=Vw,Ww=qw,Ml=Ww;var ia=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")}},sa=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 Ol(this,e)}},aa=class{constructor(e){this.decoders=e}or(e){return Ol(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`)}},Ol=(t,e)=>new aa({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),ca=class{constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new ia(e,r,n),this.decoder=new sa(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},xr=({name:t,prefix:e,encode:r,decode:n})=>new ca(t,e,r,n),yt=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:o}=Ml(r,e);return xr({prefix:t,name:e,encode:n,decode:i=>ot(o(i))})},Kw=(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},Gw=(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},G=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>xr({prefix:e,name:t,encode(o){return Gw(o,n,r)},decode(o){return Kw(o,n,r,t)}});var He=yt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Qw=yt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var la={};Q(la,{base32:()=>kr,base32hex:()=>Zw,base32hexpad:()=>tb,base32hexpadupper:()=>rb,base32hexupper:()=>eb,base32pad:()=>Xw,base32padupper:()=>Yw,base32upper:()=>Jw,base32z:()=>nb});var kr=G({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Jw=G({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Xw=G({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Yw=G({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Zw=G({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),eb=G({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),tb=G({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rb=G({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),nb=G({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var fa=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return ib(r,da(t),e||He.encoder);default:return sb(r,da(t),e||kr.encoder)}};var Rl=new WeakMap,da=t=>{let e=Rl.get(t);if(e==null){let r=new Map;return Rl.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!==bn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==ab)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=Ft(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&&Fl(e.multihash,n.multihash)}toString(e){return fa(this,e)}toJSON(){return{"/":fa(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||zl(n,o,i.bytes))}else if(r[cb]===!0){let{version:n,multihash:o,code:i}=r,s=br(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!==bn)throw new Error(`Version 0 CID must use dag-pb (code: ${bn}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=zl(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,bn,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=ot(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 wr(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]=wn(e.subarray(r));return r+=m,d},o=n(),i=bn;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]=ob(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 da(i).set(n,e),i}},ob=(t,e)=>{switch(t[0]){case"Q":{let r=e||He;return[He.prefix,r.decode(`${He.prefix}${t}`)]}case He.prefix:{let r=e||He;return[He.prefix,r.decode(t)]}case kr.prefix:{let r=e||kr;return[kr.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)]}}},ib=(t,e,r)=>{let{prefix:n}=r;if(n!==He.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},sb=(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},bn=112,ab=18,zl=(t,e,r)=>{let n=gr(t),o=n+gr(e),i=new Uint8Array(o+r.byteLength);return mr(t,i,0),mr(e,i,n),i.set(r,o),i},cb=Symbol.for("@ipld/js-cid/CID");var $l=(t,e)=>j.parse(t,e);var je,_e=class{constructor(e){nt(this,je,new Map);e&&fe(this,je,new Map(e.map(r=>[r.cid.toString(),r.bytes])))}async get(e){let r=Z(this,je).get(e.toString());if(r)return{cid:e,bytes:r}}async put(e,r){Z(this,je).set(e.toString(),r)}putSync(e,r){Z(this,je).set(e.toString(),r)}async delete(e){Z(this,je).delete(e.toString())}deleteSync(e){Z(this,je).delete(e.toString())}*entries(){for(let[e,r]of Z(this,je))yield{cid:$l(e),bytes:r}}};je=new WeakMap;var xn,Ot=class{constructor(...e){nt(this,xn,void 0);fe(this,xn,e)}async get(e){for(let r of Z(this,xn)){let n=await r.get(e);if(n)return n}}};xn=new WeakMap;var ha=class{constructor(e){k(this,"value");k(this,"next");this.value=e}},Ve,Rt,zt,kn=class{constructor(){nt(this,Ve,void 0);nt(this,Rt,void 0);nt(this,zt,void 0);this.clear()}enqueue(e){let r=new ha(e);Z(this,Ve)?(Z(this,Rt).next=r,fe(this,Rt,r)):(fe(this,Ve,r),fe(this,Rt,r)),ea(this,zt)._++}dequeue(){let e=Z(this,Ve);if(e)return fe(this,Ve,Z(this,Ve).next),ea(this,zt)._--,e.value}clear(){fe(this,Ve,void 0),fe(this,Rt,void 0),fe(this,zt,0)}get size(){return Z(this,zt)}*[Symbol.iterator](){let e=Z(this,Ve);for(;e;)yield e.value,e=e.next}};Ve=new WeakMap,Rt=new WeakMap,zt=new WeakMap;function vn(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 kn,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 q={};Q(q,{code:()=>Da,decode:()=>Ir,encode:()=>ri,name:()=>k0});var ub=["string","number","bigint","symbol"],lb=["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 Hl(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(ub.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(fb(t))return"Buffer";let r=db(t);return r||"Object"}function fb(t){return t&&t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer.call(null,t)}function db(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(lb.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 S=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 vr=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",hb=new TextDecoder,pb=new TextEncoder;function jo(t){return vr&&globalThis.Buffer.isBuffer(t)}function En(t){return t instanceof Uint8Array?jo(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var Wl=vr?(t,e,r)=>r-e>64?globalThis.Buffer.from(t.subarray(e,r)).toString("utf8"):Vl(t,e,r):(t,e,r)=>r-e>64?hb.decode(t.subarray(e,r)):Vl(t,e,r),Vo=vr?t=>t.length>64?globalThis.Buffer.from(t):jl(t):t=>t.length>64?pb.encode(t):jl(t),qe=t=>Uint8Array.from(t),Er=vr?(t,e,r)=>jo(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),Kl=vr?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),En(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},Gl=vr?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function Ql(t,e){if(jo(t)&&jo(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 jl(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 Vl(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 pa(n)}var ql=4096;function pa(t){let e=t.length;if(e<=ql)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=ql));return r}var yb=256,Sn=class{constructor(e=yb){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=Gl(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=Er(n,0,this.cursor)}else r=Kl(this.chunks,this.cursor);return e&&this.reset(),r}};var I="CBOR decode error:",it="CBOR encode error:",An=[];An[23]=1;An[24]=2;An[25]=3;An[26]=5;An[27]=9;function st(t,e,r){if(t.length-e<r)throw new Error(`${I} not enough data for type`)}var ee=[24,256,65536,4294967296,BigInt("18446744073709551616")];function ye(t,e,r){st(t,e,1);let n=t[e];if(r.strict===!0&&n<ee[0])throw new Error(`${I} integer encoded in more bytes than necessary (strict decode)`);return n}function me(t,e,r){st(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<ee[1])throw new Error(`${I} integer encoded in more bytes than necessary (strict decode)`);return n}function ge(t,e,r){st(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<ee[2])throw new Error(`${I} integer encoded in more bytes than necessary (strict decode)`);return n}function we(t,e,r){st(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<ee[3])throw new Error(`${I} 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(`${I} integers outside of the safe integer range are not supported`)}function Jl(t,e,r,n){return new S(y.uint,ye(t,e+1,n),2)}function Xl(t,e,r,n){return new S(y.uint,me(t,e+1,n),3)}function Yl(t,e,r,n){return new S(y.uint,ge(t,e+1,n),5)}function Zl(t,e,r,n){return new S(y.uint,we(t,e+1,n),9)}function Be(t,e){return ne(t,0,e.value)}function ne(t,e,r){if(r<ee[0]){let n=Number(r);t.push([e|n])}else if(r<ee[1]){let n=Number(r);t.push([e|24,n])}else if(r<ee[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<ee[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<ee[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(`${I} encountered BigInt larger than allowable range`)}}Be.encodedSize=function(e){return ne.encodedSize(e.value)};ne.encodedSize=function(e){return e<ee[0]?1:e<ee[1]?2:e<ee[2]?3:e<ee[3]?5:9};Be.compareTokens=function(e,r){return e.value<r.value?-1:e.value>r.value?1:0};function ef(t,e,r,n){return new S(y.negint,-1-ye(t,e+1,n),2)}function tf(t,e,r,n){return new S(y.negint,-1-me(t,e+1,n),3)}function rf(t,e,r,n){return new S(y.negint,-1-ge(t,e+1,n),5)}var ya=BigInt(-1),nf=BigInt(1);function of(t,e,r,n){let o=we(t,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new S(y.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${I} integers outside of the safe integer range are not supported`);return new S(y.negint,ya-BigInt(o),9)}function qo(t,e){let r=e.value,n=typeof r=="bigint"?r*ya-nf:r*-1-1;ne(t,e.type.majorEncoded,n)}qo.encodedSize=function(e){let r=e.value,n=typeof r=="bigint"?r*ya-nf:r*-1-1;return n<ee[0]?1:n<ee[1]?2:n<ee[2]?3:n<ee[3]?5:9};qo.compareTokens=function(e,r){return e.value<r.value?1:e.value>r.value?-1:0};function _n(t,e,r,n){st(t,e,r+n);let o=Er(t,e+r,e+r+n);return new S(y.bytes,o,r+n)}function sf(t,e,r,n){return _n(t,e,1,r)}function af(t,e,r,n){return _n(t,e,2,ye(t,e+1,n))}function cf(t,e,r,n){return _n(t,e,3,me(t,e+1,n))}function uf(t,e,r,n){return _n(t,e,5,ge(t,e+1,n))}function lf(t,e,r,n){let o=we(t,e+1,n);if(typeof o=="bigint")throw new Error(`${I} 64-bit integer bytes lengths not supported`);return _n(t,e,9,o)}function Wo(t){return t.encodedBytes===void 0&&(t.encodedBytes=t.type===y.string?Vo(t.value):t.value),t.encodedBytes}function Sr(t,e){let r=Wo(e);ne(t,e.type.majorEncoded,r.length),t.push(r)}Sr.encodedSize=function(e){let r=Wo(e);return ne.encodedSize(r.length)+r.length};Sr.compareTokens=function(e,r){return gb(Wo(e),Wo(r))};function gb(t,e){return t.length<e.length?-1:t.length>e.length?1:Ql(t,e)}function Bn(t,e,r,n,o){let i=r+n;st(t,e,i);let s=new S(y.string,Wl(t,e+r,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Er(t,e+r,e+i)),s}function ff(t,e,r,n){return Bn(t,e,1,r,n)}function df(t,e,r,n){return Bn(t,e,2,ye(t,e+1,n),n)}function hf(t,e,r,n){return Bn(t,e,3,me(t,e+1,n),n)}function pf(t,e,r,n){return Bn(t,e,5,ge(t,e+1,n),n)}function yf(t,e,r,n){let o=we(t,e+1,n);if(typeof o=="bigint")throw new Error(`${I} 64-bit integer string lengths not supported`);return Bn(t,e,9,o,n)}var mf=Sr;function Ar(t,e,r,n){return new S(y.array,n,r)}function gf(t,e,r,n){return Ar(t,e,1,r)}function wf(t,e,r,n){return Ar(t,e,2,ye(t,e+1,n))}function bf(t,e,r,n){return Ar(t,e,3,me(t,e+1,n))}function xf(t,e,r,n){return Ar(t,e,5,ge(t,e+1,n))}function kf(t,e,r,n){let o=we(t,e+1,n);if(typeof o=="bigint")throw new Error(`${I} 64-bit integer array lengths not supported`);return Ar(t,e,9,o)}function vf(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${I} indefinite length items not allowed`);return Ar(t,e,1,1/0)}function Ko(t,e){ne(t,y.array.majorEncoded,e.value)}Ko.compareTokens=Be.compareTokens;Ko.encodedSize=function(e){return ne.encodedSize(e.value)};function _r(t,e,r,n){return new S(y.map,n,r)}function Ef(t,e,r,n){return _r(t,e,1,r)}function Sf(t,e,r,n){return _r(t,e,2,ye(t,e+1,n))}function Af(t,e,r,n){return _r(t,e,3,me(t,e+1,n))}function _f(t,e,r,n){return _r(t,e,5,ge(t,e+1,n))}function Bf(t,e,r,n){let o=we(t,e+1,n);if(typeof o=="bigint")throw new Error(`${I} 64-bit integer map lengths not supported`);return _r(t,e,9,o)}function Cf(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${I} indefinite length items not allowed`);return _r(t,e,1,1/0)}function Go(t,e){ne(t,y.map.majorEncoded,e.value)}Go.compareTokens=Be.compareTokens;Go.encodedSize=function(e){return ne.encodedSize(e.value)};function Tf(t,e,r,n){return new S(y.tag,r,1)}function If(t,e,r,n){return new S(y.tag,ye(t,e+1,n),2)}function Lf(t,e,r,n){return new S(y.tag,me(t,e+1,n),3)}function Df(t,e,r,n){return new S(y.tag,ge(t,e+1,n),5)}function Nf(t,e,r,n){return new S(y.tag,we(t,e+1,n),9)}function Qo(t,e){ne(t,y.tag.majorEncoded,e.value)}Qo.compareTokens=Be.compareTokens;Qo.encodedSize=function(e){return ne.encodedSize(e.value)};var Eb=20,Sb=21,Ab=22,_b=23;function Uf(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${I} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new S(y.null,null,1):new S(y.undefined,void 0,1)}function Pf(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${I} indefinite length items not allowed`);return new S(y.break,void 0,1)}function ma(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${I} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${I} Infinity values are not supported`)}return new S(y.float,t,e)}function Ff(t,e,r,n){return ma(ga(t,e+1),3,n)}function Mf(t,e,r,n){return ma(wa(t,e+1),5,n)}function Of(t,e,r,n){return ma(Hf(t,e+1),9,n)}function Jo(t,e,r){let n=e.value;if(n===!1)t.push([y.float.majorEncoded|Eb]);else if(n===!0)t.push([y.float.majorEncoded|Sb]);else if(n===null)t.push([y.float.majorEncoded|Ab]);else if(n===void 0)t.push([y.float.majorEncoded|_b]);else{let o,i=!1;(!r||r.float64!==!0)&&(zf(n),o=ga(Ne,1),n===o||Number.isNaN(n)?(Ne[0]=249,t.push(Ne.slice(0,3)),i=!0):($f(n),o=wa(Ne,1),n===o&&(Ne[0]=250,t.push(Ne.slice(0,5)),i=!0))),i||(Bb(n),o=Hf(Ne,1),Ne[0]=251,t.push(Ne.slice(0,9)))}}Jo.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){zf(n);let o=ga(Ne,1);if(n===o||Number.isNaN(n))return 3;if($f(n),o=wa(Ne,1),n===o)return 5}return 9};var Rf=new ArrayBuffer(9),Ce=new DataView(Rf,1),Ne=new Uint8Array(Rf,0);function zf(t){if(t===1/0)Ce.setUint16(0,31744,!1);else if(t===-1/0)Ce.setUint16(0,64512,!1);else if(Number.isNaN(t))Ce.setUint16(0,32256,!1);else{Ce.setFloat32(0,t);let e=Ce.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)Ce.setUint16(0,31744,!1);else if(r===0)Ce.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let o=r-127;o<-24?Ce.setUint16(0,0):o<-14?Ce.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Ce.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function ga(t,e){if(t.length-e<2)throw new Error(`${I} 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 $f(t){Ce.setFloat32(0,t,!1)}function wa(t,e){if(t.length-e<4)throw new Error(`${I} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function Bb(t){Ce.setFloat64(0,t,!1)}function Hf(t,e){if(t.length-e<8)throw new Error(`${I} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}Jo.compareTokens=Be.compareTokens;function R(t,e,r){throw new Error(`${I} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function Xo(t){return()=>{throw new Error(`${I} ${t}`)}}var _=[];for(let t=0;t<=23;t++)_[t]=R;_[24]=Jl;_[25]=Xl;_[26]=Yl;_[27]=Zl;_[28]=R;_[29]=R;_[30]=R;_[31]=R;for(let t=32;t<=55;t++)_[t]=R;_[56]=ef;_[57]=tf;_[58]=rf;_[59]=of;_[60]=R;_[61]=R;_[62]=R;_[63]=R;for(let t=64;t<=87;t++)_[t]=sf;_[88]=af;_[89]=cf;_[90]=uf;_[91]=lf;_[92]=R;_[93]=R;_[94]=R;_[95]=Xo("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)_[t]=ff;_[120]=df;_[121]=hf;_[122]=pf;_[123]=yf;_[124]=R;_[125]=R;_[126]=R;_[127]=Xo("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)_[t]=gf;_[152]=wf;_[153]=bf;_[154]=xf;_[155]=kf;_[156]=R;_[157]=R;_[158]=R;_[159]=vf;for(let t=160;t<=183;t++)_[t]=Ef;_[184]=Sf;_[185]=Af;_[186]=_f;_[187]=Bf;_[188]=R;_[189]=R;_[190]=R;_[191]=Cf;for(let t=192;t<=215;t++)_[t]=Tf;_[216]=If;_[217]=Lf;_[218]=Df;_[219]=Nf;_[220]=R;_[221]=R;_[222]=R;_[223]=R;for(let t=224;t<=243;t++)_[t]=Xo("simple values are not supported");_[244]=R;_[245]=R;_[246]=R;_[247]=Uf;_[248]=Xo("simple values are not supported");_[249]=Ff;_[250]=Mf;_[251]=Of;_[252]=R;_[253]=R;_[254]=R;_[255]=Pf;var Ue=[];for(let t=0;t<24;t++)Ue[t]=new S(y.uint,t,1);for(let t=-1;t>=-24;t--)Ue[31-t]=new S(y.negint,t,1);Ue[64]=new S(y.bytes,new Uint8Array(0),1);Ue[96]=new S(y.string,"",1);Ue[128]=new S(y.array,0,1);Ue[160]=new S(y.map,0,1);Ue[244]=new S(y.false,!1,1);Ue[245]=new S(y.true,!0,1);Ue[246]=new S(y.null,null,1);function jf(t){switch(t.type){case y.false:return qe([244]);case y.true:return qe([245]);case y.null:return qe([246]);case y.bytes:return t.value.length?void 0:qe([64]);case y.string:return t.value===""?qe([96]):void 0;case y.array:return t.value===0?qe([128]):void 0;case y.map:return t.value===0?qe([160]):void 0;case y.uint:return t.value<24?qe([Number(t.value)]):void 0;case y.negint:if(t.value>=-24)return qe([31-Number(t.value)])}}var Tb={float64:!1,mapSorter:Db,quickEncodeToken:jf};function Ib(){let t=[];return t[y.uint.major]=Be,t[y.negint.major]=qo,t[y.bytes.major]=Sr,t[y.string.major]=mf,t[y.array.major]=Ko,t[y.map.major]=Go,t[y.tag.major]=Qo,t[y.float.major]=Jo,t}var Vf=Ib(),ba=new Sn,Zo=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(`${it} object contains circular references`);return new t(r,e)}},mt={null:new S(y.null,null),undefined:new S(y.undefined,void 0),true:new S(y.true,!0),false:new S(y.false,!1),emptyArray:new S(y.array,0),emptyMap:new S(y.map,0)},gt={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new S(y.float,t):t>=0?new S(y.uint,t):new S(y.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new S(y.uint,t):new S(y.negint,t)},Uint8Array(t,e,r,n){return new S(y.bytes,t)},string(t,e,r,n){return new S(y.string,t)},boolean(t,e,r,n){return t?mt.true:mt.false},null(t,e,r,n){return mt.null},undefined(t,e,r,n){return mt.undefined},ArrayBuffer(t,e,r,n){return new S(y.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new S(y.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[mt.emptyArray,new S(y.break)]:mt.emptyArray;n=Zo.createCheck(n,t);let o=[],i=0;for(let s of t)o[i++]=Yo(s,r,n);return r.addBreakTokens?[new S(y.array,t.length),o,new S(y.break)]:[new S(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?[mt.emptyMap,new S(y.break)]:mt.emptyMap;n=Zo.createCheck(n,t);let c=[],a=0;for(let u of i)c[a++]=[Yo(u,r,n),Yo(o?t.get(u):t[u],r,n)];return Lb(c,r),r.addBreakTokens?[new S(y.map,s),c,new S(y.break)]:[new S(y.map,s),c]}};gt.Map=gt.Object;gt.Buffer=gt.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))gt[`${t}Array`]=gt.DataView;function Yo(t,e={},r){let n=Hl(t),o=e&&e.typeEncoders&&e.typeEncoders[n]||gt[n];if(typeof o=="function"){let s=o(t,n,e,r);if(s!=null)return s}let i=gt[n];if(!i)throw new Error(`${it} unsupported type: ${n}`);return i(t,n,e,r)}function Lb(t,e){e.mapSorter&&t.sort(e.mapSorter)}function Db(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=Vf[o].compareTokens(r,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function qf(t,e,r,n){if(Array.isArray(e))for(let o of e)qf(t,o,r,n);else r[e.type.major](t,e,n)}function xa(t,e,r){let n=Yo(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 Sn(s);if(i(c,n,r),c.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return En(c.chunks[0])}}return ba.reset(),qf(ba,n,e,r),ba.toBytes(!0)}function ka(t,e){return e=Object.assign({},Tb,e),xa(t,Vf,e)}var Nb={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},va=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=Ue[e];if(r===void 0){let n=_[e];if(!n)throw new Error(`${I} 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}},Cn=Symbol.for("DONE"),ei=Symbol.for("BREAK");function Ub(t,e,r){let n=[];for(let o=0;o<t.value;o++){let i=Tn(e,r);if(i===ei){if(t.value===1/0)break;throw new Error(`${I} got unexpected break to lengthed array`)}if(i===Cn)throw new Error(`${I} found array but not enough entries (got ${o}, expected ${t.value})`);n[o]=i}return n}function Pb(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=Tn(e,r);if(c===ei){if(t.value===1/0)break;throw new Error(`${I} got unexpected break to lengthed map`)}if(c===Cn)throw new Error(`${I} found map but not enough entries (got ${s} [no key], expected ${t.value})`);if(n!==!0&&typeof c!="string")throw new Error(`${I} non-string keys not supported (got ${typeof c})`);if(r.rejectDuplicateMapKeys===!0&&(n&&i.has(c)||!n&&c in o))throw new Error(`${I} found repeat map key "${c}"`);let a=Tn(e,r);if(a===Cn)throw new Error(`${I} 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 Tn(t,e){if(t.done())return Cn;let r=t.next();if(r.type===y.break)return ei;if(r.type.terminal)return r.value;if(r.type===y.array)return Ub(r,t,e);if(r.type===y.map)return Pb(r,t,e);if(r.type===y.tag){if(e.tags&&typeof e.tags[r.value]=="function"){let n=Tn(t,e);return e.tags[r.value](n)}throw new Error(`${I} tag not supported (${r.value})`)}throw new Error("unsupported")}function In(t,e){if(!(t instanceof Uint8Array))throw new Error(`${I} data to decode must be a Uint8Array`);e=Object.assign({},Nb,e);let r=e.tokenizer||new va(t,e),n=Tn(r,e);if(n===Cn)throw new Error(`${I} did not find any content to decode`);if(n===ei)throw new Error(`${I} got unexpected break`);if(!r.done())throw new Error(`${I} too many terminals, data makes no sense`);return n}var Mb=Gf,Wf=128,Ob=127,Rb=~Ob,zb=Math.pow(2,31);function Gf(t,e,r){e=e||[],r=r||0;for(var n=r;t>=zb;)e[r++]=t&255|Wf,t/=128;for(;t&Rb;)e[r++]=t&255|Wf,t>>>=7;return e[r]=t|0,Gf.bytes=r-n+1,e}var $b=Ea,Hb=128,Kf=127;function Ea(t,n){var r=0,n=n||0,o=0,i=n,s,c=t.length;do{if(i>=c)throw Ea.bytes=0,new RangeError("Could not decode varint");s=t[i++],r+=o<28?(s&Kf)<<o:(s&Kf)*Math.pow(2,o),o+=7}while(s>=Hb);return Ea.bytes=i-n,r}var jb=Math.pow(2,7),Vb=Math.pow(2,14),qb=Math.pow(2,21),Wb=Math.pow(2,28),Kb=Math.pow(2,35),Gb=Math.pow(2,42),Qb=Math.pow(2,49),Jb=Math.pow(2,56),Xb=Math.pow(2,63),Yb=function(t){return t<jb?1:t<Vb?2:t<qb?3:t<Wb?4:t<Kb?5:t<Gb?6:t<Qb?7:t<Jb?8:t<Xb?9:10},Zb={encode:Mb,decode:$b,encodingLength:Yb},e0=Zb,Ln=e0;var Dn=(t,e=0)=>[Ln.decode(t,e),Ln.decode.bytes],Br=(t,e,r=0)=>(Ln.encode(t,e,r),e),Cr=t=>Ln.encodingLength(t);var Ht={};Q(Ht,{coerce:()=>Te,empty:()=>Qf,equals:()=>Aa,fromHex:()=>r0,fromString:()=>o0,isBinary:()=>n0,toHex:()=>t0,toString:()=>i0});var Qf=new Uint8Array(0),t0=t=>t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),""),r0=t=>{let e=t.match(/../g);return e?new Uint8Array(e.map(r=>parseInt(r,16))):Qf},Aa=(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},Te=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")},n0=t=>t instanceof ArrayBuffer||ArrayBuffer.isView(t),o0=t=>new TextEncoder().encode(t),i0=t=>new TextDecoder().decode(t);var jt=(t,e)=>{let r=e.byteLength,n=Cr(t),o=n+Cr(r),i=new Uint8Array(o+r);return Br(t,i,0),Br(r,i,n),i.set(e,o),new Tr(t,r,e,i)},ti=t=>{let e=Te(t),[r,n]=Dn(e),[o,i]=Dn(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Tr(r,o,s,e)},Jf=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Aa(t.bytes,r.bytes)}},Tr=class{constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};function s0(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 v=(b-g)*l+1>>>0,E=new Uint8Array(v);g!==b;){for(var T=h[g],U=0,A=v-1;(T!==0||U<w)&&A!==-1;A--,U++)T+=256*E[A]>>>0,E[A]=T%c>>>0,T=T/c>>>0;if(T!==0)throw new Error("Non-zero carry");w=U,g++}for(var P=v-w;P!==v&&E[P]===0;)P++;for(var le=a.repeat(p);P<v;++P)le+=t.charAt(E[P]);return le}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,v=new Uint8Array(b);h[p];){var E=r[h.charCodeAt(p)];if(E===255)return;for(var T=0,U=b-1;(E!==0||T<g)&&U!==-1;U--,T++)E+=c*v[U]>>>0,v[U]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");g=T,p++}if(h[p]!==" "){for(var A=b-g;A!==b&&v[A]===0;)A++;for(var P=new Uint8Array(w+(b-A)),le=w;A!==b;)P[le++]=v[A++];return P}}}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 a0=s0,c0=a0,Xf=c0;var _a=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")}},Ba=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 Yf(this,e)}},Ca=class{constructor(e){this.decoders=e}or(e){return Yf(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`)}},Yf=(t,e)=>new Ca({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Ta=class{constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new _a(e,r,n),this.decoder=new Ba(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Zf=({name:t,prefix:e,encode:r,decode:n})=>new Ta(t,e,r,n),Ia=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:o}=Xf(r,e);return Zf({prefix:t,name:e,encode:n,decode:i=>Te(o(i))})},u0=(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},l0=(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},ae=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Zf({prefix:e,name:t,encode(o){return l0(o,n,r)},decode(o){return u0(o,n,r,t)}});var at=Ia({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),XS=Ia({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Un=ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),eA=ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),tA=ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rA=ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),nA=ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),oA=ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),iA=ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),sA=ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),aA=ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ed=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return d0(r,La(t),e||at.encoder);default:return h0(r,La(t),e||Un.encoder)}};var td=new WeakMap,La=t=>{let e=td.get(t);if(e==null){let r=new Map;return td.set(t,r),r}return e},V=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!==Pn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==p0)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=jt(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&&Jf(e.multihash,n.multihash)}toString(e){return ed(this,e)}toJSON(){return{"/":ed(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||rd(n,o,i.bytes))}else if(r[y0]===!0){let{version:n,multihash:o,code:i}=r,s=ti(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!==Pn)throw new Error(`Version 0 CID must use dag-pb (code: ${Pn}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=rd(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,Pn,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=Te(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 Tr(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]=Dn(e.subarray(r));return r+=m,d},o=n(),i=Pn;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]=f0(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 La(i).set(n,e),i}},f0=(t,e)=>{switch(t[0]){case"Q":{let r=e||at;return[at.prefix,r.decode(`${at.prefix}${t}`)]}case at.prefix:{let r=e||at;return[at.prefix,r.decode(t)]}case Un.prefix:{let r=e||Un;return[Un.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)]}}},d0=(t,e,r)=>{let{prefix:n}=r;if(n!==at.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},h0=(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},Pn=112,p0=18,rd=(t,e,r)=>{let n=Cr(t),o=n+Cr(e),i=new Uint8Array(o+r.byteLength);return Br(t,i,0),Br(e,i,n),i.set(r,o),i},y0=Symbol.for("@ipld/js-cid/CID");var nd=42;function m0(t){if(t.asCID!==t&&t["/"]!==t.bytes)return null;let e=V.asCID(t);if(!e)return null;let r=new Uint8Array(e.bytes.byteLength+1);return r.set(e.bytes,1),[new S(y.tag,nd),new S(y.bytes,r)]}function g0(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function w0(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 b0={float64:!0,typeEncoders:{Object:m0,undefined:g0,number:w0}};function x0(t){if(t[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return V.decode(t.subarray(1))}var od={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};od.tags[nd]=x0;var k0="dag-cbor",Da=113,ri=t=>ka(t,b0),Ir=t=>In(t,od);var wt={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=>!wt.Null(t)&&typeof t=="object"&&t.asCID===t,List:t=>Array.isArray(t),Map:t=>!wt.Null(t)&&typeof t=="object"&&t.asCID!==t&&!wt.List(t)&&!wt.Bytes(t)},Lr={Int:wt.Int,"CarHeader > version":t=>Lr.Int(t),"CarHeader > roots (anon) > valueType (anon)":wt.Link,"CarHeader > roots (anon)":t=>wt.List(t)&&Array.prototype.every.call(t,Lr["CarHeader > roots (anon) > valueType (anon)"]),"CarHeader > roots":t=>Lr["CarHeader > roots (anon)"](t),CarHeader:t=>{let e=t&&Object.keys(t);return wt.Map(t)&&["version"].every(r=>e.includes(r))&&Object.entries(t).every(([r,n])=>Lr["CarHeader > "+r]&&Lr["CarHeader > "+r](n))}},Na=Lr.CarHeader;var bt=W(ni(),1),Fn={SHA2_256:18,LENGTH:32,DAG_PB:112},Fa=16+8+8+8;function Dr(t,e){if(!t.length)throw new Error("Unexpected end of data");let r=bt.default.decode(t);return e.seek(bt.default.decode.bytes),r}function Ma(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 Oa(t){bt.default.decode(t);let e=bt.default.decode.bytes,r=bt.default.decode(t.subarray(bt.default.decode.bytes)),n=bt.default.decode.bytes;return e+n+r}async function Ra(t,e){let r=Dr(await t.upTo(8),t);if(r===0)throw new Error("Invalid CAR header (zero length)");let n=await t.exactly(r,!0),o=Ir(n);if(!Na(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=Ma(await t.exactly(Fa,!0));t.seek(s.dataOffset-t.pos);let c=await Ra(t,1);return Object.assign(c,s)}async function P0(t){let e=await t.exactly(2,!1);if(e[0]===Fn.SHA2_256&&e[1]===Fn.LENGTH){let s=await t.exactly(34,!0),c=br(s);return j.create(0,Fn.DAG_PB,c)}let r=Dr(await t.upTo(8),t);if(r!==1)throw new Error(`Unexpected CID version (${r})`);let n=Dr(await t.upTo(8),t),o=await t.exactly(Oa(await t.upTo(8)),!0),i=br(o);return j.create(r,n,i)}async function pd(t){let e=t.pos,r=Dr(await t.upTo(8),t);if(r===0)throw new Error("Invalid CAR section (zero length)");r+=t.pos-e;let n=await P0(t),o=r-Number(t.pos-e);return{cid:n,length:r,blockLength:o}}async function F0(t){let{cid:e,blockLength:r}=await pd(t);return{bytes:await t.exactly(r,!0),cid:e}}async function M0(t){let e=t.pos,{cid:r,length:n,blockLength:o}=await pd(t),i={cid:r,length:n,blockLength:o,offset:e,blockOffset:t.pos};return t.seek(i.blockLength),i}function Nr(t){let e=(async()=>{let r=await Ra(t);if(r.version===2){let n=t.pos-r.dataOffset;t=R0(t,r.dataSize-n)}return r})();return{header:()=>e,async*blocks(){for(await e;(await t.upTo(8)).length>0;)yield await F0(t)},async*blocksIndex(){for(await e;(await t.upTo(8)).length>0;)yield await M0(t)}}}function Vt(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 O0(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 Ur(t){let e=t[Symbol.asyncIterator]();async function r(){let n=await e.next();return n.done?null:n.value}return O0(r)}function R0(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 qt=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 yd(Vt(e))}static async fromIterable(e){if(!e||typeof e[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return yd(Ur(e))}};async function yd(t){let e=Nr(t),r=await e.header(),n=[];for await(let o of e.blocks())n.push(o);return new qt(r,n)}var Mn=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 md(Vt(e))}static async fromIterable(e){if(!e||typeof e[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return md(Ur(e))}};async function md(t){let e=Nr(t),{version:r,roots:n}=await e.header();return new Mn(r,n,e.blocksIndex())}var oi=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}},za=class t extends oi{[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 gd(e);return new t(r,n,o)}static async fromIterable(e){let{version:r,roots:n,iterator:o}=await wd(e);return new t(r,n,o)}},$a=class t extends oi{[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 gd(e);return new t(r,n,o)}static async fromIterable(e){let{version:r,roots:n,iterator:o}=await wd(e);return new t(r,n,o)}};async function gd(t){if(!(t instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return bd(Vt(t))}async function wd(t){if(!t||typeof t[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return bd(Ur(t))}async function bd(t){let e=Nr(t),{version:r,roots:n}=await e.header();return{version:r,roots:n,iterator:e.blocks()}}var $0=W(ni(),1);var xd=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 $n=W(ni(),1);var H0=["string","number","bigint","symbol"],j0=["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 kd(t){if(t===null)return"null";if(t===void 0)return"undefined";if(t===!0||t===!1)return"boolean";let e=typeof t;if(H0.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(t))return"Array";if(V0(t))return"Buffer";let r=q0(t);return r||"Object"}function V0(t){return t&&t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer.call(null,t)}function q0(t){let e=Object.prototype.toString.call(t).slice(8,-1);if(j0.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 C=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 Pr=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",W0=new TextDecoder,K0=new TextEncoder;function ii(t){return Pr&&globalThis.Buffer.isBuffer(t)}function Ad(t){return t instanceof Uint8Array?ii(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t:Uint8Array.from(t)}var _d=Pr?(t,e,r)=>r-e>64?globalThis.Buffer.from(t.subarray(e,r)).toString("utf8"):Ed(t,e,r):(t,e,r)=>r-e>64?W0.decode(t.subarray(e,r)):Ed(t,e,r),Bd=Pr?t=>t.length>64?globalThis.Buffer.from(t):vd(t):t=>t.length>64?K0.encode(t):vd(t),We=t=>Uint8Array.from(t),Fr=Pr?(t,e,r)=>ii(t)?new Uint8Array(t.subarray(e,r)):t.slice(e,r):(t,e,r)=>t.slice(e,r),Cd=Pr?(t,e)=>(t=t.map(r=>r instanceof Uint8Array?r:globalThis.Buffer.from(r)),Ad(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},Td=Pr?t=>globalThis.Buffer.allocUnsafe(t):t=>new Uint8Array(t);function Id(t,e){if(ii(t)&&ii(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 vd(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 Ed(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 G0(n)}var Sd=4096;function G0(t){let e=t.length;if(e<=Sd)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Sd));return r}var Q0=256,si=class{constructor(e=Q0){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=Td(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=Fr(n,0,this.cursor)}else r=Cd(this.chunks,this.cursor);return e&&this.reset(),r}};var z="CBOR decode error:",Ha="CBOR encode error:",On=[];On[23]=1;On[24]=2;On[25]=3;On[26]=5;On[27]=9;function ct(t,e,r){if(t.length-e<r)throw new Error(`${z} not enough data for type`)}var te=[24,256,65536,4294967296,BigInt("18446744073709551616")];function be(t,e,r){ct(t,e,1);let n=t[e];if(r.strict===!0&&n<te[0])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);return n}function xe(t,e,r){ct(t,e,2);let n=t[e]<<8|t[e+1];if(r.strict===!0&&n<te[1])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);return n}function ke(t,e,r){ct(t,e,4);let n=t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];if(r.strict===!0&&n<te[2])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);return n}function ve(t,e,r){ct(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<te[3])throw new Error(`${z} 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(`${z} integers outside of the safe integer range are not supported`)}function Ld(t,e,r,n){return new C(x.uint,be(t,e+1,n),2)}function Dd(t,e,r,n){return new C(x.uint,xe(t,e+1,n),3)}function Nd(t,e,r,n){return new C(x.uint,ke(t,e+1,n),5)}function Ud(t,e,r,n){return new C(x.uint,ve(t,e+1,n),9)}function Ie(t,e){return oe(t,0,e.value)}function oe(t,e,r){if(r<te[0]){let n=Number(r);t.push([e|n])}else if(r<te[1]){let n=Number(r);t.push([e|24,n])}else if(r<te[2]){let n=Number(r);t.push([e|25,n>>>8,n&255])}else if(r<te[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<te[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(`${z} encountered BigInt larger than allowable range`)}}Ie.encodedSize=function(e){return oe.encodedSize(e.value)};oe.encodedSize=function(e){return e<te[0]?1:e<te[1]?2:e<te[2]?3:e<te[3]?5:9};Ie.compareTokens=function(e,r){return e.value<r.value?-1:e.value>r.value?1:0};function Pd(t,e,r,n){return new C(x.negint,-1-be(t,e+1,n),2)}function Fd(t,e,r,n){return new C(x.negint,-1-xe(t,e+1,n),3)}function Md(t,e,r,n){return new C(x.negint,-1-ke(t,e+1,n),5)}var ja=BigInt(-1),Od=BigInt(1);function Rd(t,e,r,n){let o=ve(t,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new C(x.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${z} integers outside of the safe integer range are not supported`);return new C(x.negint,ja-BigInt(o),9)}function ai(t,e){let r=e.value,n=typeof r=="bigint"?r*ja-Od:r*-1-1;oe(t,e.type.majorEncoded,n)}ai.encodedSize=function(e){let r=e.value,n=typeof r=="bigint"?r*ja-Od:r*-1-1;return n<te[0]?1:n<te[1]?2:n<te[2]?3:n<te[3]?5:9};ai.compareTokens=function(e,r){return e.value<r.value?1:e.value>r.value?-1:0};function Rn(t,e,r,n){ct(t,e,r+n);let o=Fr(t,e+r,e+r+n);return new C(x.bytes,o,r+n)}function zd(t,e,r,n){return Rn(t,e,1,r)}function $d(t,e,r,n){return Rn(t,e,2,be(t,e+1,n))}function Hd(t,e,r,n){return Rn(t,e,3,xe(t,e+1,n))}function jd(t,e,r,n){return Rn(t,e,5,ke(t,e+1,n))}function Vd(t,e,r,n){let o=ve(t,e+1,n);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer bytes lengths not supported`);return Rn(t,e,9,o)}function ci(t){return t.encodedBytes===void 0&&(t.encodedBytes=t.type===x.string?Bd(t.value):t.value),t.encodedBytes}function Mr(t,e){let r=ci(e);oe(t,e.type.majorEncoded,r.length),t.push(r)}Mr.encodedSize=function(e){let r=ci(e);return oe.encodedSize(r.length)+r.length};Mr.compareTokens=function(e,r){return X0(ci(e),ci(r))};function X0(t,e){return t.length<e.length?-1:t.length>e.length?1:Id(t,e)}function zn(t,e,r,n,o){let i=r+n;ct(t,e,i);let s=new C(x.string,_d(t,e+r,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Fr(t,e+r,e+i)),s}function qd(t,e,r,n){return zn(t,e,1,r,n)}function Wd(t,e,r,n){return zn(t,e,2,be(t,e+1,n),n)}function Kd(t,e,r,n){return zn(t,e,3,xe(t,e+1,n),n)}function Gd(t,e,r,n){return zn(t,e,5,ke(t,e+1,n),n)}function Qd(t,e,r,n){let o=ve(t,e+1,n);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer string lengths not supported`);return zn(t,e,9,o,n)}var Jd=Mr;function Or(t,e,r,n){return new C(x.array,n,r)}function Xd(t,e,r,n){return Or(t,e,1,r)}function Yd(t,e,r,n){return Or(t,e,2,be(t,e+1,n))}function Zd(t,e,r,n){return Or(t,e,3,xe(t,e+1,n))}function eh(t,e,r,n){return Or(t,e,5,ke(t,e+1,n))}function th(t,e,r,n){let o=ve(t,e+1,n);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer array lengths not supported`);return Or(t,e,9,o)}function rh(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${z} indefinite length items not allowed`);return Or(t,e,1,1/0)}function ui(t,e){oe(t,x.array.majorEncoded,e.value)}ui.compareTokens=Ie.compareTokens;ui.encodedSize=function(e){return oe.encodedSize(e.value)};function Rr(t,e,r,n){return new C(x.map,n,r)}function nh(t,e,r,n){return Rr(t,e,1,r)}function oh(t,e,r,n){return Rr(t,e,2,be(t,e+1,n))}function ih(t,e,r,n){return Rr(t,e,3,xe(t,e+1,n))}function sh(t,e,r,n){return Rr(t,e,5,ke(t,e+1,n))}function ah(t,e,r,n){let o=ve(t,e+1,n);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer map lengths not supported`);return Rr(t,e,9,o)}function ch(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${z} indefinite length items not allowed`);return Rr(t,e,1,1/0)}function li(t,e){oe(t,x.map.majorEncoded,e.value)}li.compareTokens=Ie.compareTokens;li.encodedSize=function(e){return oe.encodedSize(e.value)};function uh(t,e,r,n){return new C(x.tag,r,1)}function lh(t,e,r,n){return new C(x.tag,be(t,e+1,n),2)}function fh(t,e,r,n){return new C(x.tag,xe(t,e+1,n),3)}function dh(t,e,r,n){return new C(x.tag,ke(t,e+1,n),5)}function hh(t,e,r,n){return new C(x.tag,ve(t,e+1,n),9)}function fi(t,e){oe(t,x.tag.majorEncoded,e.value)}fi.compareTokens=Ie.compareTokens;fi.encodedSize=function(e){return oe.encodedSize(e.value)};var n1=20,o1=21,i1=22,s1=23;function ph(t,e,r,n){if(n.allowUndefined===!1)throw new Error(`${z} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new C(x.null,null,1):new C(x.undefined,void 0,1)}function yh(t,e,r,n){if(n.allowIndefinite===!1)throw new Error(`${z} indefinite length items not allowed`);return new C(x.break,void 0,1)}function Va(t,e,r){if(r){if(r.allowNaN===!1&&Number.isNaN(t))throw new Error(`${z} NaN values are not supported`);if(r.allowInfinity===!1&&(t===1/0||t===-1/0))throw new Error(`${z} Infinity values are not supported`)}return new C(x.float,t,e)}function mh(t,e,r,n){return Va(qa(t,e+1),3,n)}function gh(t,e,r,n){return Va(Wa(t,e+1),5,n)}function wh(t,e,r,n){return Va(vh(t,e+1),9,n)}function di(t,e,r){let n=e.value;if(n===!1)t.push([x.float.majorEncoded|n1]);else if(n===!0)t.push([x.float.majorEncoded|o1]);else if(n===null)t.push([x.float.majorEncoded|i1]);else if(n===void 0)t.push([x.float.majorEncoded|s1]);else{let o,i=!1;(!r||r.float64!==!0)&&(xh(n),o=qa(Pe,1),n===o||Number.isNaN(n)?(Pe[0]=249,t.push(Pe.slice(0,3)),i=!0):(kh(n),o=Wa(Pe,1),n===o&&(Pe[0]=250,t.push(Pe.slice(0,5)),i=!0))),i||(a1(n),o=vh(Pe,1),Pe[0]=251,t.push(Pe.slice(0,9)))}}di.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){xh(n);let o=qa(Pe,1);if(n===o||Number.isNaN(n))return 3;if(kh(n),o=Wa(Pe,1),n===o)return 5}return 9};var bh=new ArrayBuffer(9),Le=new DataView(bh,1),Pe=new Uint8Array(bh,0);function xh(t){if(t===1/0)Le.setUint16(0,31744,!1);else if(t===-1/0)Le.setUint16(0,64512,!1);else if(Number.isNaN(t))Le.setUint16(0,32256,!1);else{Le.setFloat32(0,t);let e=Le.getUint32(0),r=(e&2139095040)>>23,n=e&8388607;if(r===255)Le.setUint16(0,31744,!1);else if(r===0)Le.setUint16(0,(t&2147483648)>>16|n>>13,!1);else{let o=r-127;o<-24?Le.setUint16(0,0):o<-14?Le.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Le.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function qa(t,e){if(t.length-e<2)throw new Error(`${z} 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 kh(t){Le.setFloat32(0,t,!1)}function Wa(t,e){if(t.length-e<4)throw new Error(`${z} not enough data for float32`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,4).getFloat32(0,!1)}function a1(t){Le.setFloat64(0,t,!1)}function vh(t,e){if(t.length-e<8)throw new Error(`${z} not enough data for float64`);let r=(t.byteOffset||0)+e;return new DataView(t.buffer,r,8).getFloat64(0,!1)}di.compareTokens=Ie.compareTokens;function $(t,e,r){throw new Error(`${z} encountered invalid minor (${r}) for major ${t[e]>>>5}`)}function hi(t){return()=>{throw new Error(`${z} ${t}`)}}var B=[];for(let t=0;t<=23;t++)B[t]=$;B[24]=Ld;B[25]=Dd;B[26]=Nd;B[27]=Ud;B[28]=$;B[29]=$;B[30]=$;B[31]=$;for(let t=32;t<=55;t++)B[t]=$;B[56]=Pd;B[57]=Fd;B[58]=Md;B[59]=Rd;B[60]=$;B[61]=$;B[62]=$;B[63]=$;for(let t=64;t<=87;t++)B[t]=zd;B[88]=$d;B[89]=Hd;B[90]=jd;B[91]=Vd;B[92]=$;B[93]=$;B[94]=$;B[95]=hi("indefinite length bytes/strings are not supported");for(let t=96;t<=119;t++)B[t]=qd;B[120]=Wd;B[121]=Kd;B[122]=Gd;B[123]=Qd;B[124]=$;B[125]=$;B[126]=$;B[127]=hi("indefinite length bytes/strings are not supported");for(let t=128;t<=151;t++)B[t]=Xd;B[152]=Yd;B[153]=Zd;B[154]=eh;B[155]=th;B[156]=$;B[157]=$;B[158]=$;B[159]=rh;for(let t=160;t<=183;t++)B[t]=nh;B[184]=oh;B[185]=ih;B[186]=sh;B[187]=ah;B[188]=$;B[189]=$;B[190]=$;B[191]=ch;for(let t=192;t<=215;t++)B[t]=uh;B[216]=lh;B[217]=fh;B[218]=dh;B[219]=hh;B[220]=$;B[221]=$;B[222]=$;B[223]=$;for(let t=224;t<=243;t++)B[t]=hi("simple values are not supported");B[244]=$;B[245]=$;B[246]=$;B[247]=ph;B[248]=hi("simple values are not supported");B[249]=mh;B[250]=gh;B[251]=wh;B[252]=$;B[253]=$;B[254]=$;B[255]=yh;var Ke=[];for(let t=0;t<24;t++)Ke[t]=new C(x.uint,t,1);for(let t=-1;t>=-24;t--)Ke[31-t]=new C(x.negint,t,1);Ke[64]=new C(x.bytes,new Uint8Array(0),1);Ke[96]=new C(x.string,"",1);Ke[128]=new C(x.array,0,1);Ke[160]=new C(x.map,0,1);Ke[244]=new C(x.false,!1,1);Ke[245]=new C(x.true,!0,1);Ke[246]=new C(x.null,null,1);function Ka(t){switch(t.type){case x.false:return We([244]);case x.true:return We([245]);case x.null:return We([246]);case x.bytes:return t.value.length?void 0:We([64]);case x.string:return t.value===""?We([96]):void 0;case x.array:return t.value===0?We([128]):void 0;case x.map:return t.value===0?We([160]):void 0;case x.uint:return t.value<24?We([Number(t.value)]):void 0;case x.negint:if(t.value>=-24)return We([31-Number(t.value)])}}function Ga(){let t=[];return t[x.uint.major]=Ie,t[x.negint.major]=ai,t[x.bytes.major]=Mr,t[x.string.major]=Jd,t[x.array.major]=ui,t[x.map.major]=li,t[x.tag.major]=fi,t[x.float.major]=di,t}var H8=Ga(),j8=new si,yi=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(`${Ha} object contains circular references`);return new t(r,e)}},xt={null:new C(x.null,null),undefined:new C(x.undefined,void 0),true:new C(x.true,!0),false:new C(x.false,!1),emptyArray:new C(x.array,0),emptyMap:new C(x.map,0)},kt={number(t,e,r,n){return!Number.isInteger(t)||!Number.isSafeInteger(t)?new C(x.float,t):t>=0?new C(x.uint,t):new C(x.negint,t)},bigint(t,e,r,n){return t>=BigInt(0)?new C(x.uint,t):new C(x.negint,t)},Uint8Array(t,e,r,n){return new C(x.bytes,t)},string(t,e,r,n){return new C(x.string,t)},boolean(t,e,r,n){return t?xt.true:xt.false},null(t,e,r,n){return xt.null},undefined(t,e,r,n){return xt.undefined},ArrayBuffer(t,e,r,n){return new C(x.bytes,new Uint8Array(t))},DataView(t,e,r,n){return new C(x.bytes,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))},Array(t,e,r,n){if(!t.length)return r.addBreakTokens===!0?[xt.emptyArray,new C(x.break)]:xt.emptyArray;n=yi.createCheck(n,t);let o=[],i=0;for(let s of t)o[i++]=pi(s,r,n);return r.addBreakTokens?[new C(x.array,t.length),o,new C(x.break)]:[new C(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?[xt.emptyMap,new C(x.break)]:xt.emptyMap;n=yi.createCheck(n,t);let c=[],a=0;for(let u of i)c[a++]=[pi(u,r,n),pi(o?t.get(u):t[u],r,n)];return u1(c,r),r.addBreakTokens?[new C(x.map,s),c,new C(x.break)]:[new C(x.map,s),c]}};kt.Map=kt.Object;kt.Buffer=kt.Uint8Array;for(let t of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))kt[`${t}Array`]=kt.DataView;function pi(t,e={},r){let n=kd(t),o=e&&e.typeEncoders&&e.typeEncoders[n]||kt[n];if(typeof o=="function"){let s=o(t,n,e,r);if(s!=null)return s}let i=kt[n];if(!i)throw new Error(`${Ha} unsupported type: ${n}`);return i(t,n,e,r)}function u1(t,e){e.mapSorter&&t.sort(e.mapSorter)}var G8=Symbol.for("DONE"),Q8=Symbol.for("BREAK");var l1=Ga(),f1={float64:!1,quickEncodeToken:Ka};function Qa(t,e=l1,r=f1){if(Array.isArray(t)){let n=0;for(let o of t)n+=Qa(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 Xa=class{constructor(e,r){this.bytes=e,this.byteOffset=r,this.roots=[],this.headerSize=r}addRoot(e,r){return d1(this,e,r),this}write(e){return h1(this,e),this}close(e){return p1(this,e)}},d1=(t,e,r={})=>{let{resize:n=!1}=r,{bytes:o,headerSize:i,byteOffset:s,roots:c}=t;t.roots.push(e);let a=mi(t);if(a>i)if(a-i+s<o.byteLength)if(n)Ah(t,a);else throw c.pop(),new RangeError(`Header of size ${i} has no capacity for new root ${e}.
|
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}`)},Sh=({cid:t,bytes:e})=>{let r=t.bytes.byteLength+e.byteLength;return $n.default.encodingLength(r)+r},h1=(t,{cid:e,bytes:r})=>{let n=e.bytes.byteLength+r.byteLength,o=$n.default.encode(n);if(t.byteOffset+o.length+n>t.bytes.byteLength)throw new RangeError("Buffer has no capacity for this block");Ja(t,o),Ja(t,e.bytes),Ja(t,r)},p1=(t,e={})=>{let{resize:r=!1}=e,{roots:n,bytes:o,byteOffset:i,headerSize:s}=t,c=ri({version:1,roots:n}),a=$n.default.encode(c.length),u=a.length+c.byteLength;if(s-u===0)return Eh(t,a,c),o.subarray(0,i);if(r)return Ah(t,u),Eh(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`)},Ah=(t,e)=>{let{bytes:r,headerSize:n}=t;r.set(r.subarray(n,t.byteOffset),e),t.byteOffset+=e-n,t.headerSize=e},Ja=(t,e)=>{t.bytes.set(e,t.byteOffset),t.byteOffset+=e.length},Eh=({bytes:t},e,r)=>{t.set(e),t.set(r,e.length)},y1=[new C(x.map,2),new C(x.string,"version"),new C(x.uint,1),new C(x.string,"roots")],m1=new C(x.tag,42),g1=t=>{let e=[...y1];e.push(new C(x.array,t.length));for(let n of t)e.push(m1),e.push(new C(x.bytes,{length:n+1}));let r=Qa(e);return $n.default.encodingLength(r)+r},mi=({roots:t})=>g1(t.map(e=>e.bytes.byteLength));var _h=(t,e={})=>{let{roots:r=[],byteOffset:n=0,byteLength:o=t.byteLength,headerSize:i=mi({roots:r})}=e,s=new Uint8Array(t,n,o),c=new Xa(s,i);for(let a of r)c.addRoot(a);return c};var Kt=({name:t,code:e,encode:r})=>new Ya(t,e,r),Ya=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?jt(this.code,r):r.then(n=>jt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function gi({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*b1(t,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r],i=V.asCID(n);i?yield[o.join("/"),i]:typeof n=="object"&&(yield*Za(n,o))}else{let r=V.asCID(e);r?yield[t.join("/"),r]:yield*Za(e,t)}}function*Za(t,e){if(t==null||t instanceof Uint8Array)return;let r=V.asCID(t);r&&(yield[e.join("/"),r]);for(let[n,o]of Object.entries(t)){let i=[...e,n];yield*b1(i,o)}}function*x1(t,e){if(Array.isArray(e))for(let[r,n]of e.entries()){let o=[...t,r];yield o.join("/"),typeof n=="object"&&!V.asCID(n)&&(yield*ec(n,o))}else yield*ec(e,t)}function*ec(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"&&!V.asCID(n)&&(yield*x1(o,n))}}function k1(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=V.asCID(r);if(i)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:r}}var Hn=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:gi(),bytes:gi(),value:gi(),asBlock:gi()})}links(){return Za(this.value,[])}tree(){return ec(this.value,[])}get(e="/"){return k1(this.value,e.split("/").filter(Boolean))}};async function Ge({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=V.create(1,e.code,o);return new Hn({value:t,bytes:n,cid:i})}async function vt({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=V.create(1,e.code,o);return new Hn({value:n,bytes:t,cid:i})}function v1({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 Hn({cid:e,bytes:t,value:o})}async function wi({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(!Ht.equals(e.multihash.bytes,i.bytes))throw new Error("CID hash does not match bytes");return v1({bytes:t,cid:e,value:o,codec:n})}var Ch=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),de=Kt({name:"sha2-256",code:18,encode:Ch("SHA-256")}),S_=Kt({name:"sha2-512",code:19,encode:Ch("SHA-512")});var Et={};Q(Et,{code:()=>jn,decode:()=>A1,encode:()=>S1,name:()=>E1});var E1="raw",jn=85,S1=t=>Te(t),A1=t=>Te(t);async function Vn(t,e){let r=0,n=mi({roots:t});r+=n;for(let{cid:s,bytes:c}of e.entries())r+=Sh({cid:s,bytes:c});let o=new Uint8Array(r),i=_h(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 Ge({value:i.bytes,hasher:de,codec:Et})}async function tc(t){return await Ge({value:{fp:t},hasher:de,codec:q})}async function rc(t){let e=await t.getRoots(),r=await t.get(e[0]);if(!r)throw new Error("missing header block");let{value:n}=await vt({bytes:r.bytes,hasher:de,codec:q});if(n&&n.fp===void 0)throw new Error("missing fp");let{fp:o}=n;return o}var Gt={};Q(Gt,{code:()=>I1,crypto:()=>L1,decode:()=>T1,decrypt:()=>ki,encode:()=>C1,encrypt:()=>vi,name:()=>D1});function bi(){try{return window.crypto&&window.crypto.subtle?window.crypto:new Crypto}catch{return null}}var qn=bi();function xi(t){let e=new Uint8Array(t);return t>0&&qn.getRandomValues(e),e}var _1=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},B1=t=>{let e=t.byteLength-4;return(t[e]|t[e+1]<<8|t[e+2]<<16)+t[e+3]*16777216},Th=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},C1=({iv:t,bytes:e})=>Th([t,e]),T1=t=>{let e=t.subarray(0,12);return t=t.slice(12),{iv:e,bytes:t}},I1=3145728+1337;async function Ih(t){return await qn.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt","decrypt"])}var ki=async({key:t,value:e})=>{let{bytes:r,iv:n}=e,o=await Ih(t),i=await qn.subtle.decrypt({name:"AES-GCM",iv:n,tagLength:128},o,r);r=new Uint8Array(i);let s=B1(r.subarray(0,4)),c=V.decode(r.subarray(4,4+s));return r=r.subarray(4+s),{cid:c,bytes:r}},vi=async({key:t,cid:e,bytes:r})=>{let n=_1(e.bytes.byteLength),o=xi(12),i=Th([n,e.bytes,r]);try{let s=await Ih(t),c=await qn.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}}},L1=t=>({encrypt:e=>vi({key:t,...e}),decrypt:e=>ki({key:t,...e})}),D1="jchris@encrypted-block:aes-gcm";var Wn=t=>{let e=t.byteLength-4;return(t[e]|t[e+1]<<8|t[e+2]<<16)+t[e+3]*16777216};var Kn=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 Jt=(t,e)=>t===e?0:t>e?1:-1,Lh=(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},Qt=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 Xt=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}},St=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)}}},Dh=t=>typeof t=="string"?t:JSON.stringify(t);function N1(t,e){return t.sort(({key:r},{key:n})=>e.compare(r,n))}async function U1(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 P1(t,e,{chunker:r,compare:n}){return await At.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 F1(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 M1(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 U1(c,r,t.compare);if(a.length){let u=await P1(a,i,t),l=await F1(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 At.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 At.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 At=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 Qt){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 Qt){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 Qt){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 Qt){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=Dh(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=Dh(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:v}=await p;c=v,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:T},{key:U})=>s.compare(T,U)),NodeClass:c,distance:i}),b=await m(g,o,s),v=await t.from({...n,entries:[...w.entryList.entries,...b,...l].sort(({key:T},{key:U})=>s.compare(T,U)),NodeClass:a,distance:i});return await m(v,o,s)}}else{let g=await d(h,w.entryList.entries),b=await t.from({...n,entries:g.sort(({key:E},{key:T})=>s.compare(E,T)),NodeClass:c,distance:i}),v=await m(b,o,s);return await d(v,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=N1(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 M1(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 St({entries:c,closed:!0})),c=[]);return c.length&&s.push(new St({entries:c,closed:!1})),s.map(a=>new n({entryList:a,chunker:r,distance:o,...i}))}},Ei=class extends At{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 Ge(r),this.block}},zr=class extends Ei{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}},$r=class extends Ei{async encodeNode(){return{leaf:await Promise.all(this.entryList.entries.map(async r=>await r.encodeNode())),closed:this.closed}}get isLeaf(){return!0}},Si=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 At.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 At.from({entries:m,chunker:s,NodeClass:n,distance:l,opts:a}),yield*u,l++}};var nc=({bytes:t},{bytes:e})=>Lh(t,e),Ai=class extends Xt{constructor(e){super({address:e,key:e}),this.cid=e}encodeNode(){return this.cid}identity(){let e=this.cid.multihash.bytes;return Wn(e)}},_i=class extends Xt{async identity(){let{multihash:{bytes:e}}=await this.address;return Wn(e)}},Bi=class extends zr{},Ci=class extends $r{},Nh=(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:nc},l,d;if(a.leaf)l=a.leaf.map(h=>new Ai(h)),d=Ci;else if(a.branch){let[h,p]=a.branch;u.distance=h,l=p.map(([w,g])=>new _i({key:w,address:g})),d=Bi}else throw new Error("Unknown block data, does not match schema");let m=new St({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},Uh=({get:t,cache:e,chunker:r,list:n,codec:o,hasher:i,sorted:s})=>{s||(n=n.sort(nc));let c=Nh(t,e,r,o,i);return Si({list:n,codec:o,hasher:i,chunker:r,getNode:c,sorted:s,compare:nc,cache:e,LeafClass:Ci,LeafEntryClass:Ai,BranchClass:Bi,BranchEntryClass:_i})},Ph=({cid:t,get:e,cache:r,chunker:n,codec:o,hasher:i,...s})=>Nh(e,r,n,o,i,s)(t);var Fh=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 vi({...h,key:n}),w=await Ge({...p,codec:Gt,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=>V.parse(f)),l;for await(let f of Uh({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 Ge({value:d,codec:q,hasher:r})},Mh=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 vt({...g,codec:q,hasher:i}):void 0),c=async w=>e(w).then(async g=>g?await vt({...g,codec:Gt,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 Ph({cid:l,get:s,cache:n,chunker:o,codec:Gt,hasher:i}),{result:f}=await m.getAllEntries(),h=async w=>{if(!w)throw new Error("missing block");w.value||(w=await vt({...w,codec:Gt,hasher:i}));let{bytes:g,cid:b}=await ki({...w,key:r}).catch(E=>{throw E});return await wi({cid:b,bytes:g,hasher:i,codec:Gt})},p=[];for(let{cid:w}of f)d.cid.equals(w)||p.push(c(w).then(h));yield*p,yield h(d)};var Hr={has:()=>!1,get:()=>{throw new Error("Cannot ask for entries from nocache")},set:()=>{}};var Oh=Kn(30);function Rh(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 zh(t,e,r){let n=Rh(t),o=n.buffer.slice(0,n.byteLength),i=new _e,s=[];for(let{cid:u}of r.entries())s.push(u);let c=null;for await(let u of Fh({cids:s,get:r.get.bind(r),key:o,hasher:de,chunker:Oh,cache:Hr,root:e}))await i.put(u.cid,u.bytes),c=u;if(!c)throw new Error("no blocks encrypted");return await Vn([c.cid],i)}async function $h(t,e){let n=(await e.getRoots())[0];return await O1(n,e.get.bind(e),t)}async function O1(t,e,r){let n=Rh(r),o=n.buffer.slice(0,n.byteLength),i=new _e,s=null;for await(let c of Mh({root:t,get:e,key:o,hasher:de,chunker:Oh,cache:Hr}))await i.put(c.cid,c.bytes),s=c;if(!s)throw new Error("no blocks decrypted");return{blocks:i,root:s.cid}}var oc=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(`${it} unsupported type: Uint8Array`)}[y.string.major](e,r){this.prefix(e);let n=Vo(JSON.stringify(r.value));e.push(n.length>32?En(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(`${it} 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 R1(t,e){if(Array.isArray(t[0])||Array.isArray(e[0]))throw new Error(`${it} 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(`${it} non-string map keys are not supported`);if(r<n)return-1;if(r>n)return 1;throw new Error(`${it} unexpected duplicate map keys, this is not supported`)}var z1={addBreakTokens:!0,mapSorter:R1};function ic(t,e){return e=Object.assign({},z1,e),xa(t,new oc,e)}var jr=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(`${I} 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(`${I} 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 S(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(`${I} unexpected token at position ${this.pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${I} 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 S(y.float,s,this.pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new S(s>=0?y.uint:y.negint,s,this.pos-e):new S(s>=0?y.uint:y.negint,BigInt(i),this.pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${I} 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 S(y.string,a,s)}}let e=this.pos,r=[],n=()=>{if(this.pos+4>=this.data.length)throw new Error(`${I} 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(`${I} 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(`${I} 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(`${I} 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(`${I} unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new S(y.string,pa(r),this.pos-e);default:if(i<32)throw new Error(`${I} invalid control character at position ${this.pos}`);i<128?(r.push(i),this.pos++):o()}}throw new Error(`${I} unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new S(y.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new S(y.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new S(y.null,null,4);case 102:return this.expect([102,97,108,115,101]),new S(y.false,!1,5);case 116:return this.expect([116,114,117,101]),new S(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(`${I} 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 S(y.break,void 0,1);if(this.ch()!==44)throw new Error(`${I} 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 S(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 S(y.break,void 0,1);if(this.ch()!==44)throw new Error(`${I} 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 S(y.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${I} 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(`${I} unexpected parse state at position ${this.pos}; this shouldn't happen`)}}};function sc(t,e){return e=Object.assign({tokenizer:new jr(t,e)},e),In(t,e)}var ac=ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),d6=ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),h6=ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),p6=ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function H1(t){if(t.asCID!==t&&t["/"]!==t.bytes)return null;let e=V.asCID(t);if(!e)return null;let r=e.toString();return[new S(y.map,1/0,1),new S(y.string,"/",1),new S(y.string,r,r.length),new S(y.break,void 0,1)]}function Ti(t){let e=ac.encode(t).slice(1);return[new S(y.map,1/0,1),new S(y.string,"/",1),new S(y.map,1/0,1),new S(y.string,"bytes",5),new S(y.string,e,e.length),new S(y.break,void 0,1),new S(y.break,void 0,1)]}function Fe(t){return Ti(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function j1(t){return Ti(new Uint8Array(t))}function V1(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function q1(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 W1={typeEncoders:{Object:H1,Buffer:Ti,Uint8Array:Ti,Int8Array:Fe,Uint16Array:Fe,Int16Array:Fe,Uint32Array:Fe,Int32Array:Fe,Float32Array:Fe,Float64Array:Fe,Uint8ClampedArray:Fe,BigInt64Array:Fe,BigUint64Array:Fe,DataView:Fe,ArrayBuffer:j1,undefined:V1,number:q1}},cc=class extends jr{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 S(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=ac.decode(`m${i.value}`);return new S(y.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(r)}return e}},uc={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};uc.tags[42]=V.parse;var K1=t=>ic(t,W1),G1=t=>{let e=Object.assign(uc,{tokenizer:new cc(t,uc)});return sc(t,e)},Ii=t=>Q1.decode(K1(t));var Q1=new TextDecoder,Li=t=>G1(J1.encode(t)),J1=new TextEncoder;var X1=(t,e)=>e.some(r=>t instanceof r),Hh,jh;function Y1(){return Hh||(Hh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Z1(){return jh||(jh=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Vh=new WeakMap,fc=new WeakMap,qh=new WeakMap,lc=new WeakMap,hc=new WeakMap;function ex(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&&Vh.set(r,t)}).catch(()=>{}),hc.set(e,t),e}function tx(t){if(fc.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)});fc.set(t,e)}var dc={get(t,e,r){if(t instanceof IDBTransaction){if(e==="done")return fc.get(t);if(e==="objectStoreNames")return t.objectStoreNames||qh.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 Wh(t){dc=t(dc)}function rx(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...r){let n=t.call(Di(this),e,...r);return qh.set(n,e.sort?e.sort():[e]),Qe(n)}:Z1().includes(t)?function(...e){return t.apply(Di(this),e),Qe(Vh.get(this))}:function(...e){return Qe(t.apply(Di(this),e))}}function nx(t){return typeof t=="function"?rx(t):(t instanceof IDBTransaction&&tx(t),X1(t,Y1())?new Proxy(t,dc):t)}function Qe(t){if(t instanceof IDBRequest)return ex(t);if(lc.has(t))return lc.get(t);let e=nx(t);return e!==t&&(lc.set(t,e),hc.set(e,t)),e}var Di=t=>hc.get(t);function Gh(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 ox=["get","getKey","getAll","getAllKeys","count"],ix=["put","add","delete","clear"],pc=new Map;function Kh(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(pc.get(e))return pc.get(e);let r=e.replace(/FromIndex$/,""),n=e!==r,o=ix.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||ox.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 pc.set(e,i),i}Wh(t=>({...t,get:(e,r,n)=>Kh(e,r)||t.get(e,r,n),has:(e,r)=>!!Kh(e,r)||t.has(e,r)}));var yc="0.13.3-dev";var Qh=yc.match(/^([^.]*\.[^.]*)/);if(!Qh)throw new Error("invalid version: "+yc);var Jn=Qh[0],mc=class{constructor(e){k(this,"STORAGE_VERSION",Jn);k(this,"name");this.name=e}},Gn=class extends mc{constructor(){super(...arguments);k(this,"tag","header-base")}makeHeader({car:r,key:n}){return Ii({car:r,key:n})}parseHeader(r){return Li(r)}},Qn=class{constructor(e){k(this,"tag","car-base");k(this,"STORAGE_VERSION",Jn);k(this,"loader");this.loader=e}};var Ni=class{constructor(e){k(this,"tag","rwal-base");k(this,"STORAGE_VERSION",Jn);k(this,"loader");k(this,"ready");k(this,"walState",{operations:[],noLoaderOps:[],fileOperations:[]});k(this,"processing");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=vn(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 Vr=class extends Qn{constructor(){super(...arguments);k(this,"tag","car-browser-idb");k(this,"idb",null)}async _withDB(r){if(!this.idb){let n=`fp.${this.STORAGE_VERSION}.${this.loader.keyId}.${this.loader.name}`;this.idb=await Gh(n,1,{upgrade(o){o.createObjectStore("cars")}})}return await r(this.idb)}async load(r){return await this._withDB(async n=>{let i=await n.transaction(["cars"],"readonly").objectStore("cars").get(r.toString());if(!i)throw new Error(`missing idb block ${r.toString()}`);return{cid:r,bytes:i}})}async save(r){return await this._withDB(async n=>{let o=n.transaction(["cars"],"readwrite");return await o.objectStore("cars").put(r.bytes,r.cid.toString()),await o.done})}async remove(r){return await this._withDB(async n=>{let o=n.transaction(["cars"],"readwrite");return await o.objectStore("cars").delete(r.toString()),await o.done})}},Ui=class extends Ni{constructor(){super(...arguments);k(this,"tag","wal-browser-ls")}headerKey(r){return`fp.${this.STORAGE_VERSION}.wal.${this.loader.name}.${r}`}async load(r="main"){try{let n=localStorage.getItem(this.headerKey(r));return n?Li(n):null}catch{return null}}async save(r,n="main"){try{let o=Ii(r);localStorage.setItem(this.headerKey(n),o)}catch{}}},Pi=class extends Gn{constructor(){super(...arguments);k(this,"tag","header-browser-ls")}headerKey(r){return`fp.${this.STORAGE_VERSION}.meta.${this.name}.${r}`}async load(r="main"){try{let n=localStorage.getItem(this.headerKey(r));return n?[this.parseHeader(n)]:null}catch{return null}}async save(r,n="main"){try{let o=this.headerKey(n),i=this.makeHeader(r);return localStorage.setItem(o,i),null}catch{return null}}};function gc(t,e){return t.some(r=>r.equals(e))}function Jh(t,e=[]){let r=new Map;for(let n of t)gc(e,n)||r.set(n.toString(),n);return[...r.values()]}function Xh(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Yt=class{constructor(e,r){k(this,"name");k(this,"opts",{});k(this,"remoteMetaLoading");k(this,"remoteMetaStore");k(this,"remoteCarStore");k(this,"remoteWAL");k(this,"metaStore");k(this,"carStore");k(this,"carLog",[]);k(this,"carReaders",new Map);k(this,"ready");k(this,"key");k(this,"keyId");k(this,"getBlockCache",new Map);k(this,"committing");this.name=e,this.opts=r||this.opts,this.metaStore=new Pi(this.name),this.carStore=new Vr(this),this.remoteWAL=new Ui(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=V.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),gc(this.carLog,e.car))return;let r=await this.loadCarHeaderFromMeta(e);await this.getMoreReaders(r.cars),this.carLog=[...Jh([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 rc(r)}async _getKey(){return this.key?this.key:(this.opts.public||(bi()?await this.setKey(Xh(xi(32))):console.warn("missing crypto module, using public mode")),this.key)}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 tc(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 zh(s,i[0],e):await Vn(i,e);if(wc(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=[...Jh([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 qt.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 $h(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=bi();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=vn(5),n=e.filter(o=>!this.carReaders.has(o.toString()));await Promise.all(n.map(o=>r(()=>this.loadCar(o))))}};k(Yt,"defaultHeader");var qr=W(np(),1);var Fi=class extends Xt{async identity(){let e=await this.codec.encode(await this.encodeNode()),r=await this.hasher.encode(e);return Wn(r)}},Zt=class extends Fi{constructor(e,r){super(e,r),this.value=e.value}encodeNode(){return[this.key,this.value]}},er=class extends Fi{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]}},op=async(t,e)=>{let{result:r,cids:n}=await t.getEntry(e);return{result:r.value,cids:n}},ip=async(t,e)=>{let{result:r,cids:n}=await t.getEntries(e);return{result:r.map(o=>o.value),cids:n}},tr=class extends $r{get(e){return op(this,e)}getMany(e){return ip(this,e)}bulk(e,r={},n=!0){return super.bulk(e,{...sp,...r},n)}},rr=class extends zr{get(e){return op(this,e)}getMany(e){return ip(this,e)}bulk(e,r={},n=!0){return super.bulk(e,{...sp,...r},n)}},sp={LeafClass:tr,LeafEntryClass:Zt,BranchClass:rr,BranchEntryClass:er},ap=(t,e,r,n,o,i,s)=>{let c=s.LeafClass||tr,a=s.LeafEntryClass||Zt,u=s.BranchClass||rr,l=s.BranchEntryClass||er,d=async f=>e.has(f)?e.get(f):t(f).then(h=>m(h)),m=hx({chunker:r,cache:e,getNode:d,codec:n,hasher:o,compare:i,LeafEntryClass:a,LeafClass:c,BranchEntryClass:l,BranchClass:u});return d},cp=({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=ap(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||tr,LeafEntryClass:a.LeafEntryClass||Zt,BranchClass:a.BranchClass||rr,BranchEntryClass:a.BranchEntryClass||er};return Si(l)},up=({cid:t,get:e,cache:r,chunker:n,codec:o,hasher:i,compare:s,...c})=>ap(e,r,n,o,i,s,c)(t);function hx({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,v])=>new s({key:b,value:v},l)),p=c;else if(m.branch){let[b,v]=m.branch;f.distance=b,h=v.map(([E,T])=>new a({key:E,address:T},l)),p=u}else throw new Error("Unknown block data, does not match schema");let w=new St({entries:h,closed:m.closed}),g=new p({entryList:w,...f});return e.set(g),g}}var px=(t,e)=>{let[r,n]=t,[o,i]=e,s=Jt(r,o);return s!==0?s:yx(n,i)},yx=(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)?Jt(t,e):1},lp=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}},fp=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}},xc=class extends tr{get(e){return lp(this,e)}range(e,r){return fp(this,e,r)}bulk(e,r={},n=!0){return super.bulk(e,{...vc,...r},n)}},kc=class extends rr{get(e){return lp(this,e)}range(e,r){return fp(this,e,r)}bulk(e,r={},n=!0){return super.bulk(e,{...vc,...r},n)}},mx=xc,gx=kc,vc={LeafClass:mx,BranchClass:gx,LeafEntryClass:Zt,BranchEntryClass:er},dp={...vc,compare:px},hp=t=>(t={...dp,...t},cp(t)),Ec=t=>(t={...dp,...t},up(t));var nr=class{constructor(){k(this,"cid",null);k(this,"root",null)}},bx=(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:Jt(t,e)},xx=(t,e)=>{let[r,n]=t,[o,i]=e,s=Jt(r,o);return s!==0?s:bx(n,i)},Ac={cache:Hr,chunker:Kn(30),codec:q,hasher:de,compare:xx},_c={cache:Hr,chunker:Kn(30),codec:q,hasher:de,compare:Jt};function pp(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:[qr.default.encode(a),n],value:u||null})});!s&&c&&r.push({key:[qr.default.encode(c),n],value:null})}),r}function Sc(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 wi({cid:n,bytes:o,hasher:de,codec:q})}}async function Bc(t,e,r,n){if(!r.length)return e;if(!e.root)if(e.cid)e.root=await Ec({cid:e.cid,get:Sc(t),...n});else{let s=null,c=null;for await(let a of await hp({get:Sc(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 Cc(t,e,r){return await Ec({cid:e,get:Sc(t),...r})}async function or(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=qr.default.decode(n.key),n.row&&!n.value&&(n.value=n.row,delete n.row),n))}}function Tc(t){return t.map(e=>qr.default.encode(e))}function Ic(t){return qr.default.encode(t)}function Wr({_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 Mi(t,e,r,n);t.indexers.set(e,o)}return t.indexers.get(e)}var Mi=class{constructor(e,r,n,o){k(this,"blocks");k(this,"crdt");k(this,"name",null);k(this,"mapFn",null);k(this,"mapFnString","");k(this,"byKey",new nr);k(this,"byId",new nr);k(this,"indexHead");k(this,"includeDocsDefault",!1);k(this,"initError",null);k(this,"ready");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=kx(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 or(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(...Tc(e.range));return await or(this.crdt,{result:o,...i},e)}if(e.key){let o=Ic(e.key);return await or(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=Ic(i);return(await or(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=Tc([o,i]);return await or(this.crdt,await this.byKey.root.range(...s),e)}let{result:r,...n}=await this.byKey.root.getAllEntries();return await or(this.crdt,{result:r.map(({key:[o,i],value:s})=>({key:o,id:i,value:s})),...n},e)}_resetIndex(){this.byId=new nr,this.byKey=new nr,this.indexHead=void 0}async _hydrateIndex(){this.byId.root&&this.byKey.root||!this.byId.cid||!this.byKey.cid||(this.byId.root=await Cc(this.blocks,this.byId.cid,_c),this.byKey.root=await Cc(this.blocks,this.byKey.cid,Ac))}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=pp(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 Bc(a,this.byId,o.concat(s),_c),this.byKey=await Bc(a,this.byKey,n.concat(i),Ac),this.indexHead=r,{byId:this.byId.cid,byKey:this.byKey.cid,head:r,map:this.mapFnString,name:this.name}),c)}};function kx(t){return e=>{if(e[t])return e[t]}}var zi=class zi extends Yt{constructor(r,n,o){super(r,o);k(this,"crdt");k(this,"defaultHeader",zi.defaultHeader);this.crdt=n}async _applyCarHeader(r){for(let[n,o]of Object.entries(r.indexes))Wr({_crdt:this.crdt},n,void 0,o)}makeCarHeader({indexes:r},n,o=!1){return o?{indexes:r,cars:[],compact:n}:{indexes:r,cars:n,compact:[]}}};k(zi,"defaultHeader",{cars:[],compact:[],indexes:new Map});var Oi=zi,$i=class $i extends Yt{constructor(r,n,o){super(r,o);k(this,"defaultHeader",$i.defaultHeader);k(this,"clock");k(this,"remoteFileStore");k(this,"fileStore");this.fileStore=new Vr(this),this.clock=n}async loadFileCar(r,n=!1){return await this.storesLoadCar(r,this.fileStore,this.remoteFileStore,n)}async _applyCarHeader(r,n=!1){n?await this.clock.applyHead(null,r.head,this.clock.head):await this.clock.applyHead(null,r.head,[])}makeCarHeader(r,n,o=!1){if(wc(r)){let i=[];for(let[,s]of Object.entries(r.files))i.push(s.cid);return{files:i}}else{let{head:i}=r;return o?{head:i,cars:[],compact:n}:{head:i,cars:n,compact:[]}}}};k($i,"defaultHeader",{cars:[],compact:[],head:[]});var Ri=$i;function wc(t){return t&&t.files!==void 0}var _t=class extends _e{constructor(r){super();k(this,"parent");this.parent=r}async get(r){return this.parent.get(r)}async superGet(r){return super.get(r)}},Hi=class{constructor(e,r,n){k(this,"ready");k(this,"name",null);k(this,"loader",null);k(this,"opts",{});k(this,"transactions",new Set);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 _t(this);this.transactions.add(n);let o=await e(n),{car:i,done:s}=await r(n,o);return i?{...s,car:i}:s}},ji=class extends Hi{constructor(e,r,n){e?super(e,new Oi(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}))}},Vi=class extends Hi{constructor(e,r,n){e?super(e,new Ri(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}))}},qi=class{constructor(e){k(this,"blocks");k(this,"loader",null);k(this,"cids",new Set);this.blocks=e,this.loader=e.loader}async get(e){return this.cids.add(e),await this.blocks.get(e)}};var Dc=({name:t,code:e,encode:r})=>new Lc(t,e,r),Lc=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?Ft(this.code,r):r.then(n=>Ft(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Wi({enumerable:t=!0,configurable:e=!1}={}){return{enumerable:t,configurable:e,writable:!1}}function*vx(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*Nc(n,o))}else{let r=j.asCID(e);r?yield[t.join("/"),r]:yield*Nc(e,t)}}function*Nc(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*vx(i,o)}}function*Ex(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*Uc(n,o))}else yield*Uc(e,t)}function*Uc(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*Ex(o,n))}}function Sx(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 Me=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:Wi(),bytes:Wi(),value:Wi(),asBlock:Wi()})}links(){return Nc(this.value,[])}tree(){return Uc(this.value,[])}get(e="/"){return Sx(this.value,e.split("/").filter(Boolean))}};async function Ki({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 Me({value:t,bytes:n,cid:i})}async function Gi({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 Me({value:n,bytes:t,cid:i})}var Pc={};Q(Pc,{sha256:()=>ut,sha512:()=>Ax});var mp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),ut=Dc({name:"sha2-256",code:18,encode:mp("SHA-256")}),Ax=Dc({name:"sha2-512",code:19,encode:mp("SHA-512")});async function Yn(t,e,r){let n=new Je(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 gp(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 gp(n,s,r))return e;return e.concat(r)}var Xn=class extends Me{constructor({cid:e,value:r,bytes:n,prefix:o}){super({cid:e,value:r,bytes:n}),this.prefix=o}static create(e,r){return _x({data:e,parents:r??[]})}},Je=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 Bx(r.bytes)}};async function _x(t){let{cid:e,bytes:r}=await Ki({value:t,codec:q,hasher:ut});return new Me({cid:e,value:t,bytes:r})}async function Bx(t){let{cid:e,value:r}=await Gi({bytes:t,codec:q,hasher:ut});return new Me({cid:e,value:r,bytes:t})}async function gp(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*Fc(t,e,r={}){let n=r.renderNodeLabel??(a=>Cx(a.cid)),o=new Je(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 Cx=t=>`${String(t).slice(0,4)}..${String(t).slice(-4)}`;var ir=class extends Me{constructor({cid:e,value:r,bytes:n,prefix:o}){super({cid:e,value:r,bytes:n}),this.prefix=o}static create(){return Xe([])}};async function Xe(t,e){let{cid:r,bytes:n}=await Ki({value:t,codec:q,hasher:ut});return new ir({cid:r,value:t,bytes:n,prefix:e??""})}async function wp(t,e){let{cid:r,value:n}=await Gi({bytes:t,codec:q,hasher:ut});if(!Array.isArray(n))throw new Error(`invalid shard: ${r}`);return new ir({cid:r,value:n,bytes:t,prefix:e??""})}var sr=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 wp(n.bytes,r)}};function Mc(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 bp(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 Qi=64,Ix=512*1024;async function Zn(t,e,r,n,o={}){let i=new sr(t),s=await i.get(e),c=await Ji(i,s,r),a=c[c.length-1],u=r.slice(a.prefix.length),l=[u,n],d=[];if(u.length>Qi){let h=Array.from(Array(Math.ceil(u.length/Qi)),(w,g)=>{let b=g*Qi;return{prefix:a.prefix+u.slice(0,b),skey:u.slice(b,b+Qi)}}),p=await Xe([[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 Xe([[h[w].skey,[p.cid]]],h[w].prefix),d.push(p);l=[h[0].skey,[p.cid]]}let m=Mc(a.value,l),f=await Xe(m,a.prefix);if(f.bytes.length>(o.maxShardSize??Ix)){let h=bp(m,l[0]);if(!h)throw new Error("shard limit reached");let{prefix:p,matches:w}=h,g=await Xe(w.filter(([E])=>E!==p).map(([E,T])=>[E.slice(p.length),T]),a.prefix+p);d.push(g);let b,v=w.find(([E])=>E===p);if(v){if(Array.isArray(v[1]))throw new Error(`expected "${p}" to be a shard value but found a shard link`);b=[g.cid,v[1]]}else b=[g.cid];m=m.filter(E=>w.every(T=>E[0]!==T[0])),m=Mc(m,[p,b]),f=await Xe(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[v,E]=b;if(v!==w)return b;if(!Array.isArray(E))throw new Error(`"${w}" is not a shard link in: ${p.cid}`);return E[1]==null?[v,[f.cid]]:[v,[f.cid,E[1]]]});f=await Xe(g,p.prefix),d.push(f)}return{root:d[d.length-1].cid,additions:d,removals:c}}async function xp(t,e,r){let n=new sr(t),o=await n.get(e),i=await Ji(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 Oc(t,e,r){let n=new sr(t),o=await n.get(e),i=await Ji(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 Xe(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[v,E]=b;if(v!==w)return b;if(!Array.isArray(E))throw new Error(`"${w}" is not a shard link in: ${p.cid}`);return E[1]==null?[v,[f.cid]]:[v,[f.cid,E[1]]]});f=await Xe(g,p.prefix),l.push(f)}return{root:l[l.length-1].cid,additions:l,removals:d}}async function*kp(t,e,r={}){let{prefix:n}=r,o=new sr(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 Ji(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 Ji(t,await t.get(o[0],e.prefix+n),r.slice(n.length));return[e,...i]}}return[e]}async function vp(t,e,r,n,o){let i=new _e;if(t=new Ot(i,t),!e.length){let g=await ir.create();i.putSync(g.cid,g.bytes);let b=await Zn(t,g.cid,r,n,o),v={type:"put",root:b.root,key:r,value:n},E=await Xn.create(v,e);return e=await Yn(t,e,E.cid),{root:b.root,additions:[g,...b.additions],removals:b.removals,head:e,event:E}}let s=new Je(t),c=await zc(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 Sp(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 Zn(t,u,g.data.key,g.data.value):await Oc(t,u,g.data.key);u=b.root;for(let v of b.additions)i.putSync(v.cid,v.bytes),d.set(v.cid.toString(),v);for(let v of b.removals)m.set(v.cid.toString(),v)}let f=await Zn(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 Xn.create(h,e);i.putSync(p.cid,p.bytes),e=await Yn(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 Kr(t,e){if(!e.length)throw new Error("cannot determine root of headless clock");let r=new _e;t=new Ot(r,t);let n=new Je(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 zc(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 Sp(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 Zn(t,s,d.data.key,d.data.value):await Oc(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 Ep(t,e,r){if(!e.length)return;let n=await Kr(t,e);return n.additions.length&&(t=new Ot(new _e(n.additions),t)),xp(t,n.root,r)}async function*Rc(t,e,r){if(!e.length)return;let n=await Kr(t,e);n.additions.length&&(t=new Ot(new _e(n.additions),t)),yield*kp(t,n.root,r)}async function zc(t,e){if(!e.length)return;let r=e.map(n=>[n]);for(;;){let n=!1;for(let o of r){let i=await Dx(t,o[o.length-1]);if(!i)continue;n=!0,o.push(i);let s=Nx(r);if(s)return s}if(!n)return}}async function Dx(t,e){let{value:r}=await t.get(e);return r.parents.length?r.parents.length===1?r.parents[0]:zc(t,r.parents):e}function Nx(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 Sp(t,e,r){if(e.length===1&&String(e[0])===String(r))return[];let n=new Map,o=await Promise.all(e.map(s=>Ap(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 Ap(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=>Ap(t,a,r,n+1)));return i.concat(...c)}var en={};Q(en,{DEFAULT_DIRECTORY_MODE:()=>Uy,DEFAULT_FILE_MODE:()=>Ny,NodeType:()=>F,code:()=>Yr,createAdvancedFile:()=>rk,createComplexFile:()=>ok,createDirectoryShard:()=>Oy,createEmptyFile:()=>ek,createFileChunk:()=>tk,createFileShard:()=>nk,createFlatDirectory:()=>cs,createRaw:()=>Py,createShardedDirectory:()=>My,createSimpleFile:()=>Fy,createSymlink:()=>zy,cumulativeContentByteLength:()=>tt,cumulativeDagByteLength:()=>Zr,decode:()=>jy,decodeMetadata:()=>lr,encode:()=>Hy,encodeAdvancedFile:()=>cu,encodeComplexFile:()=>uu,encodeDirectory:()=>fs,encodeDirectoryMetadata:()=>hu,encodeFile:()=>Ry,encodeFileChunk:()=>au,encodeFileShard:()=>ik,encodeHAMTShard:()=>lu,encodeLink:()=>us,encodeMetadata:()=>io,encodeMode:()=>qy,encodeRaw:()=>su,encodeSimpleFile:()=>ls,encodeSymlink:()=>$y,filesize:()=>uk,matchFile:()=>ck,name:()=>iu});var Ux=new TextDecoder;function $c(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 Xi(t,e){let r;[r,e]=$c(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 _p(t,e){let r;return[r,e]=$c(t,e),[r&7,r>>3,e]}function Px(t){let e={},r=t.length,n=0;for(;n<r;){let o,i;if([o,i,n]=_p(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]=Xi(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]=Xi(t,n),e.Name=Ux.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]=$c(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 Bp(t){let e=t.length,r=0,n,o=!1,i;for(;r<e;){let c,a;if([c,a,r]=_p(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]=Xi(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]=Xi(t,r),n.push(Px(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 Tp=new TextEncoder,Cp=2**32,Fx=2**31;function Mx(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=eo(e,r,t.Tsize)-1,e[r]=24}if(typeof t.Name=="string"){let n=Tp.encode(t.Name);r-=n.length,e.set(n,r),r=eo(e,r,n.length)-1,e[r]=18}return t.Hash&&(r-=t.Hash.length,e.set(t.Hash,r),r=eo(e,r,t.Hash.length)-1,e[r]=10),e.length-r}function Ip(t){let e=Rx(t),r=new Uint8Array(e),n=e;if(t.Data&&(n-=t.Data.length,r.set(t.Data,n),n=eo(r,n,t.Data.length)-1,r[n]=10),t.Links)for(let o=t.Links.length-1;o>=0;o--){let i=Mx(t.Links[o],r.subarray(0,n));n-=i,n=eo(r,n,i)-1,r[n]=18}return r}function Ox(t){let e=0;if(t.Hash){let r=t.Hash.length;e+=1+r+Gr(r)}if(typeof t.Name=="string"){let r=Tp.encode(t.Name).length;e+=1+r+Gr(r)}return typeof t.Tsize=="number"&&(e+=1+Gr(t.Tsize)),e}function Rx(t){let e=0;if(t.Data){let r=t.Data.length;e+=1+r+Gr(r)}if(t.Links)for(let r of t.Links){let n=Ox(r);e+=1+n+Gr(n)}return e}function eo(t,e,r){e-=Gr(r);let n=e;for(;r>=Fx;)t[e++]=r&127|128,r/=128;for(;r>=128;)t[e++]=r&127|128,r>>>=7;return t[e]=r,n}function Gr(t){return t%2===0&&t++,Math.floor((zx(t)+6)/7)}function zx(t){let e=0;return t>=Cp&&(t=Math.floor(t/Cp),e=32),t>=65536&&(t>>>=16,e+=16),t>=256&&(t>>>=8,e+=8),e+$x[t]}var $x=[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 Hx=["Data","Links"],jx=["Hash","Name","Tsize"],Hc=new TextEncoder;function Dp(t,e){if(t===e)return 0;let r=t.Name?Hc.encode(t.Name):[],n=e.Name?Hc.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 Lp(t,e){return!Object.keys(t).some(r=>!e.includes(r))}function Vx(t){if(typeof t.asCID=="object"){let r=j.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=j.asCID(t.Hash);try{r||(typeof t.Hash=="string"?r=j.parse(t.Hash):t.Hash instanceof Uint8Array&&(r=j.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 jc(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=Hc.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(Vx),e.Links.sort(Dp);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Np(t){if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form");if(!Lp(t,Hx))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(!Lp(r,jx))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&&Dp(r,t.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}var ar=112;function Up(t){Np(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),Ip(e)}function Ye(t){let e=Bp(t),r={};return e.Data&&(r.Data=e.Data),e.Links&&(r.Links=e.Links.map(n=>{let o={};try{o.Hash=j.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 ft=W(Ty(),1),Jr=ft.default.Reader,nu=ft.default.Writer,N=ft.default.util,ie=ft.default.roots.unixfs||(ft.default.roots.unixfs={}),Xr=ie.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=N.newBuffer([]),t.prototype.filesize=N.Long?N.Long.fromBits(0,0,!0):0,t.prototype.blocksizes=N.emptyArray,t.prototype.hashType=N.Long?N.Long.fromBits(0,0,!0):0,t.prototype.fanout=N.Long?N.Long.fromBits(0,0,!0):0,t.prototype.mode=0,t.prototype.mtime=null,t.encode=function(r,n){if(n||(n=nu.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")&&ie.UnixTime.encode(r.mtime,n.uint32(66).fork()).ldelim(),n},t.decode=function(r,n){r instanceof Jr||(r=Jr.create(r));for(var o=n===void 0?r.len:r.pos+n,i=new ie.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=ie.UnixTime.decode(r,r.uint32());break;default:r.skipType(s&7);break}}if(!i.hasOwnProperty("Type"))throw N.ProtocolError("missing required 'Type'",{instance:i});return i},t.fromObject=function(r){if(r instanceof ie.Data)return r;var n=new ie.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"?N.base64.decode(r.Data,n.Data=N.newBuffer(N.base64.length(r.Data)),0):r.Data.length&&(n.Data=r.Data)),r.filesize!=null&&(N.Long?(n.filesize=N.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 N.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)N.Long?(n.blocksizes[o]=N.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 N.LongBits(r.blocksizes[o].low>>>0,r.blocksizes[o].high>>>0).toNumber(!0))}if(r.hashType!=null&&(N.Long?(n.hashType=N.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 N.LongBits(r.hashType.low>>>0,r.hashType.high>>>0).toNumber(!0))),r.fanout!=null&&(N.Long?(n.fanout=N.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 N.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=ie.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=N.newBuffer(o.Data))),N.Long){var i=new N.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(N.Long){var i=new N.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(N.Long){var i=new N.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?ie.Data.DataType[r.Type]:r.Type),r.Data!=null&&r.hasOwnProperty("Data")&&(o.Data=n.bytes===String?N.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?N.Long.prototype.toString.call(r.filesize):n.longs===Number?new N.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?N.Long.prototype.toString.call(r.blocksizes[s]):n.longs===Number?new N.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?N.Long.prototype.toString.call(r.hashType):n.longs===Number?new N.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?N.Long.prototype.toString.call(r.fanout):n.longs===Number?new N.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=ie.UnixTime.toObject(r.mtime,n)),o},t.prototype.toJSON=function(){return this.constructor.toObject(this,ft.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})(),m3=ie.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=N.Long?N.Long.fromBits(0,0,!1):0,t.prototype.FractionalNanoseconds=0,t.encode=function(r,n){return n||(n=nu.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 Jr||(r=Jr.create(r));for(var o=n===void 0?r.len:r.pos+n,i=new ie.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 N.ProtocolError("missing required 'Seconds'",{instance:i});return i},t.fromObject=function(r){if(r instanceof ie.UnixTime)return r;var n=new ie.UnixTime;return r.Seconds!=null&&(N.Long?(n.Seconds=N.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 N.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(N.Long){var i=new N.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?N.Long.prototype.toString.call(r.Seconds):n.longs===Number?new N.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,ft.default.util.toJSONOptions)},t})(),g3=ie.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=nu.create()),r.MimeType!=null&&Object.hasOwnProperty.call(r,"MimeType")&&n.uint32(10).string(r.MimeType),n},t.decode=function(r,n){r instanceof Jr||(r=Jr.create(r));for(var o=n===void 0?r.len:r.pos+n,i=new ie.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 ie.Metadata)return r;var n=new ie.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,ft.default.util.toJSONOptions)},t})();var F=Xr.DataType;var Dy=Object.freeze([]),ou=new Uint8Array(0),Ee=Object.freeze({}),Ny=parseInt("0644",8),Uy=parseInt("0755",8),Yr=ar,iu="UnixFS",Tt=(t,e)=>(Object(globalThis).debug&&console.log({data:t,links:e}),Up(jc({Data:Xr.encode(t).finish(),Links:e}))),Py=t=>({type:F.Raw,content:t}),ek=t=>Fy(ou,t),Fy=(t,e)=>({type:F.File,layout:"simple",content:t,metadata:lr(e)}),tk=t=>({type:F.File,layout:"simple",content:t}),rk=(t,e)=>({type:F.File,layout:"advanced",parts:t,metadata:lr(e)}),nk=t=>({type:F.File,layout:"advanced",parts:t}),ok=(t,e,r)=>({type:F.File,layout:"complex",content:t,parts:e,metadata:lr(r)}),cs=(t,e)=>({type:F.Directory,metadata:lr(e),entries:t}),My=(t,e,r,n,o=Ee)=>({type:F.HAMTShard,bitfield:e,fanout:fu(r),hashType:du(n),entries:t,metadata:lr(o)}),Oy=(t,e,r,n)=>({type:F.HAMTShard,bitfield:e,fanout:fu(r),hashType:du(n),entries:t}),su=t=>Tt({Type:F.Raw,Data:t.byteLength>0?t:void 0,filesize:t.byteLength,blocksizes:Dy},[]),Ry=(t,e=!1)=>{let r=e?Ee:Object(t).metadata;switch(t.layout){case"simple":return ls(t.content,r);case"advanced":return cu(t.parts,r);case"complex":return uu(t.content,t.parts,r);default:throw new TypeError(`File with unknown layout "${Object(t).layout}" was passed`)}},au=t=>ls(t,Ee),ik=t=>Tt({Type:F.File,blocksizes:t.map(oo),filesize:tt(t)},t.map(us)),cu=(t,e=Ee)=>Tt({Type:F.File,blocksizes:t.map(oo),filesize:tt(t),...io(e)},t.map(us)),us=t=>({Name:"",Tsize:t.dagByteLength,Hash:t.cid}),ls=(t,e=Ee)=>Tt({Type:F.File,Data:t.byteLength>0?t:void 0,filesize:t.byteLength,blocksizes:[],...io(e)},[]),uu=(t,e,r=Ee)=>Tt({Type:F.File,Data:t,filesize:t.byteLength+tt(e),blocksizes:e.map(oo)},e.map(us)),fs=t=>Tt({Type:t.type,...hu(t.metadata||Ee)},t.entries.map(Vy)),lu=({bitfield:t,fanout:e,hashType:r,entries:n,metadata:o=Ee})=>Tt({Type:F.HAMTShard,Data:t.byteLength>0?t:void 0,fanout:fu(e),hashType:du(r),...hu(o)},n.map(Vy)),fu=t=>{if(Math.log2(t)%1===0)return t;throw new TypeError(`Expected hamt size to be a power of two instead got ${t}`)},du=t=>{if(Number.isInteger(t))return t;throw new TypeError(`Expected an integer value instead got ${t}`)};var zy=(t,e=Ee)=>({type:F.Symlink,content:t,metadata:lr(e)}),$y=(t,e=!1)=>{let r=e?Ee:Object(t).metadata;return Tt({Type:F.Symlink,Data:t.content,...io(r||Ee)},[])},Hy=(t,e=!0)=>{switch(t.type){case F.Raw:return su(t.content);case F.File:return Ry(t);case F.Directory:return fs(t);case F.HAMTShard:return lu(t);case F.Symlink:return $y(t);default:throw new Error(`Unknown node type ${Object(t).type}`)}},jy=t=>{let e=Ye(t),r=Xr.decode(e.Data),{Type:n,Data:o,mtime:i,mode:s,blocksizes:c,...a}=Xr.toObject(r,{defaults:!1,arrays:!0,longs:Number,objects:!1}),u={...s&&{mode:s},...sk(i)},l=e.Links;switch(r.Type){case F.Raw:return Py(o);case F.File:return l.length===0?new is(o,u):o.byteLength===0?new ss(Iy(a.blocksizes,l),u):new as(o,Iy(a.blocksizes,l),u);case F.Directory:return cs(Ly(l),u);case F.HAMTShard:return My(Ly(l),o||ou,a.fanout,a.hashType,u);case F.Symlink:return zy(o,u);default:throw new TypeError(`Unsupported node type ${r.Type}`)}},sk=t=>t==null?void 0:{mtime:{secs:t.Seconds,nsecs:t.FractionalNanoseconds||0}};var Iy=(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},Ly=t=>t.map(e=>({cid:e.Hash,name:e.Name||"",dagByteLength:e.Tsize||0})),tt=t=>t.reduce((e,r)=>e+r.contentByteLength,0),Zr=(t,e)=>e.reduce((r,n)=>r+n.dagByteLength,t.byteLength),oo=t=>t.contentByteLength,Vy=({name:t,dagByteLength:e,cid:r})=>({Name:t,Tsize:e,Hash:r}),hu=t=>io(t,Uy),io=({mode:t,mtime:e},r=Ny)=>({mode:t!=null?qy(t,r):void 0,mtime:e!=null?ak(e):void 0}),lr=t=>t==null?Ee:{...t.mode==null?void 0:{mode:Wy(t.mode)},...t.mtime==null?void 0:{mtime:t.mtime}},ak=t=>t==null?void 0:t.nsecs!==0?{Seconds:t.secs,FractionalNanoseconds:t.nsecs}:{Seconds:t.secs},qy=(t,e)=>{let r=t==null?void 0:Wy(t);return r===e||r==null?void 0:r},Wy=t=>t&4095|t&4294963200,ck=({content:t=ou,parts:e=Dy,metadata:r=Ee,...n})=>e.length===0?new is(t,r):t.byteLength===0?new ss(e,r):new as(t,e,r),is=class{constructor(e,r){this.content=e,this.metadata=r,this.layout="simple",this.type=F.File}get filesize(){return this.content.byteLength}encode(){return ls(this.content,this.metadata)}},ss=class{constructor(e,r){this.parts=e,this.metadata=r}get layout(){return"advanced"}get type(){return F.File}get fileSize(){return tt(this.parts)}get blockSizes(){return this.parts.map(oo)}encode(){return cu(this.parts,this.metadata)}},as=class{constructor(e,r,n){this.content=e,this.parts=r,this.metadata=n}get layout(){return"complex"}get type(){return F.File}get fileSize(){return this.content.byteLength+tt(this.parts)}get blockSizes(){return this.parts.map(oo)}encode(){return uu(this.content,this.parts,this.metadata)}},uk=t=>{switch(t.type){case F.Raw:case F.Symlink:return t.content.byteLength;case F.File:switch(t.layout){case"simple":return t.content.byteLength;case"advanced":return tt(t.parts);case"complex":return t.content.byteLength+tt(t.parts)}default:return 0}};var lk=function*(t){let e=yield*t;yield*hs(e)};function*wu(){return yield ms}var rn=function*(){yield gs};var ds=function*(t){let e=yield*wu();if(dk(t)){let r=!1,n;if(t.then(o=>{r=!1,n=o,It(e)},o=>{r=!0,n=o,It(e)}),yield*rn(),r)throw n;return n}else return mk(fk(e)),yield*rn(),t};function*fk(t){It(t)}var dk=t=>t!=null&&typeof t.then=="function",hs=function*(t){yield t},ps=function*(t){let e=[];for(let r of Object.entries(t)){let[n,o]=r;o!==co&&e.push(yield*on(pk(o,n)))}yield*xu(e)},ys=t=>t.length>0?hk(t.map(lk)):co;function*hk(t){let e=[];for(let r of t)e.push(yield*on(r));yield*xu(e)}var pk=(t,e)=>t===co?co:t instanceof so?new so([...t.tags,e],t.source):new so([e],t),so=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 gs:case ms:return e;default:{let r=e,{value:n}=r;for(let o of this.tags)n=yk(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"}},uo=()=>co;var yk=(t,e)=>({type:t,[t]:e});var ms=Symbol("current"),gs=Symbol("suspend");var dt=class t{static of(e){return e.group||tn}static enqueue(e,r){e.group=r,r.stack.active.push(e)}constructor(e,r=[],n=new Set,o=new nn(r,n)){this.driver=e,this.parent=t.of(e),this.stack=o,this.id=++Jy}},pu=class{constructor(){this.status=ao,this.stack=new nn,this.id=0}},nn=class{constructor(e=[],r=new Set){this.active=e,this.idle=r}static size({active:e,idle:r}){return e.length+r.size}},mk=t=>It(t[Symbol.iterator]()),It=t=>{let e=dt.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(tn.status===ao)for(tn.status=Xy;;)try{for(let r of bu(tn));tn.status=ao;break}catch{tn.stack.active.shift()}},gk=t=>It(t),bu=function*(t){let{active:e}=t.stack,r=e[0];for(t.stack.idle.delete(r);r;){let n=Yy;e:for(;!n.done&&r===e[0];){let o=n.value;switch(o){case gs:t.stack.idle.add(r);break e;case ms:n=r.next(r);break;default:n=r.next(yield o);break}}e.shift(),r=e[0],t.stack.idle.delete(r)}};var on=(t,e)=>new gu(t,e),wk=(t,e)=>Gy(t,{ok:!0,value:e});var yu=(t,e)=>Gy(t,{ok:!1,error:e});function*Gy(t,e){try{let r=t,n=e.ok?r.return(e.value):r.throw(e.error);if(!n.done)if(n.value===gs){let{idle:o}=dt.of(r).stack;o.add(r)}else It(r)}catch{}}function*xu(t){if(t.length===0)return;let e=yield*wu(),r=new dt(e),n=null;for(let o of t){let{result:i}=o;if(i){!i.ok&&!n&&(n=i);continue}bk(o,r)}try{if(n)throw n.error;for(;yield*bu(r),nn.size(r.stack)>0;)yield*rn()}catch(o){for(let i of r.stack.active)yield*yu(i,o);for(let i of r.stack.idle)yield*yu(i,o),It(i);throw o}}var bk=(t,e)=>{let r=dt.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*ku(t){t.status===ao&&(yield*t),t.result||(yield*xu([t]));let e=t.result;if(e.ok)return e.value;throw e.error}var mu=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}},gu=class extends mu{constructor(e,r=xk,n={},o=Yy){super(n),this.id=++Jy,this.name=r.name||"",this.task=e,this.state=o,this.status=ao,this.result,this.handler=n,this.controller}*resume(){gk(this)}join(){return ku(this)}abort(e){return yu(this,e)}exit(e){return wk(this,e)}get[Symbol.toStringTag](){return"Fork"}*[Symbol.iterator](){return this.activate()}activate(){return this.controller=this.task[Symbol.iterator](),this.status=Xy,It(this),this}panic(e){this.result={ok:!1,error:e},this.status=Ky;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=Ky;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)}}},Qy=function*(t,e){let r=yield*wu(),n=new dt(r);for(dt.enqueue(t[Symbol.iterator](),n);;){for(let o of bu(n))dt.enqueue(e(o)[Symbol.iterator](),n);if(nn.size(n.stack)>0)yield*rn();else break}},Jy=0,ao="idle",Xy="active",Ky="finished",Yy={done:!1,value:ms},xk={},co=function*(){}(),tn=new pu;function vu(){}Object.defineProperties(vu,{prototype:{value:new Proxy(Object.prototype,{get(t,e,r){return typeof e=="symbol"?Reflect.get(t,e,r):r.get(e)}})}});var Eu=()=>new lo;var em=(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 Eu();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 lo(n,t.byteOffset+o,s)},kk=(t,e)=>e.byteLength>0?(t.segments.push(e),new lo(t.segments,t.byteOffset,t.byteLength+e.byteLength)):t,vk=(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}}},Ek=(t,e,r)=>{let n=r;for(let o of t.segments)e.set(o,n),n+=o.byteLength;return e};function*Sk(t){for(let e of t.segments)yield*e}var lo=class extends vu{constructor(e=[],r=0,n=0){super(),this.segments=e,this.byteLength=n,this.length=n,this.byteOffset=r}[Symbol.iterator](){return Sk(this)}slice(e,r){return em(this,e,r)}subarray(e,r){return em(this,e,r)}push(e){return kk(this,e)}get(e){return vk(this,e)}copyTo(e,r){return Ek(this,e,r)}};var fo=t=>{throw new Error(t)},tm=(t,e,...r)=>fo(String.raw(t,JSON.stringify(e),...r)),rm=new Uint8Array(0),nm=[];var om=t=>({config:t,buffer:Eu()}),im=(t,e)=>e.byteLength>0?am(t.config,t.buffer.push(e),!1):{...t,chunks:nm},sm=t=>am(t.config,t.buffer,!0),am=(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 cm=()=>({mutable:!0,needs:{},nodes:{},links:{},linked:_u});var Bu=(t,e)=>{let r=sn(e,{});for(let n of t){let{ready:o,has:i,wants:s}=lm(n.children,r.links);s.length===0?r=sn(r,{links:Au(void 0,i),linked:[{id:n.id,links:o}]}):r=sn(r,{needs:Au(n.id,s),nodes:{[n.id]:{children:n.children,count:s.length}}})}return r},um=(t,e,r)=>{let n=r.needs[t],o=r.nodes[n];if(o!=null)if(o.count===1){let{ready:i,has:s}=lm(o.children,{...r.links,[t]:e});return sn(r,{needs:{[t]:void 0},links:Au(void 0,s),nodes:{[n]:void 0},linked:[{id:n,links:i}]})}else return sn(r,{needs:{[t]:void 0},links:{[t]:e},nodes:{[n]:{...o,count:o.count-1}}});else return sn(r,{links:{[t]:e}})},sn=(t,{needs:e,nodes:r,links:n,linked:o})=>{let i=t.mutable?t:{...t},s=t.mutable?Ck:void 0;return e&&(i.needs=Su(t.needs,e,s)),r&&(i.nodes=Su(t.nodes,r,s)),n&&(i.links=Su(t.links,n,s)),i.linked=o?Bk(t.linked||_u,o,_u):t.linked||[],i},Au=(t,e)=>{let r={};for(let n of e)r[n]=t;return r},Su=(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 Bk=(t,e,r=t)=>{if(t===r)return[...t,...e];for(let n of e)t.push(n);return t},lm=(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}},_u=Object.freeze([]),Ck=Object.freeze({});var fm=(t,e)=>{switch(t.type){case"write":return Ik(e,t.bytes);case"link":return Lk(e,t.link);case"block":return{state:e,effect:uo()};case"close":return Dk(e);case"end":return{state:e,effect:uo()};default:return tm`File Writer got unknown message ${t}`}},dm=(t,e,r)=>({status:"open",metadata:e,config:r,writer:t,chunker:om({chunker:r.chunker}),layout:r.fileLayout.open(),nodeQueue:cm()}),Ik=(t,e)=>{if(t.status==="open"){let{chunks:r,...n}=im(t.chunker,e),{nodes:o,leaves:i,layout:s}=t.config.fileLayout.write(t.layout,r),{linked:c,...a}=Bu(o,t.nodeQueue),u=[...hm(i,t.config),...Cu(c,t.config)];return{state:{...t,chunker:n,layout:s,nodeQueue:a},effect:ps({link:ys(u)})}}else return fo("Unable to perform write on closed file")},Lk=(t,{id:e,link:r,block:n})=>{let{linked:o,...i}=um(e,r,t.nodeQueue),s=Cu(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():uo();return{state:c,effect:ps({link:ys(s),block:Pk(t.writer,n),end:a})}},Dk=t=>{if(t.status==="open"){let{chunks:e}=sm(t.chunker),{layout:r,...n}=t.config.fileLayout.write(t.layout,e),{root:o,...i}=t.config.fileLayout.close(r,t.metadata),[s,c]=Mk(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=[...hm(c,t.config),...Cu(a,t.config)],d=on(rn());return{state:{...t,chunker:null,layout:null,rootID:o.id,status:"closed",end:d,nodeQueue:u},effect:ps({link:ys(l),end:ku(d)})}}else return{state:t,effect:uo()}},hm=(t,e)=>t.map(r=>Nk(e,r,e.fileChunkEncoder)),Nk=function*({hasher:t,linker:e},{id:r,content:n},o){let i=o.encode(n?Fk(n):rm),s=yield*ds(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}},Cu=(t,e)=>t.map(r=>Uk(e,r)),Uk=function*(t,{id:e,links:r},n){let o=t.fileEncoder.encode({type:F.File,layout:"advanced",parts:r,metadata:n}),i=yield*ds(Promise.resolve(t.hasher.digest(o))),s=t.linker.createLink(t.fileEncoder.code,i),c={bytes:o,cid:s},a={cid:s,contentByteLength:tt(r),dagByteLength:Zr(o,r)};return{id:e,block:c,link:a}},Pk=function*(t,e){(t.desiredSize||0)<=0&&(yield*ds(t.ready)),t.write(e)},Fk=t=>t instanceof Uint8Array?t:t.copyTo(new Uint8Array(t.byteLength),0),Mk=t=>t.children==null;var Iu={};Q(Iu,{context:()=>Rk,cut:()=>ym,name:()=>pm,type:()=>zk,withMaxChunkSize:()=>Tu});var pm="fixed",Rk={maxChunkSize:262144},zk="Stateless",Tu=t=>({type:"Stateless",context:{maxChunkSize:t},name:pm,cut:ym}),ym=({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 ho=class{constructor(e,r,n){this.id=e,this.children=r,this.metadata=n}},ws=t=>({open:()=>Hk({width:t}),write:jk,close:Vk}),$k={width:174},Hk=({width:t}=$k)=>({width:t,head:null,leafIndex:[],nodeIndex:[],lastID:0}),jk=(t,e)=>{if(e.length===0)return{layout:t,nodes:pe,leaves:pe};{let{lastID:r}=t,[n,o]=t.head?[null,(e.unshift(t.head),e)]:e.length===1&&t.leafIndex.length===0?[e[0],pe]:[null,e];if(o.length===0)return{layout:{...t,head:n},nodes:pe,leaves:pe};{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?gm({...t,leafIndex:i,head:n,lastID:r},s):{layout:{...t,head:n,leafIndex:i,lastID:r},leaves:s,nodes:pe}}}},gm=(t,e=pe,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;){mm(i,1);let u=new ho(++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 ho(++o,u.splice(0,c));mm(i,a+1),i[a].push(l.id),r.push(l)}}return{layout:{...t,lastID:o,leafIndex:s,nodeIndex:i},leaves:e,nodes:r}},Vk=(t,e)=>{let r=t;if(t.head)return{root:{id:1,content:t.head,metadata:e},leaves:pe,nodes:pe};if(t.leafIndex.length===0)return{root:{id:1,metadata:e},leaves:pe,nodes:pe};{let{nodes:n,layout:o}=gm(r,pe,[],!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:pe}}else return{root:new ho(o.lastID+1,c,e),nodes:n,leaves:pe}}},mm=(t,e)=>{for(;t.length<e;)t.push([]);return t},pe=[];var Lt=()=>({chunker:Iu,fileChunkEncoder:Lu,smallFileEncoder:Lu,fileEncoder:en,fileLayout:ws(174),hasher:ut,linker:{createLink:j.createV1}}),Dt=t=>({...Lt(),...t}),Lu={code:Yr,name:iu,encode:au};var po=({writer:t,metadata:e={},settings:r=Lt()})=>new Du(dm(t,e,Dt(r))),wm=async(t,e)=>(await xm(t,hs({type:"write",bytes:e})),t),bm=async(t,{releaseLock:e=!1,closeWriter:r=!1}={})=>{await xm(t,hs({type:"close"}));let{state:n}=t;if(n.status==="linked")return r?await t.state.writer.close():e&&t.state.writer.releaseLock(),n.link;fo(`Expected writer to be in 'linked' state after close, but it is in "${n.status}" instead`)},xm=(t,e)=>on(Qy(e,r=>{let{state:n,effect:o}=fm(r,t.state);return t.state=n,o})),Du=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.config}write(e){return wm(this,e)}close(e){return bm(this,e)}};var Wk=Lt,Uu=({writer:t,settings:e=Wk(),metadata:r={}})=>new bs({writer:t,metadata:r,settings:e,entries:new Map,closed:!1}),xs=(t,e,r,{overwrite:n=!1}={})=>{let o=Pu(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},ks=(t,e)=>(Pu(t.state).entries.delete(e),t),Pu=t=>{if(t.closed)throw new Error("Can not change written directory, but you can .fork() and make changes to it");return t},km=async(t,{closeWriter:e=!1,releaseLock:r=!1}={})=>{let{writer:n,settings:o,metadata:i}=Pu(t.state);t.state.closed=!0;let s=[...vm(t)],c=cs(s,i),a=fs(c),u=await o.hasher.digest(a),l=o.linker.createLink(Yr,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:Zr(a,s)}},vm=function*({state:t}){for(let[e,{dagByteLength:r,cid:n}]of t.entries)yield{name:e,dagByteLength:r,cid:n}},Em=({state:t},{writer:e=t.writer,metadata:r=t.metadata,settings:n=t.settings}={})=>new bs({writer:e,metadata:r,settings:n,entries:new Map(t.entries.entries()),closed:!1}),bs=class{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.settings}links(){return vm(this)}set(e,r,n){return xs(this,e,r,n)}remove(e){return ks(this,e)}fork(e){return Em(this,e)}close(e){return km(this,e)}entries(){return this.state.entries.entries()}has(e){return this.state.entries.has(e)}get size(){return this.state.entries.size}};var Ss={};Q(Ss,{API:()=>vs,and:()=>e2,bitCount:()=>Es,empty:()=>Sm,from:()=>Gk,fromBytes:()=>n2,get:()=>Zk,or:()=>t2,popcount:()=>Fu,set:()=>Am,size:()=>Qk,toBytes:()=>r2,unset:()=>Yk});var vs={};var Sm=(t=32)=>{if(t!==32)throw new Error(`Uint32 BitField does not support size: ${t}`);return 0},Gk=(t,e)=>{let r=Sm(e);for(let n of t)r=Am(r,n);return r},Qk=t=>32,Jk=(t,e)=>t>>>e&31,Xk=(t,e)=>1<<Jk(t,e),Fu=(t,e=31)=>Es(t&Xk(e,0)-1),Am=(t,e)=>t|1<<e,Yk=(t,e)=>t&(255^1<<e),Zk=(t,e)=>(t>>e&1)!==0,Es=t=>{let e=t-(t>>1&1431655765),r=(e&858993459)+(e>>2&858993459);return(r+(r>>4)&252645135)*16843009>>24},e2=(t,e)=>t&e,t2=(t,e)=>t|e,r2=t=>Uint8Array.of(t>>24&255,t>>16&255,t>>8&255,t&255),n2=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 Cm=W(Mu(),1),o2=new TextEncoder,i2=Cm.default.x64.hash126,Tm=({bitWidth:t=5,hash:e=i2})=>{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(o2.encode(s)),size:Math.ceil(4*8/t)}};var an=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 mo(this.config)}lookup(e,r,n,o){return Lm(this,e,r,n,o)}associate(e,r,n,o,i,s){return zu(this,e,r,n,o,i,s)}dissociate(e,r,n,o,i){return Dm(this,e,r,n,o,i)}fork(e=null){return go(this,e)}entries(){return Nm(this)}keys(){return Um(this)}values(){return Pm(this)}},_s=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 s2(this,n,o)}associate(e,r,n,o,i,s){return a2(this,e,n,o,i,s)}dissociate(e,r,n,o,i){return c2(this,e,n,o,i)}fork(e=null){return u2(this,e)}entries(){return Nm(this)}keys(){return Um(this)}values(){return Pm(this)}},s2=(t,e,r)=>{let{children:n,count:o}=t,i=Ou(n,o,e);return n[i]===e?n[i+1]:r},a2=(t,e,r,n,o,i)=>{let{children:s,count:c}=t,a=Ou(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},c2=(t,e,r,n,o)=>{let{children:i,count:s,config:c}=t,a=Ou(i,s,n);if(i[a]!==n)return t;if(o.value=!0,s===2){let u=a===0?2:0;return zu(mo(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}},u2=(t,e=null)=>Rm(t.edit,e)?t:new _s(e,t.count,t.children.slice(),t.config),Ou=(t,e,r)=>{let n=0;for(;n<e&&t[n]>r;)n+=2;return n};var mo=(t,e=null)=>new an(e,t.BitField.empty(Math.pow(2,t.bitWidth)),t.BitField.empty(Math.pow(2,t.bitWidth)),[],t),Cs=(t,e,r)=>Lm(t,0,t.config.Path.from(e),e,r),Lm=(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 Ts(t,d)===n?Bs(t,d):o}else return u.get(s,l)?Is(t,l).lookup(e+1,r,n,o):o},Ru=(t,e,r,n,o)=>zu(t,e,0,t.config.Path.from(r),r,n,o),zu=(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=Ts(t,f);if(o===h)return Bs(t,f)===i?t:l2(t,e,f,i);{let p=Mm(u,e,r+1,l.from(h),h,Bs(t,f),n,o,i);return s.value=!0,d2(t,e,m,p)}}else if(d.get(a,m)){let f=Is(t,m),h=f.associate(e,r+1,n,o,i,s);return f===h?t:Fm(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(wo(f),0,o,i),h}},$u=(t,e,r,n)=>Dm(t,e,0,t.config.Path.from(r),r,n);var Dm=(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===Ts(t,m)){i.value=!0;let f=go(t,e);return f.datamap=u.unset(t.datamap,d),f.children.splice(wo(m),2),f}else return t}else if(u.get(c,d)){let m=Is(t,d),f=m.dissociate(e,r+1,n,o,i);return h2(f)?p2(t)?f:f2(t,e,d,f):m===f?t:Fm(t,e,d,f)}else return t},Nm=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},go=(t,e)=>Rm(t.edit,e)?t:new an(e,t.datamap,t.nodemap,t.children.slice(),t.config),Um=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},Pm=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},l2=(t,e,r,n)=>{let o=t.fork(e);return o.children[Om(r)]=n,o},f2=(t,e,r,n)=>{let{datamap:o,nodemap:i,config:s}=t,{BitField:c}=s,a=go(t,e);return a.children.splice(Ls(t,r),1),a.children.splice(wo(c.popcount(o,r)),0,n.children[0],n.children[1]),a.datamap=c.set(o,r),a.nodemap=c.unset(i,r),a},Fm=(t,e,r,n)=>{let o=go(t,e);return o.children[Ls(t,r)]=n,o},d2=(t,e,r,n)=>{let{nodemap:o,datamap:i,config:s}=t,{BitField:c}=s,a=c.popcount(i,r),u=wo(a),l=Ls(t,r),d=go(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},Mm=(t,e,r,n,o,i,s,c,a)=>{let{BitField:u,Path:l}=t;if(l.size<r)return new _s(e,2,[o,i,c,a],t);{let d=l.at(n,r),m=l.at(s,r);return d===m?new an(e,u.empty(Math.pow(2,t.bitWidth)),u.from([d],Math.pow(2,t.bitWidth)),[Mm(t,e,r+1,n,o,i,s,c,a)],t):new an(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)}},Ts=({children:t},e)=>t[wo(e)],wo=t=>t*2,Bs=({children:t},e)=>t[Om(e)],Om=t=>t*2+1,Is=(t,e)=>t.children[Ls(t,e)],Ls=({children:t,nodemap:e,config:r},n)=>t.length-1-r.BitField.popcount(e,n),Rm=(t,e)=>t!=null&&t===e,h2=t=>t.nodeArity===0&&t.dataArity===1,p2=({config:{BitField:t},datamap:e,nodemap:r})=>t.popcount(e)===0&&t.popcount(r)===1;var Ds=W(Mu(),1);function y2(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 K3=Kt({name:"murmur3-32",code:35,encode:t=>y2(Ds.default.x86.hash32(t))}),$m=Kt({name:"murmur3-128",code:34,encode:t=>Ht.fromHex(Ds.default.x64.hash128(t))}),bo=Kt({name:"murmur3-x64-64",code:34,encode:t=>Ht.fromHex(Ds.default.x64.hash128(t)).subarray(0,8)});var m2=new TextEncoder,g2=t=>bo.encode(t),Hm=({bitWidth:t=8,hash:e=g2}={})=>{let r=e(new Uint8Array).byteLength;return{from:i=>e(m2.encode(i)),at:(i,s)=>{let c=s*t;if(c>r)throw new RangeError("Out of bounds");return Hu(i,c,t)},size:Math.ceil(r*8/t)}},Hu=(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 ju={};Q(ju,{API:()=>vs,and:()=>C2,empty:()=>jm,from:()=>b2,fromBytes:()=>A2,get:()=>E2,or:()=>B2,popcount:()=>_2,set:()=>k2,size:()=>x2,toBytes:()=>S2,unset:()=>v2});var jm=(t=256)=>{if(t%8!==0)throw new Error("Must be multiple of 8");return new Uint8Array(t/8)},b2=(t,e)=>{let r=jm(e);for(let n of t){let{byte:o,byteOffset:i,bitOffset:s}=xo(r,n);r[i]=o|1<<s}return r},x2=t=>t.byteLength*8,xo=(t,e)=>{let r=t.byteLength-1-(e/8|0),n=e%8;return{byte:t[r],byteOffset:r,bitOffset:n}},Vm=(t,e,r)=>{if(t[e]!==r){let n=t.slice(0);return n[e]=r,n}return t},k2=(t,e)=>{let{byte:r,byteOffset:n,bitOffset:o}=xo(t,e);return Vm(t,n,r|1<<o)},v2=(t,e)=>{let{byte:r,byteOffset:n,bitOffset:o}=xo(t,e);return Vm(t,n,r&(255^1<<o))},E2=(t,e)=>{var{byte:r,bitOffset:n}=xo(t,e);return(r>>n&1)!==0},S2=t=>t,A2=t=>t,_2=(t,e=t.byteLength*8)=>{let{byteOffset:r,bitOffset:n,byte:o}=xo(t,e),i=Fu(o,n),s=t.byteLength-1;for(;s>r;){let c=t[s];i+=Es(c),s--}return i},B2=(t,e)=>{let r=t.slice(),n=0;for(;n<t.length;)r[n]|=e[n],n++;return r},C2=(t,e)=>{let r=t.slice(),n=0;for(;n<t.length;)r[n]&=e[n],n++;return r};var qm=new RangeError("Not Found");var T2=({bitWidth:t=5,BitField:e=t===5?Ss:ju,Path:r=t===5?Tm({bitWidth:t}):Hm({bitWidth:t})}={})=>({bitWidth:t,BitField:e,Path:r});var qu=(t,e)=>Cs(t.root,e,qm)!==qm,Wm=(t,e,r=void 0)=>Cs(t.root,e,r),Km=t=>{let e={},r=T2(t);return new Ns(e,0,mo(r,e),r)},Vu=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,mo(this.config,null),this.config)}has(e){return qu(this,e)}get(e){return Cs(this.root,e,void 0)}set(e,r){let n={value:!1},o=Ru(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=$u(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 Ns({},this.count,this.root,this.config)}},Ns=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=Ru(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=$u(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 Vu(this.count,this.root,this.config);throw new Error(".build was called on the finalized builder")}};var I2=new TextEncoder,L2=t=>bo.encode(t),Qm=({bitWidth:t=8,hash:e=L2})=>{let r=e(new Uint8Array).byteLength,n={bitWidth:t,hash:e,hashSize:r};return{at:(s,c)=>D2(s,c,n),from:s=>I2.encode(s),size:1/0}},D2=(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:N2(t,u)),d=i<=a?a%i:a,m=i-d,f=m<c?m:c;s=(s<<f)+Hu(l,d,f),c-=f,a+=f}return s},N2=(t,e)=>{let r=new Uint8Array(t.byteLength+1).fill(e,t.byteLength);return r.set(t),r};var Jm=8,P2={bitWidth:Jm,Path:Qm({bitWidth:Jm})};var Wu=(t=P2)=>Km(t);var Xm=class extends Map{constructor(e=Wu()){super(),this.builder=e}clear(){this.builder=Wu()}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 Wm(this.builder,e)}has(e){return qu(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 Ym=({writable:t,settings:e=Lt()})=>new Ku({writer:t.getWriter(),settings:e}),M2=async(t,{releaseLock:e=!0,closeWriter:r=!0}={})=>(r?await t.writer.close():e&&t.writer.releaseLock(),t),Ku=class{constructor({writer:e,settings:r}){this.writer=e,this.settings=Dt(r)}createFileWriter({settings:e=this.settings,metadata:r}={}){return po({writer:this.writer,settings:e,metadata:r})}createDirectoryWriter({settings:e=this.settings,metadata:r}={}){return Uu({writer:this.writer,settings:e,metadata:r})}close(e){return M2(this,e)}},O2=1048576,R2=O2*100,Zm=(t=R2)=>({highWaterMark:t,size:e=>e.bytes.length});var Xs=W(rt(),1);function H2(t){return t[Symbol.asyncIterator]!=null}function j2(t){if(H2(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 rg=j2;var ow=W(rt(),1);var ng=0,V2="identity",og=Te,q2=t=>jt(ng,og(t)),ig={code:ng,name:V2,encode:og,digest:q2};var sg=W(rt(),1);var W2=async(t,e,r,n,o,i,s,c)=>{let a=await s.get(t,c),u=Ir(a),l=u,d=r;for(;n.length>0;){let m=n[0];if(m in l){n.shift(),d=`${d}/${m}`;let f=V.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,sg.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}}}},ag=W2;var cg=W(rt(),1);var ce=class extends Event{constructor(e,r){super(e),this.detail=r}};function K2(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 fr=K2;var ko=W(rt(),1),G2=(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,ko.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(o>n)throw(0,ko.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(i<0n)throw(0,ko.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,ko.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:o,end:i}},cn=G2;var Q2=t=>{async function*e(r={}){let{start:n,end:o}=cn(t.length,r.offset,r.length),i=fr(t,0n,n,o);r.onProgress?.(new ce("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,cg.default)(new Error(`No link named ${r} found in raw node ${t}`),"ERR_NOT_FOUND");let a=ti(t.multihash.bytes);return{entry:{type:"identity",name:e,path:r,cid:t,content:Q2(a.digest),depth:i,size:BigInt(a.digest.length),node:a.digest}}},ug=J2;var lg=W(rt(),1);var X2=t=>{async function*e(r={}){let{start:n,end:o}=cn(t.length,r.offset,r.length),i=fr(t,0n,n,o);r.onProgress?.(new ce("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(t.byteLength)})),yield i}return e},Y2=async(t,e,r,n,o,i,s,c)=>{if(n.length>0)throw(0,lg.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:X2(a),depth:i,size:BigInt(a.length),node:a}}},fg=Y2;var Uo=W(rt(),1);var Zu=W(rt(),1);var Gu=W(os(),1),dg=W(tu(),1),hg=W(lt(),1),Qu=W(rs(),1),pg=W(Yc(),1);function Z2(){hg.default._configure(),Gu.default._configure(dg.default),Qu.default._configure(pg.default)}Z2();var yg=["uint64","int64","sint64","fixed64","sfixed64"];function ev(t){for(let e of yg){if(t[e]==null)continue;let r=t[e];t[e]=function(){return BigInt(r.call(this).toString())}}return t}function Ju(t){return ev(new Gu.default(t))}function tv(t){for(let e of yg){if(t[e]==null)continue;let r=t[e];t[e]=function(n){return r.call(this,n.toString())}}return t}function Xu(){return tv(Qu.default.create())}function vo(t,e){let r=Ju(t instanceof Uint8Array?t:t.subarray());return e.decode(r)}function Eo(t,e){let r=Xu();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var un;(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"})(un||(un={}));function Us(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function Yu(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 Us("enum",un.VARINT,r,n)}function So(t,e){return Us("message",un.LENGTH_DELIMITED,t,e)}var ze;(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=()=>Yu(r)}(e=t.DataType||(t.DataType={}));let n;t.codec=()=>(n==null&&(n=So((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),Ps.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=Ps.codec().decode(o,o.uint32());break;default:o.skipType(a&7);break}}return s})),n),t.encode=o=>Eo(o,t.codec()),t.decode=o=>vo(o,t.codec())})(ze||(ze={}));var Ps;(function(t){let e;t.codec=()=>(e==null&&(e=So((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=>Eo(r,t.codec()),t.decode=r=>vo(r,t.codec())})(Ps||(Ps={}));var mg;(function(t){let e;t.codec=()=>(e==null&&(e=So((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=>Eo(r,t.codec()),t.decode=r=>vo(r,t.codec())})(mg||(mg={}));var gg={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},rv=["directory","hamt-sharded-directory"],wg=parseInt("0644",8),bg=parseInt("0755",8),ln=class t{constructor(e={type:"file"}){k(this,"type");k(this,"data");k(this,"blockSizes");k(this,"hashType");k(this,"fanout");k(this,"mtime");k(this,"_mode");k(this,"_originalMode");let{type:r,data:n,blockSizes:o,hashType:i,fanout:s,mtime:c,mode:a}=e;if(r!=null&&!Object.values(gg).includes(r))throw(0,Zu.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}static unmarshal(e){let r=ze.decode(e),n=new t({type:gg[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}set mode(e){e==null?this._mode=this.isDirectory()?bg:wg:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return rv.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=ze.DataType.Raw;break;case"directory":e=ze.DataType.Directory;break;case"file":e=ze.DataType.File;break;case"metadata":e=ze.DataType.Metadata;break;case"symlink":e=ze.DataType.Symlink;break;case"hamt-sharded-directory":e=ze.DataType.HAMTShard;break;default:throw(0,Zu.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===wg&&!this.isDirectory()&&(n=void 0),n===bg&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),ze.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 Ig=W(vg(),1);var el={};Q(el,{identity:()=>sv});var sv=xr({prefix:"\0",name:"identity",encode:t=>Pl(t),decode:t=>Ul(t)});var tl={};Q(tl,{base2:()=>av});var av=G({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var rl={};Q(rl,{base8:()=>cv});var cv=G({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var nl={};Q(nl,{base10:()=>uv});var uv=yt({prefix:"9",name:"base10",alphabet:"0123456789"});var ol={};Q(ol,{base16:()=>lv,base16upper:()=>fv});var lv=G({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),fv=G({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var il={};Q(il,{base36:()=>dv,base36upper:()=>hv});var dv=yt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),hv=yt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var sl={};Q(sl,{base64:()=>pv,base64pad:()=>yv,base64url:()=>mv,base64urlpad:()=>gv});var pv=G({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),yv=G({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),mv=G({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),gv=G({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var al={};Q(al,{base256emoji:()=>vv});var Eg=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}"),wv=Eg.reduce((t,e,r)=>(t[r]=e,t),[]),bv=Eg.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function xv(t){return t.reduce((e,r)=>(e+=wv[r],e),"")}function kv(t){let e=[];for(let r of t){let n=bv[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var vv=xr({prefix:"\u{1F680}",name:"base256emoji",encode:xv,decode:kv});var cl={};Q(cl,{identity:()=>Av});var Sg=0,Ev="identity",Ag=ot,Sv=t=>Ft(Sg,Ag(t)),Av={code:Sg,name:Ev,encode:Ag,digest:Sv};var ET=new TextEncoder,ST=new TextDecoder;var ul={...el,...tl,...rl,...nl,...ol,...la,...il,...ua,...sl,...al},_T={...Pc,...cl};function fn(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Fs(t=0){return globalThis.Buffer?.allocUnsafe!=null?fn(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Bg(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var _g=Bg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ll=Bg("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=Fs(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Cv={utf8:_g,"utf-8":_g,hex:ul.base16,latin1:ll,ascii:ll,binary:ll,...ul},Cg=Cv;function Tg(t,e="utf8"){let r=Cg[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?fn(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var dr=class t{constructor(e,r,n=0){this._options=e,this._popCount=0,this._parent=r,this._posAtParent=n,this._children=new Ig.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 Lg(this,e,r)}toJSON(){return this.serialize(Iv,Lv)}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"?Tg(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(Tv);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 Tv(t){return!!t}function Iv(t,e){return t.key}function Lv(t){return t}async function Lg(t,e,r){let n=[];for(let o of t._children.compactArray())if(o instanceof dr)await Lg(o,e,r);else{let i=await e(o);n.push({bitField:t._children.bitField(),children:i})}return await r(n)}var Dv=[255,254,252,248,240,224,192,128],Nv=[1,3,7,15,31,63,127,255],Ms=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=Uv(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 Uv(t,e,r){let n=Pv(e,r);return(t&n)>>>e}function Pv(t,e){return Dv[t]&Nv[Math.min(e+t-1,7)]}function Dg(t,e){e==null&&(e=t.reduce((o,i)=>o+i.length,0));let r=Fs(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return fn(r)}function Ng(t){function e(r){return r instanceof Os?r:new Os(r,t)}return e}var Os=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?Dg([this._value,Uint8Array.from([this._depth])]):this._value,r=await this._hashFn(e),n=new Ms(r);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Ug(t){if(t==null||t.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:t.bits??8,hash:Ng(t.hashFn)};return new dr(e)}var Fv=async function(t){return(await $m.encode(t)).slice(0,8).reverse()},Mv=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 dr({hash:r._options.hash,bits:r._options.bits},e,o));return}await r.put(n.Name.substring(2),!0)}))},Pg=t=>t.toString(16).toUpperCase().padStart(2,"0").substring(0,2),Ov=t=>{let e=t.bucket,r=[];for(;e._parent!=null;)r.push(e),e=e._parent;return r.push(e),r.reverse()},Fg=async(t,e,r,n,o)=>{if(n==null){let l=Ug({hashFn:Fv});n={rootBucket:l,hamtDepth:1,lastBucket:l}}await Mv(t.Links,n.lastBucket,n.rootBucket);let i=await n.rootBucket._findNewBucketAndPos(e),s=Pg(i.pos),c=Ov(i);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],s=Pg(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=Ye(u),Fg(t,e,r,n,o)},Mg=Fg;function Rv(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 Rs=Rv;function zv(t){return t[Symbol.asyncIterator]!=null}function $v(t,e){if(zv(t))return async function*(){for await(let c of t)await e(c)&&(yield c)}();let r=Rs(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 Og=$v;function Hv(t){return t[Symbol.asyncIterator]!=null}function jv(t,e){if(Hv(t))return async function*(){for await(let c of t)yield e(c)}();let r=Rs(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 dn=jv;function ht(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var zs=globalThis.CustomEvent??Event;async function*hr(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=ht(),c=ht(),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=ht(),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 zs("task-complete"))},w=>{p.done=!0,p.err=w,o.dispatchEvent(new zs("task-complete"))})}a=!0,o.dispatchEvent(new zs("task-complete"))}catch(h){u=h,o.dispatchEvent(new zs("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=ht(),await c.promise),u!=null)throw u;if(n?yield*m():yield*f(),a&&i.length===0)break}}var $s=class{constructor(e){k(this,"buffer");k(this,"mask");k(this,"top");k(this,"btm");k(this,"next");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}},hn=class{constructor(e={}){k(this,"size");k(this,"hwm");k(this,"head");k(this,"tail");this.hwm=e.splitLimit??16,this.head=new $s(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 $s(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 fl=class extends Error{constructor(r,n){super(r??"The operation was aborted");k(this,"type");k(this,"code");this.type="aborted",this.code=n??"ABORT_ERR"}};function pn(t={}){return Vv(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 Vv(t,e){e=e??{};let r=e.onEnd,n=new hn,o,i,s,c=ht(),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(v){g(v)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{c.resolve(),c=ht()})}},u=w=>i!=null?i(w):(n.push(w),o),l=w=>(n=new hn,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 hn,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,v;g!=null&&(b=new Promise((E,T)=>{v=()=>{T(new fl)},g.addEventListener("abort",v)}));try{await Promise.race([c.promise,b])}finally{v!=null&&g!=null&&g?.removeEventListener("abort",v)}}},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 qv(t){return t[Symbol.asyncIterator]!=null}function Wv(...t){let e=[];for(let r of t)qv(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=pn({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 Rg=Wv;function yn(t,...e){if(t==null)throw new Error("Empty pipeline");if(dl(t)){let n=t;t=()=>n.source}else if($g(t)||zg(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&dl(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++)dl(r[n])&&(r[n]=Gv(r[n]));return Kv(...r)}var Kv=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},zg=t=>t?.[Symbol.asyncIterator]!=null,$g=t=>t?.[Symbol.iterator]!=null,dl=t=>t==null?!1:t.sink!=null&&t.source!=null,Gv=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=pn({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let o,i=t.source;if(zg(i))o=async function*(){yield*i,n.end()};else if($g(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Rg(n,o())}return t.source};var Qv=(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 ce("unixfs:exporter:walk:directory",{cid:t})),yield*yn(d,m=>dn(m,f=>async()=>{let h=f.Name??"",p=`${n}/${h}`;return(await o(f.Hash,h,p,[],i+1,s,a)).entry}),m=>hr(m,{ordered:!0}),m=>Og(m,f=>f!=null))}return c},Hg=Qv;var yr=W(rt(),1);var Zg=W(Vg(),1);var _o=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},pl=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},qg=t=>globalThis.DOMException===void 0?new pl(t):new DOMException(t),Wg=t=>{let e=t.reason===void 0?qg("This operation was aborted."):t.reason;return e instanceof Error?e:qg(e)};function yl(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(Wg(a)),a.addEventListener("abort",()=>{c(Wg(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 _o(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 ml(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 pr=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)},pt,Bo=class{constructor(){pt.set(this,[])}enqueue(e,r){r={priority:0,...r};let n={priority:r.priority,run:e};if(this.size&&pr(this,pt,"f")[this.size-1].priority>=r.priority){pr(this,pt,"f").push(n);return}let o=ml(pr(this,pt,"f"),n,(i,s)=>s.priority-i.priority);pr(this,pt,"f").splice(o,0,n)}dequeue(){let e=pr(this,pt,"f").shift();return e?.run}filter(e){return pr(this,pt,"f").filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return pr(this,pt,"f").length}};pt=new WeakMap;var K=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},L=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)},Y,To,Io,Ut,Gs,Lo,js,$e,Co,Se,Vs,Ae,Do,Nt,qs,Kg,Gg,Xg,Qg,Jg,Ws,gl,wl,Qs,Yg,Ks,Js=class extends Error{},No=class extends Zg.default{constructor(e){var r,n,o,i;if(super(),Y.add(this),To.set(this,void 0),Io.set(this,void 0),Ut.set(this,0),Gs.set(this,void 0),Lo.set(this,void 0),js.set(this,0),$e.set(this,void 0),Co.set(this,void 0),Se.set(this,void 0),Vs.set(this,void 0),Ae.set(this,0),Do.set(this,void 0),Nt.set(this,void 0),qs.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:Bo,...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})`);K(this,To,e.carryoverConcurrencyCount,"f"),K(this,Io,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),K(this,Gs,e.intervalCap,"f"),K(this,Lo,e.interval,"f"),K(this,Se,new e.queueClass,"f"),K(this,Vs,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,K(this,qs,e.throwOnTimeout===!0,"f"),K(this,Nt,e.autoStart===!1,"f")}get concurrency(){return L(this,Do,"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})`);K(this,Do,e,"f"),L(this,Y,"m",Qs).call(this)}async add(e,r={}){return r={timeout:this.timeout,throwOnTimeout:L(this,qs,"f"),...r},new Promise((n,o)=>{L(this,Se,"f").enqueue(async()=>{var i,s,c;K(this,Ae,(s=L(this,Ae,"f"),s++,s),"f"),K(this,Ut,(c=L(this,Ut,"f"),c++,c),"f");try{if(!((i=r.signal)===null||i===void 0)&&i.aborted)throw new Js("The task was aborted.");let a=e({signal:r.signal});r.timeout&&(a=yl(Promise.resolve(a),r.timeout)),r.signal&&(a=Promise.race([a,L(this,Y,"m",Yg).call(this,r.signal)]));let u=await a;n(u),this.emit("completed",u)}catch(a){if(a instanceof _o&&!r.throwOnTimeout){n();return}o(a),this.emit("error",a)}finally{L(this,Y,"m",Xg).call(this)}},r),this.emit("add"),L(this,Y,"m",Ws).call(this)})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return L(this,Nt,"f")?(K(this,Nt,!1,"f"),L(this,Y,"m",Qs).call(this),this):this}pause(){K(this,Nt,!0,"f")}clear(){K(this,Se,new(L(this,Vs,"f")),"f")}async onEmpty(){L(this,Se,"f").size!==0&&await L(this,Y,"m",Ks).call(this,"empty")}async onSizeLessThan(e){L(this,Se,"f").size<e||await L(this,Y,"m",Ks).call(this,"next",()=>L(this,Se,"f").size<e)}async onIdle(){L(this,Ae,"f")===0&&L(this,Se,"f").size===0||await L(this,Y,"m",Ks).call(this,"idle")}get size(){return L(this,Se,"f").size}sizeBy(e){return L(this,Se,"f").filter(e).length}get pending(){return L(this,Ae,"f")}get isPaused(){return L(this,Nt,"f")}};To=new WeakMap,Io=new WeakMap,Ut=new WeakMap,Gs=new WeakMap,Lo=new WeakMap,js=new WeakMap,$e=new WeakMap,Co=new WeakMap,Se=new WeakMap,Vs=new WeakMap,Ae=new WeakMap,Do=new WeakMap,Nt=new WeakMap,qs=new WeakMap,Y=new WeakSet,Kg=function(){return L(this,Io,"f")||L(this,Ut,"f")<L(this,Gs,"f")},Gg=function(){return L(this,Ae,"f")<L(this,Do,"f")},Xg=function(){var e;K(this,Ae,(e=L(this,Ae,"f"),e--,e),"f"),L(this,Y,"m",Ws).call(this),this.emit("next")},Qg=function(){L(this,Y,"m",wl).call(this),L(this,Y,"m",gl).call(this),K(this,Co,void 0,"f")},Jg=function(){let e=Date.now();if(L(this,$e,"f")===void 0){let r=L(this,js,"f")-e;if(r<0)K(this,Ut,L(this,To,"f")?L(this,Ae,"f"):0,"f");else return L(this,Co,"f")===void 0&&K(this,Co,setTimeout(()=>{L(this,Y,"m",Qg).call(this)},r),"f"),!0}return!1},Ws=function(){if(L(this,Se,"f").size===0)return L(this,$e,"f")&&clearInterval(L(this,$e,"f")),K(this,$e,void 0,"f"),this.emit("empty"),L(this,Ae,"f")===0&&this.emit("idle"),!1;if(!L(this,Nt,"f")){let e=!L(this,Y,"a",Jg);if(L(this,Y,"a",Kg)&&L(this,Y,"a",Gg)){let r=L(this,Se,"f").dequeue();return r?(this.emit("active"),r(),e&&L(this,Y,"m",gl).call(this),!0):!1}}return!1},gl=function(){L(this,Io,"f")||L(this,$e,"f")!==void 0||(K(this,$e,setInterval(()=>{L(this,Y,"m",wl).call(this)},L(this,Lo,"f")),"f"),K(this,js,Date.now()+L(this,Lo,"f"),"f"))},wl=function(){L(this,Ut,"f")===0&&L(this,Ae,"f")===0&&L(this,$e,"f")&&(clearInterval(L(this,$e,"f")),K(this,$e,void 0,"f")),K(this,Ut,L(this,To,"f")?L(this,Ae,"f"):0,"f"),L(this,Y,"m",Qs).call(this)},Qs=function(){for(;L(this,Y,"m",Ws).call(this););},Yg=async function(e){return new Promise((r,n)=>{e.addEventListener("abort",()=>{n(new Js("The task was aborted."))},{once:!0})})},Ks=async function(e,r){return new Promise(n=>{let o=()=>{r&&!r()||(this.off(e,o),n())};this.on(e,o)})};async function ew(t,e,r,n,o,i,s){if(e instanceof Uint8Array){let u=fr(e,n,o,i);r.push(u);return}if(e.Data==null)throw(0,yr.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let c;try{c=ln.unmarshal(e.Data)}catch(u){throw(0,yr.default)(u,"ERR_NOT_UNIXFS")}if(c.data!=null){let u=c.data,l=fr(u,n,o,i);r.push(l),n+=BigInt(l.byteLength)}let a=[];if(e.Links.length!==c.blockSizes.length)throw(0,yr.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 yn(a,u=>dn(u,l=>async()=>{let d=await t.get(l.link.Hash,s);return{...l,block:d}}),u=>hr(u,{ordered:!0}),async u=>{for await(let{link:l,block:d,blockStart:m}of u){let f;switch(l.Hash.code){case ar:f=Ye(d);break;case jn:f=d;break;default:r.end((0,yr.default)(new Error(`Unsupported codec: ${l.Hash.code}`),"ERR_NOT_UNIXFS"));return}let h=new No({concurrency:1});h.on("error",p=>{r.end(p)}),h.add(async()=>{s.onProgress?.(new ce("unixfs:exporter:walk:file",{cid:l.Hash})),await ew(t,f,r,m,o,i,s)}),await h.onIdle()}}),n>=i&&r.end()}var Yv=(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}=cn(u,a.offset,a.length);if(d===0n)return;let m=0n,f=d-l,h=pn();a.onProgress?.(new ce("unixfs:exporter:walk:file",{cid:t})),ew(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,yr.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 ce("unixfs:exporter:progress:unixfs:file",{bytesRead:m,totalBytes:f,fileSize:u})),yield p}if(m<f)throw(0,yr.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return c},bl=Yv;var Zv=(t,e,r,n,o,i,s)=>{function c(a={}){return a.onProgress?.(new ce("unixfs:exporter:walk:hamt-sharded-directory",{cid:t})),tw(e,n,o,i,s,a)}return c};async function*tw(t,e,r,n,o,i){let s=t.Links,c=yn(s,a=>dn(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=Ye(d),i.onProgress?.(new ce("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:tw(t,e,r,n,o,i)}}}),a=>hr(a,{ordered:!0}));for await(let{entries:a}of c)yield*a}var rw=Zv;var eE=(t,e)=>t.Links.find(n=>n.Name===e)?.Hash,tE={raw:bl,file:bl,directory:Hg,"hamt-sharded-directory":rw,metadata:(t,e,r,n,o,i,s)=>()=>[],symlink:(t,e,r,n,o,i,s)=>()=>[]},rE=async(t,e,r,n,o,i,s,c)=>{let a=await s.get(t,c),u=Ye(a),l,d;if(e==null&&(e=t.toString()),u.Data==null)throw(0,Uo.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{l=ln.unmarshal(u.Data)}catch(f){throw(0,Uo.default)(f,"ERR_NOT_UNIXFS")}if(r==null&&(r=e),n.length>0){let f;if(l?.type==="hamt-sharded-directory"?f=await Mg(u,n[0],s):f=eE(u,n[0]),f==null)throw(0,Uo.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=tE[l.type](t,u,l,r,o,i,s);if(m==null)throw(0,Uo.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}},nw=rE;var nE={[ar]:nw,[jn]:fg,[Da]:ag,[ig.code]:ug},iw=async(t,e,r,n,o,i,s)=>{let c=nE[t.code];if(c==null)throw(0,ow.default)(new Error(`No resolver for code ${t.code}`),"ERR_NO_RESOLVER");return c(t,e,r,n,iw,o,i,s)},sw=iw;var oE=(t="")=>(t.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),iE=t=>{if(t instanceof Uint8Array)return{cid:V.decode(t),toResolve:[]};let e=V.asCID(t);if(e!=null)return{cid:e,toResolve:[]};if(typeof t=="string"){t.indexOf("/ipfs/")===0&&(t=t.substring(6));let r=oE(t);return{cid:V.parse(r[0]),toResolve:r.slice(1)}}throw(0,Xs.default)(new Error(`Unknown path type ${t}`),"ERR_BAD_PATH")};async function*sE(t,e,r={}){let{cid:n,toResolve:o}=iE(t),i=n.toString(),s=i,c=o.length;for(;;){let a=await sw(n,i,s,o,c,e,r);if(a.entry==null&&a.next==null)throw(0,Xs.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 aw(t,e,r={}){let n=await rg(sE(t,e,r));if(n==null)throw(0,Xs.default)(new Error(`Could not resolve ${t}`),"ERR_NOT_FOUND");return n}var aE=Zm(),cE=Dt({fileChunkEncoder:Et,smallFileEncoder:Et,chunker:Tu(1024*1024),fileLayout:ws(1024)});async function cw(t){let e=uE(t),r=await lE(e);return{cid:r.at(-1).cid,blocks:r}}async function uw(t,e,r){let n=await aw(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 uE(t){let{readable:e,writable:r}=new TransformStream({},aE),n=Ym({writable:r,settings:cE}),o=new xl("",t);return(async()=>(await o.finalize(n),await n.close()))(),e}async function lE(t){let e=[];return await t.pipeTo(new WritableStream({write(r){e.push(r)}})),e}var Po,xl=class{constructor(e,r){nt(this,Po,void 0);k(this,"name");this.name=e,fe(this,Po,r)}async finalize(e){let r=po(e);return await Z(this,Po).stream().pipeTo(new WritableStream({async write(n){await r.write(n)}})),await r.close()}};Po=new WeakMap;async function dw(t,e,r,n){let o;for(let i of r){let s=await fE(t,i);o=await vp(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 fE(t,e){let r;e.del?r={del:!0}:(await dE(t,e.value),r={doc:e.value});let n=await Ge({value:r,hasher:de,codec:q});return t.putSync(n.cid,n.bytes),n.cid}async function dE(t,e){e._files&&await lw(t,e._files),e._publicFiles&&await lw(t,e._publicFiles,!0)}async function lw(t,e,r=!1){let n=t.parent,o=new _t(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 cw(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 hw(t,e,r){if(!e.length)throw new Error("Getting from an empty database");let n=await Ep(t,e,r);if(!n)throw new Error(`Missing key ${r}`);return await Sl(t,n)}function El(t,{doc:e}){e&&(e._files&&fw(t,e._files),e._publicFiles&&fw(t,e._publicFiles,!0))}function fw(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 uw({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 Sl(t,e){let r=await t.get(e);if(!r)throw new Error(`Missing linked block ${e.toString()}`);let{value:n}=await vt({bytes:r.bytes,hasher:de,codec:q});return El(t,n),n}var kl=class extends Je{async get(e){try{return await super.get(e)}catch(r){return console.error("missing event",e.toString(),r),{value:null}}}};async function Fo(t,e,r,n){let o=n.dirty?new kl(t):new Je(t);return{result:(await vl(t,o,e,r,[],new Set,new Set,n.limit||1/0)).reverse(),head:e}}async function vl(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 vl(t,e,l.parents,n,o,i,s,c));else{i.add(d);let f=await Sl(t,m);o.push({key:d,value:f.doc,del:f.del}),c--,l.parents&&(o=await vl(t,e,l.parents,n,o,i,s,c))}}return o}async function*pw(t,e){for await(let[r,n]of Rc(t,e)){let o=await Sl(t,n);yield{key:r,value:o.doc,del:o.del}}}async function*yw(t,e){for await(let r of Fc(t,e))yield r}async function mw(t,e){let r=new qi(t),n=new _t(t);for await(let[,i]of Rc(r,e))if(!await r.get(i))throw new Error("Missing block: "+i.toString());for await(let i of Fc(r,e));let o=await Kr(r,e);for(let{cid:i,bytes:s}of[...o.additions,...o.removals])n.putSync(i,s);await Fo(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 Ys=class{constructor(){k(this,"head",[]);k(this,"zoomers",new Set);k(this,"watchers",new Set);k(this,"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 _t)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 Yn(u,l,m);let d=await Kr(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 Fo(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 Zs=class{constructor(e,r){k(this,"name");k(this,"opts",{});k(this,"ready");k(this,"blocks");k(this,"indexBlocks");k(this,"indexers",new Map);k(this,"clock",new Ys);this.name=e||null,this.opts=r||this.opts,this.blocks=new Vi(this.name,this.clock,this.opts),this.clock.blocks=this.blocks,this.indexBlocks=new ji(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 dw(n,this.clock.head,e,r);return e=e.map(({key:s,value:c,del:a})=>(El(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 pw(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 yw(this.blocks,this.clock.head))e.push(r);return e.join(`
|
4
|
+
`)}async get(e){await this.ready;let r=await hw(this.blocks,this.clock.head,e);return r.del?null:r}async changes(e=[],r={}){return await this.ready,await Fo(this.blocks,this.clock.head,e,r)}async compact(){if(await this.ready,!(this.blocks.loader&&this.blocks.loader.carLog.length<2))return await mw(this.blocks,this.clock.head)}};var Pt=class{constructor(e,r){k(this,"name");k(this,"opts",{});k(this,"_listeners",new Set);k(this,"_crdt");k(this,"_writeQueue");this.name=e||null,this.opts=r||this.opts,this._crdt=new Zs(e,this.opts),this._crdt.clock.onTick(n=>{this._notify(n)}),this._writeQueue=Tl(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||Cl(),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"?Wr({_crdt:this._crdt},e):Wr({_crdt:this._crdt},pE(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)})}}};k(Pt,"databases",new Map);function hE(t,e){return Pt.databases.has(t)||Pt.databases.set(t,new Pt(t,e)),Pt.databases.get(t)}function pE(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}return Ew(yE);})();
|
26
5
|
/*! Bundled license information:
|
27
6
|
|
28
|
-
@noble/ed25519/lib/esm/index.js:
|
29
|
-
(*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
|
30
|
-
|
31
7
|
uuidv7/dist/index.js:
|
32
8
|
(**
|
33
9
|
* uuidv7: An experimental implementation of the proposed UUID Version 7
|