From d6565755c8d9e72fb81079c1d68f3b58ed34f324 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B4=CF=85=CF=82?= Date: Thu, 10 Oct 2024 09:30:57 -0400 Subject: [PATCH] Updates --- ...itor-BZjgjvzZ.js => MarkdownEditor-BjREHNgK.js} | 6 +++--- assets/{ccip-C65gceaI.js => ccip-DwSTQdgO.js} | 2 +- ...module-BGL-0WI2.js => hooks.module-BcwbS9_4.js} | 2 +- assets/{index-C2wvX7We.js => index-3vXbTmOw.js} | 2 +- assets/{index-CBwDx5gl.js => index-4Hagg-7l.js} | 14 +++++++------- assets/{index-DU_L3lXF.js => index-Ai9Weebq.js} | 2 +- assets/{index-Du_jcaiP.js => index-B8jQNpCr.js} | 2 +- assets/{index-BD1OjTxN.js => index-B9vDB2b7.js} | 2 +- assets/{index-DocGlZMh.js => index-BiSwxBQ1.js} | 2 +- assets/{index-DsdYCcX2.js => index-BiyKXlbq.js} | 2 +- assets/{index-CIykCf4V.js => index-BokeEoEU.js} | 2 +- assets/{index-BRP0rdCl.js => index-BsyXQ4Po.js} | 2 +- assets/index-Bx4zt1nf.css | 1 - assets/{index-DC1Fb-7Y.js => index-C0D5lmsC.js} | 2 +- assets/{index-CRlmaQeU.js => index-C46J882Q.js} | 2 +- assets/index-C5iV8B94.css | 1 + assets/{index-B4L7DgZe.js => index-C95wco15.js} | 2 +- assets/{index-jRjoKnSb.js => index-CB9V-exR.js} | 2 +- assets/{index-CnStXQ1G.js => index-D5QN3wsq.js} | 2 +- assets/{index-Br-i5CyM.js => index-D97Cskqz.js} | 2 +- assets/{index-BN-uPEw0.js => index-DOC88JTU.js} | 2 +- assets/{index-DXK7-roO.js => index-DPGV2Jmk.js} | 2 +- assets/{index-D2BcTF5n.js => index-DUeiJTUn.js} | 2 +- assets/{index-B5R0vXrb.js => index-DYSmb46M.js} | 2 +- assets/{index-DWGivvfr.js => index-DqyaIzih.js} | 2 +- assets/{index-Czk6-ejp.js => index-qkal7za7.js} | 2 +- ...dex.lazy-CnuJ_C2i.js => index.lazy-BRB6PNxD.js} | 8 ++++---- ...dex.lazy-BI9rjCag.js => index.lazy-C0W667Dk.js} | 2 +- ...qual-D9iYaUN7.js => isAddressEqual-DlPIwSPc.js} | 2 +- ...secp256k1-B5jMENlr.js => secp256k1-CibHJEZu.js} | 2 +- ...w3m-modal-C_J1BgbU.js => w3m-modal-V5rdP7TG.js} | 8 ++++---- index.html | 4 ++-- 32 files changed, 46 insertions(+), 46 deletions(-) rename assets/{MarkdownEditor-BZjgjvzZ.js => MarkdownEditor-BjREHNgK.js} (99%) rename assets/{ccip-C65gceaI.js => ccip-DwSTQdgO.js} (95%) rename assets/{hooks.module-BGL-0WI2.js => hooks.module-BcwbS9_4.js} (99%) rename assets/{index-C2wvX7We.js => index-3vXbTmOw.js} (99%) rename assets/{index-CBwDx5gl.js => index-4Hagg-7l.js} (99%) rename assets/{index-DU_L3lXF.js => index-Ai9Weebq.js} (98%) rename assets/{index-Du_jcaiP.js => index-B8jQNpCr.js} (99%) rename assets/{index-BD1OjTxN.js => index-B9vDB2b7.js} (98%) rename assets/{index-DocGlZMh.js => index-BiSwxBQ1.js} (99%) rename assets/{index-DsdYCcX2.js => index-BiyKXlbq.js} (98%) rename assets/{index-CIykCf4V.js => index-BokeEoEU.js} (96%) rename assets/{index-BRP0rdCl.js => index-BsyXQ4Po.js} (99%) delete mode 100644 assets/index-Bx4zt1nf.css rename assets/{index-DC1Fb-7Y.js => index-C0D5lmsC.js} (99%) rename assets/{index-CRlmaQeU.js => index-C46J882Q.js} (99%) create mode 100644 assets/index-C5iV8B94.css rename assets/{index-B4L7DgZe.js => index-C95wco15.js} (92%) rename assets/{index-jRjoKnSb.js => index-CB9V-exR.js} (99%) rename assets/{index-CnStXQ1G.js => index-D5QN3wsq.js} (99%) rename assets/{index-Br-i5CyM.js => index-D97Cskqz.js} (99%) rename assets/{index-BN-uPEw0.js => index-DOC88JTU.js} (92%) rename assets/{index-DXK7-roO.js => index-DPGV2Jmk.js} (98%) rename assets/{index-D2BcTF5n.js => index-DUeiJTUn.js} (99%) rename assets/{index-B5R0vXrb.js => index-DYSmb46M.js} (98%) rename assets/{index-DWGivvfr.js => index-DqyaIzih.js} (98%) rename assets/{index-Czk6-ejp.js => index-qkal7za7.js} (94%) rename assets/{index.lazy-CnuJ_C2i.js => index.lazy-BRB6PNxD.js} (99%) rename assets/{index.lazy-BI9rjCag.js => index.lazy-C0W667Dk.js} (99%) rename assets/{isAddressEqual-D9iYaUN7.js => isAddressEqual-DlPIwSPc.js} (70%) rename assets/{secp256k1-B5jMENlr.js => secp256k1-CibHJEZu.js} (99%) rename assets/{w3m-modal-C_J1BgbU.js => w3m-modal-V5rdP7TG.js} (95%) diff --git a/assets/MarkdownEditor-BZjgjvzZ.js b/assets/MarkdownEditor-BjREHNgK.js similarity index 99% rename from assets/MarkdownEditor-BZjgjvzZ.js rename to assets/MarkdownEditor-BjREHNgK.js index 453f941..cdee360 100644 --- a/assets/MarkdownEditor-BZjgjvzZ.js +++ b/assets/MarkdownEditor-BjREHNgK.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BRP0rdCl.js","assets/index-CBwDx5gl.js","assets/index-Bx4zt1nf.css","assets/index.lazy-CnuJ_C2i.js","assets/isAddressEqual-D9iYaUN7.js","assets/secp256k1-B5jMENlr.js","assets/index-lHEOM186.css","assets/index-CnStXQ1G.js","assets/index-jRjoKnSb.js","assets/index-Br-i5CyM.js","assets/index-BN-uPEw0.js","assets/index-DXK7-roO.js","assets/index-DU_L3lXF.js","assets/index-CRlmaQeU.js","assets/index-DC1Fb-7Y.js","assets/index-C2wvX7We.js","assets/index-D2BcTF5n.js","assets/index-B4L7DgZe.js","assets/index-DWGivvfr.js","assets/index-BD1OjTxN.js","assets/dockerfile-BuNIbK2j.js","assets/simple-mode-C4Nsj8zu.js","assets/factor-D8pE9siL.js","assets/nsis-CEAdamBV.js","assets/pug-BmUsPMDj.js","assets/javascript-iSgyE4tI.js","assets/index-Czk6-ejp.js","assets/index-CIykCf4V.js"])))=>i.map(i=>d[i]); -import{b6 as w,e as k,j as R,cM as Lo,g as dC,cN as v7,cO as w7,b8 as V,f as vx}from"./index-CBwDx5gl.js";import{s as ip,r as S7,c as wx,d as Sx,V as sn,o as sr,a as eu,m as on,b as Ar,f as li,e as $r,u as Pi,g as Jn,h as _l,v as k7,E as C7,t as pC,i as _7,j as P7,k as T7}from"./index.lazy-CnuJ_C2i.js";var E7=Object.defineProperty,$7=(n,e,t)=>e in n?E7(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ai=(n,e,t)=>($7(n,typeof e!="symbol"?e+"":e,t),t);let A7=class gC{constructor(e=new Map){this.map=e}clone(){return new gC(new Map(this.map))}increment(e){const t=this.map.get(e)??0;this.map.set(e,t+1)}decrement(e,t){let r=this.map.get(e);r!==void 0&&(r-=1,this.map.set(e,r),r===0&&t())}},tu=class{constructor(){Ai(this,"map",new Map)}getOrCreate(e){let t=this.map.get(e);return t===void 0&&(t=new Set,this.map.set(e,t)),t}get(e){return this.map.get(e)}use(e,t){const r=this.get(e);r!==void 0&&t(r)}delete(e){return this.map.delete(e)}};function vo(n,e){return e(n),n}function n1(){}function kx(n,e){return n===e}const Bf=new Map;let Q7=class{constructor(e={}){Ai(this,"subscriptions",new tu),Ai(this,"singletonSubscriptions",new Map),Ai(this,"graph",new tu),Ai(this,"state",new Map),Ai(this,"distinctNodes",new Map),Ai(this,"executionMaps",new Map),Ai(this,"definitionRegistry",new Set);for(const t of Object.getOwnPropertySymbols(e))this.state.set(t,e[t])}cellInstance(e,t=!0,r=Symbol()){return this.state.has(r)||this.state.set(r,e),t!==!1&&!this.distinctNodes.has(r)&&this.distinctNodes.set(r,t===!0?kx:t),r}signalInstance(e=!0,t=Symbol()){return e!==!1&&this.distinctNodes.set(t,e===!0?kx:e),t}sub(e,t){this.register(e);const r=this.subscriptions.getOrCreate(e);return r.add(t),()=>r.delete(t)}singletonSub(e,t){return this.register(e),t===void 0?this.singletonSubscriptions.delete(e):this.singletonSubscriptions.set(e,t),()=>this.singletonSubscriptions.delete(e)}resetSingletonSubs(){this.singletonSubscriptions.clear()}subMultiple(e,t){const r=this.signalInstance();return this.connect({map:i=>(...s)=>{i(s)},sink:r,sources:e}),this.sub(r,t)}pubIn(e){var t;const r=Reflect.ownKeys(e),i=this.getExecutionMap(r),s=i.refCount.clone(),o=i.participatingNodes.slice(),l=new Map(this.state),a=c=>{this.graph.use(c,u=>{for(const{sources:h,sink:f}of u)h.has(c)&&s.decrement(f,()=>{o.splice(o.indexOf(f),1),a(f)})})};for(;;){const c=o.shift();if(c===void 0)break;const u=c;let h=!1;const f=d=>{const p=this.distinctNodes.get(u);if(p!==void 0&&p(l.get(u),d)){h=!1;return}h=!0,l.set(u,d),this.state.has(u)&&this.state.set(u,d)};if(Object.prototype.hasOwnProperty.call(e,u)?f(e[u]):i.projections.use(u,d=>{for(const p of d){const g=[...Array.from(p.sources),...Array.from(p.pulls)].map(m=>l.get(m));p.map(f)(...g)}}),h){const d=l.get(u);this.subscriptions.use(u,p=>{for(const g of p)g(d)}),(t=this.singletonSubscriptions.get(u))==null||t(d)}else a(u)}}connect({sources:e,pulls:t=[],map:r,sink:i}){const s={map:r,pulls:new Set(t),sink:this.register(i),sources:new Set(e)};for(const o of[...e,...t])this.register(o),this.graph.getOrCreate(o).add(s);this.executionMaps.clear()}pub(e,t){this.pubIn({[e]:t})}pipe(e,...t){return this.combineOperators(...t)(e)}transformer(...e){return t=>vo(this.signalInstance(),r=>(this.link(this.pipe(r,...e),t),r))}link(e,t){this.connect({map:r=>i=>{r(i)},sink:t,sources:[e]})}combine(...e){return vo(this.signalInstance(),t=>{this.connect({map:r=>(...i)=>{r(i)},sink:t,sources:e})})}getValue(e){return this.register(e),this.state.get(e)}getValues(e){return e.map(t=>this.getValue(t))}register(e){const t=Bf.get(e);return t===void 0||this.definitionRegistry.has(e)?e:(this.definitionRegistry.add(e),vo(t.type==="cell"?this.cellInstance(t.initial,t.distinct,e):this.signalInstance(t.distinct,e),r=>{t.init(this,r)}))}changeWith(e,t,r){this.connect({sources:[t],pulls:[e],sink:e,map:i=>(s,o)=>{i(r(o,s))}})}calculateExecutionMap(e){const t=[],r=new Set,i=new tu,s=new A7,o=new tu,l=(a,c=0)=>{s.increment(a),!r.has(a)&&(this.register(a),i.use(a,u=>{c=Math.max(...Array.from(u).map(h=>t.indexOf(h)))+1}),this.graph.use(a,u=>{for(const h of u)h.sources.has(a)?(o.getOrCreate(h.sink).add(h),l(h.sink,c)):i.getOrCreate(h.sink).add(a)}),r.add(a),t.splice(c,0,a))};return e.forEach(l),{participatingNodes:t,pendingPulls:i,projections:o,refCount:s}}getExecutionMap(e){let t=e;if(e.length===1){t=e[0];const i=this.executionMaps.get(t);if(i!==void 0)return i}else for(const[i,s]of this.executionMaps.entries())if(Array.isArray(i)&&i.length===e.length&&i.every(o=>e.includes(o)))return s;const r=this.calculateExecutionMap(e);return this.executionMaps.set(t,r),r}combineOperators(...e){return t=>{for(const r of e)t=r(t,this);return t}}};function be(n,e=n1,t=!0){return vo(Symbol(),r=>{Bf.set(r,{type:"cell",distinct:t,initial:n,init:e})})}function gt(n=n1,e=!1){return vo(Symbol(),t=>{Bf.set(t,{type:"signal",distinct:e,init:n})})}function os(n=n1){return vo(Symbol(),e=>{Bf.set(e,{type:"signal",distinct:!1,init:n})})}const mC=w.createContext(null);function lc(){const n=w.useContext(mC);if(n===null)throw new Error("useRealm must be used within a RealmContextProvider");return n}function Nt(n){const e=lc();e.register(n);const t=w.useCallback(r=>e.sub(n,r),[e,n]);return w.useSyncExternalStore(t,()=>e.getValue(n),()=>e.getValue(n))}function yt(...n){const e=lc(),t=w.useMemo(()=>e.getValues(n),[]),r=w.useRef(t),i=w.useCallback(s=>{const o=l=>{r.current=l,s()};return e.subMultiple(n,o)},[e,...n]);return w.useSyncExternalStore(i,()=>r.current,()=>r.current)}function at(n){const e=lc();return e.register(n),w.useCallback(t=>{e.pub(n,t)},[e,n])}function ui(n){return(e,t)=>{const r=t.signalInstance();return t.connect({map:i=>s=>{i(n(s))},sink:r,sources:[e]}),r}}function ct(...n){return(e,t)=>{const r=t.signalInstance();return t.connect({map:i=>(...s)=>{i(s)},pulls:n,sink:r,sources:[e]}),r}}function OC(n){return(e,t)=>{const r=t.signalInstance();return t.connect({map:i=>()=>{i(n)},sink:r,sources:[e]}),r}}function ac(n){return(e,t)=>{const r=t.signalInstance();return t.connect({map:i=>s=>{n(s)&&i(s)},sink:r,sources:[e]}),r}}function bC(n,e){return(t,r)=>{const i=r.signalInstance();return r.connect({map:s=>o=>{s(e=n(e,o))},sink:i,sources:[t]}),i}}function R7(n,e){return e(n),n}function Es(){}function Nn(n){return function(e){return{init:t=>{var r;return(r=n.init)==null?void 0:r.call(n,t,e)},postInit:t=>{var r;return(r=n.postInit)==null?void 0:r.call(n,t,e)},update:t=>{var r;return(r=n.update)==null?void 0:r.call(n,t,e)}}}}function M7({children:n,plugins:e}){const t=w.useMemo(()=>R7(new Q7,r=>{var i,s;for(const o of e)(i=o.init)==null||i.call(o,r);for(const o of e)(s=o.postInit)==null||s.call(o,r)}),[]);return w.useEffect(()=>{var r;for(const i of e)(r=i.update)==null||r.call(i,t)}),w.createElement(mC.Provider,{value:t},n)}function L7(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var I7=L7(function(n){const e=new URLSearchParams;e.append("code",n);for(let t=1;ti.map(i=>d[i]); +import{b6 as w,e as k,j as R,cM as Lo,g as dC,cN as v7,cO as w7,b8 as V,f as vx}from"./index-4Hagg-7l.js";import{s as ip,r as S7,c as wx,d as Sx,V as sn,o as sr,a as eu,m as on,b as Ar,f as li,e as $r,u as Pi,g as Jn,h as _l,v as k7,E as C7,t as pC,i as _7,j as P7,k as T7}from"./index.lazy-BRB6PNxD.js";var E7=Object.defineProperty,$7=(n,e,t)=>e in n?E7(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ai=(n,e,t)=>($7(n,typeof e!="symbol"?e+"":e,t),t);let A7=class gC{constructor(e=new Map){this.map=e}clone(){return new gC(new Map(this.map))}increment(e){const t=this.map.get(e)??0;this.map.set(e,t+1)}decrement(e,t){let r=this.map.get(e);r!==void 0&&(r-=1,this.map.set(e,r),r===0&&t())}},tu=class{constructor(){Ai(this,"map",new Map)}getOrCreate(e){let t=this.map.get(e);return t===void 0&&(t=new Set,this.map.set(e,t)),t}get(e){return this.map.get(e)}use(e,t){const r=this.get(e);r!==void 0&&t(r)}delete(e){return this.map.delete(e)}};function vo(n,e){return e(n),n}function n1(){}function kx(n,e){return n===e}const Bf=new Map;let Q7=class{constructor(e={}){Ai(this,"subscriptions",new tu),Ai(this,"singletonSubscriptions",new Map),Ai(this,"graph",new tu),Ai(this,"state",new Map),Ai(this,"distinctNodes",new Map),Ai(this,"executionMaps",new Map),Ai(this,"definitionRegistry",new Set);for(const t of Object.getOwnPropertySymbols(e))this.state.set(t,e[t])}cellInstance(e,t=!0,r=Symbol()){return this.state.has(r)||this.state.set(r,e),t!==!1&&!this.distinctNodes.has(r)&&this.distinctNodes.set(r,t===!0?kx:t),r}signalInstance(e=!0,t=Symbol()){return e!==!1&&this.distinctNodes.set(t,e===!0?kx:e),t}sub(e,t){this.register(e);const r=this.subscriptions.getOrCreate(e);return r.add(t),()=>r.delete(t)}singletonSub(e,t){return this.register(e),t===void 0?this.singletonSubscriptions.delete(e):this.singletonSubscriptions.set(e,t),()=>this.singletonSubscriptions.delete(e)}resetSingletonSubs(){this.singletonSubscriptions.clear()}subMultiple(e,t){const r=this.signalInstance();return this.connect({map:i=>(...s)=>{i(s)},sink:r,sources:e}),this.sub(r,t)}pubIn(e){var t;const r=Reflect.ownKeys(e),i=this.getExecutionMap(r),s=i.refCount.clone(),o=i.participatingNodes.slice(),l=new Map(this.state),a=c=>{this.graph.use(c,u=>{for(const{sources:h,sink:f}of u)h.has(c)&&s.decrement(f,()=>{o.splice(o.indexOf(f),1),a(f)})})};for(;;){const c=o.shift();if(c===void 0)break;const u=c;let h=!1;const f=d=>{const p=this.distinctNodes.get(u);if(p!==void 0&&p(l.get(u),d)){h=!1;return}h=!0,l.set(u,d),this.state.has(u)&&this.state.set(u,d)};if(Object.prototype.hasOwnProperty.call(e,u)?f(e[u]):i.projections.use(u,d=>{for(const p of d){const g=[...Array.from(p.sources),...Array.from(p.pulls)].map(m=>l.get(m));p.map(f)(...g)}}),h){const d=l.get(u);this.subscriptions.use(u,p=>{for(const g of p)g(d)}),(t=this.singletonSubscriptions.get(u))==null||t(d)}else a(u)}}connect({sources:e,pulls:t=[],map:r,sink:i}){const s={map:r,pulls:new Set(t),sink:this.register(i),sources:new Set(e)};for(const o of[...e,...t])this.register(o),this.graph.getOrCreate(o).add(s);this.executionMaps.clear()}pub(e,t){this.pubIn({[e]:t})}pipe(e,...t){return this.combineOperators(...t)(e)}transformer(...e){return t=>vo(this.signalInstance(),r=>(this.link(this.pipe(r,...e),t),r))}link(e,t){this.connect({map:r=>i=>{r(i)},sink:t,sources:[e]})}combine(...e){return vo(this.signalInstance(),t=>{this.connect({map:r=>(...i)=>{r(i)},sink:t,sources:e})})}getValue(e){return this.register(e),this.state.get(e)}getValues(e){return e.map(t=>this.getValue(t))}register(e){const t=Bf.get(e);return t===void 0||this.definitionRegistry.has(e)?e:(this.definitionRegistry.add(e),vo(t.type==="cell"?this.cellInstance(t.initial,t.distinct,e):this.signalInstance(t.distinct,e),r=>{t.init(this,r)}))}changeWith(e,t,r){this.connect({sources:[t],pulls:[e],sink:e,map:i=>(s,o)=>{i(r(o,s))}})}calculateExecutionMap(e){const t=[],r=new Set,i=new tu,s=new A7,o=new tu,l=(a,c=0)=>{s.increment(a),!r.has(a)&&(this.register(a),i.use(a,u=>{c=Math.max(...Array.from(u).map(h=>t.indexOf(h)))+1}),this.graph.use(a,u=>{for(const h of u)h.sources.has(a)?(o.getOrCreate(h.sink).add(h),l(h.sink,c)):i.getOrCreate(h.sink).add(a)}),r.add(a),t.splice(c,0,a))};return e.forEach(l),{participatingNodes:t,pendingPulls:i,projections:o,refCount:s}}getExecutionMap(e){let t=e;if(e.length===1){t=e[0];const i=this.executionMaps.get(t);if(i!==void 0)return i}else for(const[i,s]of this.executionMaps.entries())if(Array.isArray(i)&&i.length===e.length&&i.every(o=>e.includes(o)))return s;const r=this.calculateExecutionMap(e);return this.executionMaps.set(t,r),r}combineOperators(...e){return t=>{for(const r of e)t=r(t,this);return t}}};function be(n,e=n1,t=!0){return vo(Symbol(),r=>{Bf.set(r,{type:"cell",distinct:t,initial:n,init:e})})}function gt(n=n1,e=!1){return vo(Symbol(),t=>{Bf.set(t,{type:"signal",distinct:e,init:n})})}function os(n=n1){return vo(Symbol(),e=>{Bf.set(e,{type:"signal",distinct:!1,init:n})})}const mC=w.createContext(null);function lc(){const n=w.useContext(mC);if(n===null)throw new Error("useRealm must be used within a RealmContextProvider");return n}function Nt(n){const e=lc();e.register(n);const t=w.useCallback(r=>e.sub(n,r),[e,n]);return w.useSyncExternalStore(t,()=>e.getValue(n),()=>e.getValue(n))}function yt(...n){const e=lc(),t=w.useMemo(()=>e.getValues(n),[]),r=w.useRef(t),i=w.useCallback(s=>{const o=l=>{r.current=l,s()};return e.subMultiple(n,o)},[e,...n]);return w.useSyncExternalStore(i,()=>r.current,()=>r.current)}function at(n){const e=lc();return e.register(n),w.useCallback(t=>{e.pub(n,t)},[e,n])}function ui(n){return(e,t)=>{const r=t.signalInstance();return t.connect({map:i=>s=>{i(n(s))},sink:r,sources:[e]}),r}}function ct(...n){return(e,t)=>{const r=t.signalInstance();return t.connect({map:i=>(...s)=>{i(s)},pulls:n,sink:r,sources:[e]}),r}}function OC(n){return(e,t)=>{const r=t.signalInstance();return t.connect({map:i=>()=>{i(n)},sink:r,sources:[e]}),r}}function ac(n){return(e,t)=>{const r=t.signalInstance();return t.connect({map:i=>s=>{n(s)&&i(s)},sink:r,sources:[e]}),r}}function bC(n,e){return(t,r)=>{const i=r.signalInstance();return r.connect({map:s=>o=>{s(e=n(e,o))},sink:i,sources:[t]}),i}}function R7(n,e){return e(n),n}function Es(){}function Nn(n){return function(e){return{init:t=>{var r;return(r=n.init)==null?void 0:r.call(n,t,e)},postInit:t=>{var r;return(r=n.postInit)==null?void 0:r.call(n,t,e)},update:t=>{var r;return(r=n.update)==null?void 0:r.call(n,t,e)}}}}function M7({children:n,plugins:e}){const t=w.useMemo(()=>R7(new Q7,r=>{var i,s;for(const o of e)(i=o.init)==null||i.call(o,r);for(const o of e)(s=o.postInit)==null||s.call(o,r)}),[]);return w.useEffect(()=>{var r;for(const i of e)(r=i.update)==null||r.call(i,t)}),w.createElement(mC.Provider,{value:t},n)}function L7(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var I7=L7(function(n){const e=new URLSearchParams;e.append("code",n);for(let t=1;ts8;try{An(n,()=>{const i=le()||function(f){return f.getEditorState().read(()=>{const d=le();return d!==null?d.clone():null})}(n),s=new Map,o=n.getRootElement(),l=n._editorState,a=n._blockCursorElement;let c=!1,u="";for(let f=0;f0){let y=0;for(let v=0;v0)for(const[f,d]of s)if(z(d)){const p=d.getChildrenKeys();let g=f.firstChild;for(let m=0;m0){for(let f=0;f{TC(n,e,t)})}function _x(n,e){const t=n.__mode,r=n.__format,i=n.__style,s=e.__mode,o=e.__format,l=e.__style;return!(t!==null&&t!==s||r!==null&&r!==o||i!==null&&i!==l)}function Px(n,e){const t=n.mergeWithSibling(e),r=pt()._normalizedNodes;return r.add(n.__key),r.add(e.__key),t}function Tx(n){let e,t,r=n;if(r.__text!==""||!r.isSimpleText()||r.isUnmergeable()){for(;(e=r.getPreviousSibling())!==null&&oe(e)&&e.isSimpleText()&&!e.isUnmergeable();){if(e.__text!==""){if(_x(e,r)){r=Px(e,r);break}break}e.remove()}for(;(t=r.getNextSibling())!==null&&oe(t)&&t.isSimpleText()&&!t.isUnmergeable();){if(t.__text!==""){if(_x(r,t)){r=Px(r,t);break}break}t.remove()}}else r.remove()}function k1(n){return Ex(n.anchor),Ex(n.focus),n}function Ex(n){for(;n.type==="element";){const e=n.getNode(),t=n.offset;let r,i;if(t===e.getChildrenSize()?(r=e.getChildAtIndex(t-1),i=!0):(r=e.getChildAtIndex(t),i=!1),oe(r)){n.set(r.__key,i?r.getTextContentSize():0,"text");break}if(!z(r))break;n.set(r.__key,i?r.getChildrenSize():0,"element")}}let c8=1;const u8=typeof queueMicrotask=="function"?queueMicrotask:n=>{Promise.resolve().then(n)};function C1(n){const e=document.activeElement;if(e===null)return!1;const t=e.nodeName;return Xe(jr(n))&&(t==="INPUT"||t==="TEXTAREA"||e.contentEditable==="true"&&Kf(e)==null)}function fc(n,e,t){const r=n.getRootElement();try{return r!==null&&r.contains(e)&&r.contains(t)&&e!==null&&!C1(e)&&P1(e)===n}catch{return!1}}function _1(n){return n instanceof ld}function P1(n){let e=n;for(;e!=null;){const t=Kf(e);if(_1(t))return t;e=ed(e)}return null}function Kf(n){return n?n.__lexicalEditor:null}function ao(n){return n.isToken()||n.isSegmented()}function h8(n){return n.nodeType===ls}function Th(n){let e=n;for(;e!=null;){if(h8(e))return e;e=e.firstChild}return null}function Dg(n,e,t){const r=hi[e];if(t!==null&&(n&r)==(t&r))return n;let i=n^r;return e==="subscript"?i&=~hi.superscript:e==="superscript"&&(i&=~hi.subscript),i}function AC(n){return oe(n)||fi(n)||Xe(n)}function QC(n,e){if(e!=null)return void(n.__key=e);bn(),s2();const t=pt(),r=ki(),i=""+c8++;r._nodeMap.set(i,n),z(n)?t._dirtyElements.set(i,!0):t._dirtyLeaves.add(i),t._cloneNotNeeded.add(i),t._dirtyType=CC,n.__key=i}function As(n){const e=n.getParent();if(e!==null){const t=n.getWritable(),r=e.getWritable(),i=n.getPreviousSibling(),s=n.getNextSibling();if(i===null)if(s!==null){const o=s.getWritable();r.__first=s.__key,o.__prev=null}else r.__first=null;else{const o=i.getWritable();if(s!==null){const l=s.getWritable();l.__prev=o.__key,o.__next=l.__key}else o.__next=null;t.__prev=null}if(s===null)if(i!==null){const o=i.getWritable();r.__last=i.__key,o.__next=null}else r.__last=null;else{const o=s.getWritable();if(i!==null){const l=i.getWritable();l.__next=o.__key,o.__prev=l.__key}else o.__prev=null;t.__next=null}r.__size--,t.__parent=null}}function Eh(n){s2();const e=n.getLatest(),t=e.__parent,r=ki(),i=pt(),s=r._nodeMap,o=i._dirtyElements;t!==null&&function(a,c,u){let h=a;for(;h!==null;){if(u.has(h))return;const f=c.get(h);if(f===void 0)break;u.set(h,!1),h=f.__parent}}(t,s,o);const l=e.__key;i._dirtyType=CC,z(n)?o.set(l,!0):i._dirtyLeaves.add(l)}function zt(n){bn();const e=pt(),t=e._compositionKey;if(n!==t){if(e._compositionKey=n,t!==null){const r=ht(t);r!==null&&r.getWritable()}if(n!==null){const r=ht(n);r!==null&&r.getWritable()}}}function Zi(){return gc()?null:pt()._compositionKey}function ht(n,e){const t=(e||ki())._nodeMap.get(n);return t===void 0?null:t}function RC(n,e){const t=n[`__lexicalKey_${pt()._key}`];return t!==void 0?ht(t,e):null}function jr(n,e){let t=n;for(;t!=null;){const r=RC(t,e);if(r!==null)return r;t=ed(t)}return null}function MC(n){const e=n._decorators,t=Object.assign({},e);return n._pendingDecorators=t,t}function $x(n){return n.read(()=>ze().getTextContent())}function ze(){return LC(ki())}function LC(n){return n._nodeMap.get("root")}function en(n){bn();const e=ki();n!==null&&(n.dirty=!0,n.setCachedNodes(null)),e._selection=n}function mo(n){const e=pt(),t=function(r,i){let s=r;for(;s!=null;){const o=s[`__lexicalKey_${i._key}`];if(o!==void 0)return o;s=ed(s)}return null}(n,e);return t===null?n===e.getRootElement()?ht("root"):null:ht(t)}function Ax(n,e){return e?n.getTextContentSize():0}function IC(n){return/[\uD800-\uDBFF][\uDC00-\uDFFF]/g.test(n)}function T1(n){const e=[];let t=n;for(;t!==null;)e.push(t),t=t._parentEditor;return e}function DC(){return Math.random().toString(36).replace(/[^a-z]+/g,"").substr(0,5)}function NC(n){return n.nodeType===ls?n.nodeValue:null}function E1(n,e,t){const r=Xr(e._window);if(r===null)return;const i=r.anchorNode;let{anchorOffset:s,focusOffset:o}=r;if(i!==null){let l=NC(i);const a=jr(i);if(l!==null&&oe(a)){if(l===Gf&&t){const c=t.length;l=t,s=c,o=c}l!==null&&$1(a,l,s,o,n)}}}function $1(n,e,t,r,i){let s=n;if(s.isAttached()&&(i||!s.isDirty())){const o=s.isComposing();let l=e;(o||i)&&e[e.length-1]===Gf&&(l=e.slice(0,-1));const a=s.getTextContent();if(i||l!==a){if(l===""){if(zt(null),p1||Uf||g1)s.remove();else{const g=pt();setTimeout(()=>{g.update(()=>{s.isAttached()&&s.remove()})},20)}return}const c=s.getParent(),u=ol(),h=s.getTextContentSize(),f=Zi(),d=s.getKey();if(s.isToken()||f!==null&&d===f&&!o||U(u)&&(c!==null&&!c.canInsertTextBefore()&&u.anchor.offset===0||u.anchor.key===n.__key&&u.anchor.offset===0&&!s.canInsertTextBefore()&&!o||u.focus.key===n.__key&&u.focus.offset===h&&!s.canInsertTextAfter()&&!o))return void s.markDirty();const p=le();if(!U(p)||t===null||r===null)return void s.setTextContent(l);if(p.setTextNodeRange(s,t,s,r),s.isSegmented()){const g=Ot(s.getTextContent());s.replace(g),s=g}s.setTextContent(l)}}}function f8(n,e){if(e.isSegmented())return!0;if(!n.isCollapsed())return!1;const t=n.anchor.offset,r=e.getParentOrThrow(),i=e.isToken();return t===0?!e.canInsertTextBefore()||!r.canInsertTextBefore()&&!e.isComposing()||i||function(s){const o=s.getPreviousSibling();return(oe(o)||z(o)&&o.isInline())&&!o.canInsertTextAfter()}(e):t===e.getTextContentSize()&&(!e.canInsertTextAfter()||!r.canInsertTextAfter()&&!e.isComposing()||i)}function Qx(n){return n==="ArrowLeft"}function Rx(n){return n==="ArrowRight"}function jl(n,e){return nr?n:e}function Mx(n){return n==="Enter"}function Pl(n){return n==="Backspace"}function Tl(n){return n==="Delete"}function Lx(n,e,t){return n.toLowerCase()==="a"&&jl(e,t)}function d8(){const n=ze();en(k1(n.select(0,n.getChildrenSize())))}function ra(n,e){n.__lexicalClassNameCache===void 0&&(n.__lexicalClassNameCache={});const t=n.__lexicalClassNameCache,r=t[e];if(r!==void 0)return r;const i=n[e];if(typeof i=="string"){const s=Ph(i);return t[e]=s,s}return i}function A1(n,e,t,r,i){if(t.size===0)return;const s=r.__type,o=r.__key,l=e.get(s);l===void 0&&ue(33,s);const a=l.klass;let c=n.get(a);c===void 0&&(c=new Map,n.set(a,c));const u=c.get(o),h=u==="destroyed"&&i==="created";(u===void 0||h)&&c.set(o,h?"updated":i)}function Ix(n,e,t){const r=n.getParent();let i=t,s=n;return r!==null&&(e&&t===0?(i=s.getIndexWithinParent(),s=r):e||t!==s.getChildrenSize()||(i=s.getIndexWithinParent()+1,s=r)),s.getChildAtIndex(e?i-1:i)}function Ca(n,e){const t=n.offset;if(n.type==="element")return Ix(n.getNode(),e,t);{const r=n.getNode();if(e&&t===0||!e&&t===r.getTextContentSize()){const i=e?r.getPreviousSibling():r.getNextSibling();return i===null?Ix(r.getParentOrThrow(),e,r.getIndexWithinParent()+(e?0:1)):i}}return null}function VC(n){const e=td(n).event,t=e&&e.inputType;return t==="insertFromPaste"||t==="insertFromPasteAsQuotation"}function ge(n,e,t){return l2(n,e,t)}function Jf(n){return!Ht(n)&&!n.isLastChild()&&!n.isInline()}function $h(n,e){const t=n._keyToDOMMap.get(e);return t===void 0&&ue(75,e),t}function ed(n){const e=n.assignedSlot||n.parentElement;return e!==null&&e.nodeType===11?e.host:e}function Ng(n,e){let t=n.getParent();for(;t!==null;){if(t.is(e))return!0;t=t.getParent()}return!1}function td(n){const e=n._window;return e===null&&ue(78),e}function p8(n){let e=n.getParentOrThrow();for(;e!==null;){if(Qt(e))return e;e=e.getParentOrThrow()}return e}function Qt(n){return Ht(n)||z(n)&&n.isShadowRoot()}function g8(n){const e=n.constructor.clone(n);return QC(e,null),e}function Zn(n){const e=pt(),t=n.constructor.getType(),r=e._nodes.get(t);r===void 0&&ue(97);const i=r.replace;if(i!==null){const s=i(n);return s instanceof n.constructor||ue(98),s}return n}function op(n,e){!Ht(n.getParent())||z(e)||Xe(e)||ue(99)}function lp(n){return(Xe(n)||z(n)&&!n.canBeEmpty())&&!n.isInline()}function Q1(n,e,t){t.style.removeProperty("caret-color"),e._blockCursorElement=null;const r=n.parentElement;r!==null&&r.removeChild(n)}function m8(n,e,t){let r=n._blockCursorElement;if(U(t)&&t.isCollapsed()&&t.anchor.type==="element"&&e.contains(document.activeElement)){const i=t.anchor,s=i.getNode(),o=i.offset;let l=!1,a=null;if(o===s.getChildrenSize())lp(s.getChildAtIndex(o-1))&&(l=!0);else{const c=s.getChildAtIndex(o);if(lp(c)){const u=c.getPreviousSibling();(u===null||lp(u))&&(l=!0,a=n.getElementByKey(c.__key))}}if(l){const c=n.getElementByKey(s.__key);return r===null&&(n._blockCursorElement=r=function(u){const h=u.theme,f=document.createElement("div");f.contentEditable="false",f.setAttribute("data-lexical-cursor","true");let d=h.blockCursor;if(d!==void 0){if(typeof d=="string"){const p=Ph(d);d=h.blockCursor=p}d!==void 0&&f.classList.add(...d)}return f}(n._config)),e.style.caretColor="transparent",void(a===null?c.appendChild(r):c.insertBefore(r,a))}}r!==null&&Q1(r,n,e)}function Xr(n){return br?(n||window).getSelection():null}function O8(n,e){let t=n.getChildAtIndex(e);t==null&&(t=n),Qt(n)&&ue(102);const r=o=>{const l=o.getParentOrThrow(),a=Qt(l),c=o!==t||a?g8(o):o;if(a)return z(o)&&z(c)||ue(133),o.insertAfter(c),[o,c,c];{const[u,h,f]=r(l),d=o.getNextSiblings();return f.append(c,...d),[u,h,c]}},[i,s]=r(t);return[i,s]}function b8(n){return ur(n)&&n.tagName==="A"}function ur(n){return n.nodeType===1}function Vg(n){const e=new RegExp(/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var|#text)$/,"i");return n.nodeName.match(e)!==null}function Ah(n){const e=new RegExp(/^(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hr|li|main|nav|noscript|ol|p|pre|section|table|td|tfoot|ul|video)$/,"i");return n.nodeName.match(e)!==null}function co(n){if(Ht(n)||Xe(n)&&!n.isInline())return!0;if(!z(n)||Qt(n))return!1;const e=n.getFirstChild(),t=e===null||fi(e)||oe(e)||e.isInline();return!n.isInline()&&n.canBeEmpty()!==!1&&t}function ap(n,e){let t=n;for(;t!==null&&t.getParent()!==null&&!e(t);)t=t.getParentOrThrow();return e(t)?t:null}function x8(){return pt()}const Dx=new WeakMap,y8=new Map;function v8(n){if(!n._readOnly&&n.isEmpty())return y8;n._readOnly||ue(192);let e=Dx.get(n);if(!e){e=new Map,Dx.set(n,e);for(const[t,r]of n._nodeMap){const i=r.__type;let s=e.get(i);s||(s=new Map,e.set(i,s)),s.set(t,r)}}return e}function R1(n){const e=n.constructor.clone(n);return e.afterCloneFrom(n),e}function ZC(n,e,t,r,i,s){let o=n.getFirstChild();for(;o!==null;){const l=o.__key;o.__parent===e&&(z(o)&&ZC(o,l,t,r,i,s),t.has(l)||s.delete(l),i.push(l)),o=o.getNextSibling()}}let Gi,an,_a,nd,Zg,Bg,Ls,ar,Fg,Pa,At="",ln="",Er=null,rr="",si="",BC=!1,Ta=!1,eh=null;function Qh(n,e){const t=Ls.get(n);if(e!==null){const r=Xg(n);r.parentNode===e&&e.removeChild(r)}if(ar.has(n)||an._keyToDOMMap.delete(n),z(t)){const r=Mh(t,Ls);zg(r,0,r.length-1,null)}t!==void 0&&A1(Pa,_a,nd,t,"destroyed")}function zg(n,e,t,r){let i=e;for(;i<=t;++i){const s=n[i];s!==void 0&&Qh(s,r)}}function xs(n,e){n.setProperty("text-align",e)}const w8="40px";function FC(n,e){const t=Gi.theme.indent;if(typeof t=="string"){const i=n.classList.contains(t);e>0&&!i?n.classList.add(t):e<1&&i&&n.classList.remove(t)}const r=getComputedStyle(n).getPropertyValue("--lexical-indent-base-value")||w8;n.style.setProperty("padding-inline-start",e===0?"":`calc(${e} * ${r})`)}function zC(n,e){const t=n.style;e===0?xs(t,""):e===O1?xs(t,"left"):e===b1?xs(t,"center"):e===x1?xs(t,"right"):e===y1?xs(t,"justify"):e===v1?xs(t,"start"):e===w1&&xs(t,"end")}function Rh(n,e,t){const r=ar.get(n);r===void 0&&ue(60);const i=r.createDOM(Gi,an);if(function(s,o,l){const a=l._keyToDOMMap;o["__lexicalKey_"+l._key]=s,a.set(s,o)}(n,i,an),oe(r)?i.setAttribute("data-lexical-text","true"):Xe(r)&&i.setAttribute("data-lexical-decorator","true"),z(r)){const s=r.__indent,o=r.__size;if(s!==0&&FC(i,s),o!==0){const a=o-1;(function(c,u,h,f){const d=ln;ln="",jg(c,h,0,u,f,null),XC(h,f),ln=d})(Mh(r,ar),a,r,i)}const l=r.__format;l!==0&&zC(i,l),r.isInline()||jC(null,r,i),Jf(r)&&(At+=mi,si+=mi)}else{const s=r.getTextContent();if(Xe(r)){const o=r.decorate(an,Gi);o!==null&&qC(n,o),i.contentEditable="false"}else oe(r)&&(r.isDirectionless()||(ln+=s));At+=s,si+=s}if(e!==null)if(t!=null)e.insertBefore(i,t);else{const s=e.__lexicalLineBreak;s!=null?e.insertBefore(i,s):e.appendChild(i)}return A1(Pa,_a,nd,r,"created"),i}function jg(n,e,t,r,i,s){const o=At;At="";let l=t;for(;l<=r;++l){Rh(n[l],i,s);const a=ar.get(n[l]);a!==null&&oe(a)&&(Er===null&&(Er=a.getFormat()),rr===""&&(rr=a.getStyle()))}Jf(e)&&(At+=mi),i.__lexicalTextContent=At,At=o+At}function Nx(n,e){const t=e.get(n);return fi(t)||Xe(t)&&t.isInline()}function jC(n,e,t){const r=n!==null&&(n.__size===0||Nx(n.__last,Ls)),i=e.__size===0||Nx(e.__last,ar);if(r){if(!i){const s=t.__lexicalLineBreak;if(s!=null)try{t.removeChild(s)}catch(o){if(typeof o=="object"&&o!=null){const l=`${o.toString()} Parent: ${t.tagName}, child: ${s.tagName}.`;throw new Error(l)}throw o}t.__lexicalLineBreak=null}}else if(i){const s=document.createElement("br");t.__lexicalLineBreak=s,t.appendChild(s)}}function XC(n,e){const t=e.__lexicalDirTextContent,r=e.__lexicalDir;if(t!==ln||r!==eh){const s=ln==="",o=s?eh:(i=ln,K7.test(i)?"rtl":J7.test(i)?"ltr":null);if(o!==r){const l=e.classList,a=Gi.theme;let c=r!==null?a[r]:void 0,u=o!==null?a[o]:void 0;if(c!==void 0){if(typeof c=="string"){const h=Ph(c);c=a[r]=h}l.remove(...c)}if(o===null||s&&o==="ltr")e.removeAttribute("dir");else{if(u!==void 0){if(typeof u=="string"){const h=Ph(u);u=a[o]=h}u!==void 0&&l.add(...u)}e.dir=o}Ta||(n.getWritable().__dir=o)}eh=o,e.__lexicalDirTextContent=ln,e.__lexicalDir=o}var i}function S8(n,e,t){const r=ln;var i;ln="",Er=null,rr="",function(s,o,l){const a=At,c=s.__size,u=o.__size;if(At="",c===1&&u===1){const h=s.__first,f=o.__first;if(h===f)Xl(h,l);else{const p=Xg(h),g=Rh(f,null,null);try{l.replaceChild(g,p)}catch(m){if(typeof m=="object"&&m!=null){const b=`${m.toString()} Parent: ${l.tagName}, new child: {tag: ${g.tagName} key: ${f}}, old child: {tag: ${p.tagName}, key: ${h}}.`;throw new Error(b)}throw m}Qh(h,null)}const d=ar.get(f);oe(d)&&(Er===null&&(Er=d.getFormat()),rr===""&&(rr=d.getStyle()))}else{const h=Mh(s,Ls),f=Mh(o,ar);if(c===0)u!==0&&jg(f,o,0,u-1,l,null);else if(u===0){if(c!==0){const d=l.__lexicalLineBreak==null;zg(h,0,c-1,d?null:l),d&&(l.textContent="")}}else(function(d,p,g,m,b,O){const x=m-1,y=b-1;let v,C,S=(T=O,T.firstChild),_=0,P=0;for(var T;_<=x&&P<=y;){const D=p[_],N=g[P];if(D===N)S=cp(Xl(N,O)),_++,P++;else{v===void 0&&(v=new Set(p)),C===void 0&&(C=new Set(g));const H=C.has(D),X=v.has(N);if(H)if(X){const Y=$h(an,N);Y===S?S=cp(Xl(N,O)):(S!=null?O.insertBefore(Y,S):O.appendChild(Y),Xl(N,O)),_++,P++}else Rh(N,O,S),P++;else S=cp(Xg(D)),Qh(D,O),_++}const Z=ar.get(N);Z!==null&&oe(Z)&&(Er===null&&(Er=Z.getFormat()),rr===""&&(rr=Z.getStyle()))}const M=_>x,Q=P>y;if(M&&!Q){const D=g[y+1];jg(g,d,P,y,O,D===void 0?null:an.getElementByKey(D))}else Q&&!M&&zg(p,_,x,O)})(o,h,f,c,u,l)}Jf(o)&&(At+=mi),l.__lexicalTextContent=At,At=a+At}(n,e,t),XC(e,t),No(i=e)&&Er!=null&&Er!==i.__textFormat&&!Ta&&(i.setTextFormat(Er),i.setTextStyle(rr)),function(s){No(s)&&rr!==""&&rr!==s.__textStyle&&!Ta&&s.setTextStyle(rr)}(e),ln=r}function Mh(n,e){const t=[];let r=n.__first;for(;r!==null;){const i=e.get(r);i===void 0&&ue(101),t.push(r),r=i.__next}return t}function Xl(n,e){const t=Ls.get(n);let r=ar.get(n);t!==void 0&&r!==void 0||ue(61);const i=BC||Bg.has(n)||Zg.has(n),s=$h(an,n);if(t===r&&!i){if(z(t)){const o=s.__lexicalTextContent;o!==void 0&&(At+=o,si+=o);const l=s.__lexicalDirTextContent;l!==void 0&&(ln+=l)}else{const o=t.getTextContent();oe(t)&&!t.isDirectionless()&&(ln+=o),si+=o,At+=o}return s}if(t!==r&&i&&A1(Pa,_a,nd,r,"updated"),r.updateDOM(t,s,Gi)){const o=Rh(n,null,null);return e===null&&ue(62),e.replaceChild(o,s),Qh(n,null),o}if(z(t)&&z(r)){const o=r.__indent;o!==t.__indent&&FC(s,o);const l=r.__format;l!==t.__format&&zC(s,l),i&&(S8(t,r,s),Ht(r)||r.isInline()||jC(t,r,s)),Jf(r)&&(At+=mi,si+=mi)}else{const o=r.getTextContent();if(Xe(r)){const l=r.decorate(an,Gi);l!==null&&qC(n,l)}else oe(r)&&!r.isDirectionless()&&(ln+=o);At+=o,si+=o}if(!Ta&&Ht(r)&&r.__cachedText!==si){const o=r.getWritable();o.__cachedText=si,r=o}return s}function qC(n,e){let t=an._pendingDecorators;const r=an._decorators;if(t===null){if(r[n]===e)return;t=MC(an)}t[n]=e}function cp(n){let e=n.nextSibling;return e!==null&&e===an._blockCursorElement&&(e=e.nextSibling),e}function k8(n,e,t,r,i,s){At="",si="",ln="",BC=r===Do,eh=null,an=t,Gi=t._config,_a=t._nodes,nd=an._listeners.mutation,Zg=i,Bg=s,Ls=n._nodeMap,ar=e._nodeMap,Ta=e._readOnly,Fg=new Map(t._keyToDOMMap);const o=new Map;return Pa=o,Xl("root",null),an=void 0,_a=void 0,Zg=void 0,Bg=void 0,Ls=void 0,ar=void 0,Gi=void 0,Fg=void 0,Pa=void 0,o}function Xg(n){const e=Fg.get(n);return e===void 0&&ue(75,n),e}const ti=Object.freeze({}),qg=30,Wg=[["keydown",function(n,e){if(ia=n.timeStamp,WC=n.key,e.isComposing())return;const{key:t,shiftKey:r,ctrlKey:i,metaKey:s,altKey:o}=n;ge(e,r1,n)||t!=null&&(function(l,a,c,u){return Rx(l)&&!a&&!u&&!c}(t,i,o,s)?ge(e,yC,n):function(l,a,c,u,h){return Rx(l)&&!u&&!c&&(a||h)}(t,i,r,o,s)?ge(e,N7,n):function(l,a,c,u){return Qx(l)&&!a&&!u&&!c}(t,i,o,s)?ge(e,i1,n):function(l,a,c,u,h){return Qx(l)&&!u&&!c&&(a||h)}(t,i,r,o,s)?ge(e,V7,n):function(l,a,c){return function(u){return u==="ArrowUp"}(l)&&!a&&!c}(t,i,s)?ge(e,s1,n):function(l,a,c){return function(u){return u==="ArrowDown"}(l)&&!a&&!c}(t,i,s)?ge(e,o1,n):function(l,a){return Mx(l)&&a}(t,r)?(sa=!0,ge(e,Io,n)):function(l){return l===" "}(t)?ge(e,vC,n):function(l,a){return nr&&a&&l.toLowerCase()==="o"}(t,i)?(n.preventDefault(),sa=!0,ge(e,wo,!0)):function(l,a){return Mx(l)&&!a}(t,r)?(sa=!1,ge(e,Io,n)):function(l,a,c,u){return nr?!a&&!c&&(Pl(l)||l.toLowerCase()==="h"&&u):!(u||a||c)&&Pl(l)}(t,o,s,i)?Pl(t)?ge(e,qf,n):(n.preventDefault(),ge(e,$s,!0)):function(l){return l==="Escape"}(t)?ge(e,uc,n):function(l,a,c,u,h){return nr?!(c||u||h)&&(Tl(l)||l.toLowerCase()==="d"&&a):!(a||u||h)&&Tl(l)}(t,i,r,o,s)?Tl(t)?ge(e,Wf,n):(n.preventDefault(),ge(e,$s,!1)):function(l,a,c){return Pl(l)&&(nr?a:c)}(t,o,i)?(n.preventDefault(),ge(e,Sa,!0)):function(l,a,c){return Tl(l)&&(nr?a:c)}(t,o,i)?(n.preventDefault(),ge(e,Sa,!1)):function(l,a){return nr&&a&&Pl(l)}(t,s)?(n.preventDefault(),ge(e,ka,!0)):function(l,a){return nr&&a&&Tl(l)}(t,s)?(n.preventDefault(),ge(e,ka,!1)):function(l,a,c,u){return l.toLowerCase()==="b"&&!a&&jl(c,u)}(t,o,s,i)?(n.preventDefault(),ge(e,ai,"bold")):function(l,a,c,u){return l.toLowerCase()==="u"&&!a&&jl(c,u)}(t,o,s,i)?(n.preventDefault(),ge(e,ai,"underline")):function(l,a,c,u){return l.toLowerCase()==="i"&&!a&&jl(c,u)}(t,o,s,i)?(n.preventDefault(),ge(e,ai,"italic")):function(l,a,c,u){return l==="Tab"&&!a&&!c&&!u}(t,o,i,s)?ge(e,l1,n):function(l,a,c,u){return l.toLowerCase()==="z"&&!a&&jl(c,u)}(t,r,s,i)?(n.preventDefault(),ge(e,jf,void 0)):function(l,a,c,u){return nr?l.toLowerCase()==="z"&&c&&a:l.toLowerCase()==="y"&&u||l.toLowerCase()==="z"&&u&&a}(t,r,s,i)?(n.preventDefault(),ge(e,Xf,void 0)):$t(e._editorState._selection)?function(l,a,c,u){return!a&&l.toLowerCase()==="c"&&(nr?c:u)}(t,r,s,i)?(n.preventDefault(),ge(e,Yf,n)):function(l,a,c,u){return!a&&l.toLowerCase()==="x"&&(nr?c:u)}(t,r,s,i)?(n.preventDefault(),ge(e,h1,n)):Lx(t,s,i)&&(n.preventDefault(),ge(e,Lg,n)):!Wi&&Lx(t,s,i)&&(n.preventDefault(),ge(e,Lg,n)),function(l,a,c,u){return l||a||c||u}(i,r,o,s)&&ge(e,SC,n))}],["pointerdown",function(n,e){const t=n.target,r=n.pointerType;t instanceof Node&&r!=="touch"&&An(e,()=>{Xe(jr(t))||(Yg=!0)})}],["compositionstart",function(n,e){An(e,()=>{const t=le();if(U(t)&&!e.isComposing()){const r=t.anchor,i=t.anchor.getNode();zt(r.key),(n.timeStamp{up(e,n.data)})}],["input",function(n,e){n.stopPropagation(),An(e,()=>{const t=le(),r=n.data,i=GC(n);if(r!=null&&U(t)&&UC(t,i,r,n.timeStamp,!1)){El&&(up(e,r),El=!1);const s=t.anchor.getNode(),o=Xr(e._window);if(o===null)return;const l=t.isBackward(),a=l?t.anchor.offset:t.focus.offset,c=l?t.focus.offset:t.anchor.offset;kh&&!t.isCollapsed()&&oe(s)&&o.anchorNode!==null&&s.getTextContent().slice(0,a)+r+s.getTextContent().slice(a+c)===NC(o.anchorNode)||ge(e,So,r);const u=r.length;Wi&&u>1&&n.inputType==="insertCompositionText"&&!e.isComposing()&&(t.anchor.offset-=u),p1||Uf||g1||!e.isComposing()||(ia=0,zt(null))}else E1(!1,e,r!==null?r:void 0),El&&(up(e,r||void 0),El=!1);bn(),EC(pt())}),uo=null}],["click",function(n,e){An(e,()=>{const t=le(),r=Xr(e._window),i=ol();if(r){if(U(t)){const s=t.anchor,o=s.getNode();s.type==="element"&&s.offset===0&&t.isCollapsed()&&!Ht(o)&&ze().getChildrenSize()===1&&o.getTopLevelElementOrThrow().isEmpty()&&i!==null&&t.is(i)?(r.removeAllRanges(),t.dirty=!0):n.detail===3&&!t.isCollapsed()&&o!==t.focus.getNode()&&(z(o)?o.select(0):o.getParentOrThrow().select(0))}else if(n.pointerType==="touch"){const s=r.anchorNode;if(s!==null){const o=s.nodeType;(o===hc||o===ls)&&en(I1(i,r,e,n))}}}ge(e,Ff,n)})}],["cut",ti],["copy",ti],["dragstart",ti],["dragover",ti],["dragend",ti],["paste",ti],["focus",ti],["blur",ti],["drop",ti]];kh&&Wg.push(["beforeinput",(n,e)=>function(t,r){const i=t.inputType,s=GC(t);i==="deleteCompositionText"||Wi&&VC(r)||i!=="insertCompositionText"&&An(r,()=>{const o=le();if(i==="deleteContentBackward"){if(o===null){const d=ol();if(!U(d))return;en(d.clone())}if(U(o)){const d=o.anchor.key===o.focus.key;if(l=t.timeStamp,WC==="MediaLast"&&l{An(r,()=>{zt(null)})},qg),U(o)){const p=o.anchor.getNode();p.markDirty(),o.format=p.getFormat(),oe(p)||ue(142),o.style=p.getStyle()}}else{zt(null),t.preventDefault();const p=o.anchor.getNode().getTextContent(),g=o.anchor.offset===0&&o.focus.offset===p.length;q7&&d&&!g||ge(r,$s,!0)}return}}var l;if(!U(o))return;const a=t.data;uo!==null&&E1(!1,r,uo),o.dirty&&uo===null||!o.isCollapsed()||Ht(o.anchor.getNode())||s===null||o.applyDOMRange(s),uo=null;const c=o.anchor,u=o.focus,h=c.getNode(),f=u.getNode();if(i!=="insertText"&&i!=="insertTranspose")switch(t.preventDefault(),i){case"insertFromYank":case"insertFromDrop":case"insertReplacementText":ge(r,So,t);break;case"insertFromComposition":zt(null),ge(r,So,t);break;case"insertLineBreak":zt(null),ge(r,wo,!1);break;case"insertParagraph":zt(null),sa&&!Uf?(sa=!1,ge(r,wo,!1)):ge(r,wa,void 0);break;case"insertFromPaste":case"insertFromPasteAsQuotation":ge(r,zf,t);break;case"deleteByComposition":(function(d,p){return d!==p||z(d)||z(p)||!d.isToken()||!p.isToken()})(h,f)&&ge(r,Rg,t);break;case"deleteByDrag":case"deleteByCut":ge(r,Rg,t);break;case"deleteContent":ge(r,$s,!1);break;case"deleteWordBackward":ge(r,Sa,!0);break;case"deleteWordForward":ge(r,Sa,!1);break;case"deleteHardLineBackward":case"deleteSoftLineBackward":ge(r,ka,!0);break;case"deleteContentForward":case"deleteHardLineForward":case"deleteSoftLineForward":ge(r,ka,!1);break;case"formatStrikeThrough":ge(r,ai,"strikethrough");break;case"formatBold":ge(r,ai,"bold");break;case"formatItalic":ge(r,ai,"italic");break;case"formatUnderline":ge(r,ai,"underline");break;case"historyUndo":ge(r,jf,void 0);break;case"historyRedo":ge(r,Xf,void 0)}else{if(a===` `)t.preventDefault(),ge(r,wo,!1);else if(a===mi)t.preventDefault(),ge(r,wa,void 0);else if(a==null&&t.dataTransfer){const d=t.dataTransfer.getData("text/plain");t.preventDefault(),o.insertRawText(d)}else a!=null&&UC(o,s,a,t.timeStamp,!0)?(t.preventDefault(),ge(r,So,a)):uo=a;HC=t.timeStamp}})}(n,e)]);let ia=0,WC=null,HC=0,uo=null;const Lh=new WeakMap;let Hg=!1,Yg=!1,sa=!1,El=!1,YC=[0,"",0,"root",0];function UC(n,e,t,r,i){const s=n.anchor,o=n.focus,l=s.getNode(),a=pt(),c=Xr(a._window),u=c!==null?c.anchorNode:null,h=s.key,f=a.getElementByKey(h),d=t.length;return h!==o.key||!oe(l)||(!i&&(!kh||HC1||(i||!kh)&&f!==null&&!l.isComposing()&&u!==Th(f)||c!==null&&e!==null&&(!e.collapsed||e.startContainer!==c.anchorNode||e.startOffset!==c.anchorOffset)||l.getFormat()!==n.format||l.getStyle()!==n.style||f8(n,l)}function Vx(n,e){return n!==null&&n.nodeValue!==null&&n.nodeType===ls&&e!==0&&e!==n.nodeValue.length}function Zx(n,e,t){const{anchorNode:r,anchorOffset:i,focusNode:s,focusOffset:o}=n;Hg&&(Hg=!1,Vx(r,i)&&Vx(s,o))||An(e,()=>{if(!t)return void en(null);if(!fc(e,r,s))return;const l=le();if(U(l)){const a=l.anchor,c=a.getNode();if(l.isCollapsed()){n.type==="Range"&&n.anchorNode===n.focusNode&&(l.dirty=!0);const u=td(e).event,h=u?u.timeStamp:performance.now(),[f,d,p,g,m]=YC,b=ze(),O=e.isComposing()===!1&&b.getTextContent()==="";if(h ); } -`,nG={defaultPreset:"react",presets:[{name:"react",meta:"live react",label:"React",sandpackTemplate:"react",sandpackTheme:"light",snippetFileName:"/App.js",snippetLanguage:"jsx",initialSnippetContent:tG}]},YA=be(nG),rG=gt(n=>{n.link(n.pipe(rG,ct(YA),ui(([e,t])=>{const r=e?t.presets.find(i=>i.name===e):t.presets.find(i=>i.name==t.defaultPreset);if(!r)throw new Error(`No sandpack preset found with name ${e}`);return{code:r.initialSnippetContent??"",language:r.snippetLanguage??"jsx",meta:r.meta}})),Md)});function j(n){return new Yo(Pb.define(n))}function $i(n){return V(()=>import("./index-BRP0rdCl.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>e.sql({dialect:e[n]}))}const iG=[I.of({name:"C",extensions:["c","h","ino"],load(){return V(()=>import("./index-CnStXQ1G.js"),__vite__mapDeps([7,1,2,3,4,5,6])).then(n=>n.cpp())}}),I.of({name:"C++",alias:["cpp"],extensions:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],load(){return V(()=>import("./index-CnStXQ1G.js"),__vite__mapDeps([7,1,2,3,4,5,6])).then(n=>n.cpp())}}),I.of({name:"CQL",alias:["cassandra"],extensions:["cql"],load(){return $i("Cassandra")}}),I.of({name:"CSS",extensions:["css"],load(){return V(()=>Promise.resolve().then(()=>kY),void 0).then(n=>n.css())}}),I.of({name:"Go",extensions:["go"],load(){return V(()=>import("./index-jRjoKnSb.js"),__vite__mapDeps([8,1,2,3,4,5,6])).then(n=>n.go())}}),I.of({name:"HTML",alias:["xhtml"],extensions:["html","htm","handlebars","hbs"],load(){return V(()=>Promise.resolve().then(()=>JU),void 0).then(n=>n.html())}}),I.of({name:"Java",extensions:["java"],load(){return V(()=>import("./index-Br-i5CyM.js"),__vite__mapDeps([9,1,2,3,4,5,6])).then(n=>n.java())}}),I.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return V(()=>Promise.resolve().then(()=>Zu),void 0).then(n=>n.javascript())}}),I.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return V(()=>import("./index-BN-uPEw0.js"),__vite__mapDeps([10,1,2,3,4,5,6])).then(n=>n.json())}}),I.of({name:"JSX",extensions:["jsx"],load(){return V(()=>Promise.resolve().then(()=>Zu),void 0).then(n=>n.javascript({jsx:!0}))}}),I.of({name:"LESS",extensions:["less"],load(){return V(()=>import("./index-DXK7-roO.js"),__vite__mapDeps([11,1,2,3,4,5,6])).then(n=>n.less())}}),I.of({name:"Liquid",extensions:["liquid"],load(){return V(()=>import("./index-DU_L3lXF.js"),__vite__mapDeps([12,1,2,3,4,5,6])).then(n=>n.liquid())}}),I.of({name:"MariaDB SQL",load(){return $i("MariaSQL")}}),I.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return V(()=>Promise.resolve().then(()=>gee),void 0).then(n=>n.markdown())}}),I.of({name:"MS SQL",load(){return $i("MSSQL")}}),I.of({name:"MySQL",load(){return $i("MySQL")}}),I.of({name:"PHP",extensions:["php","php3","php4","php5","php7","phtml"],load(){return V(()=>import("./index-CRlmaQeU.js"),__vite__mapDeps([13,1,2,3,4,5,6])).then(n=>n.php())}}),I.of({name:"PLSQL",extensions:["pls"],load(){return $i("PLSQL")}}),I.of({name:"PostgreSQL",load(){return $i("PostgreSQL")}}),I.of({name:"Python",extensions:["BUILD","bzl","py","pyw"],filename:/^(BUCK|BUILD)$/,load(){return V(()=>import("./index-DC1Fb-7Y.js"),__vite__mapDeps([14,1,2,3,4,5,6])).then(n=>n.python())}}),I.of({name:"Rust",extensions:["rs"],load(){return V(()=>import("./index-C2wvX7We.js"),__vite__mapDeps([15,1,2,3,4,5,6])).then(n=>n.rust())}}),I.of({name:"Sass",extensions:["sass"],load(){return V(()=>import("./index-D2BcTF5n.js"),__vite__mapDeps([16,1,2,3,4,5,6])).then(n=>n.sass({indented:!0}))}}),I.of({name:"SCSS",extensions:["scss"],load(){return V(()=>import("./index-D2BcTF5n.js"),__vite__mapDeps([16,1,2,3,4,5,6])).then(n=>n.sass())}}),I.of({name:"SQL",extensions:["sql"],load(){return $i("StandardSQL")}}),I.of({name:"SQLite",load(){return $i("SQLite")}}),I.of({name:"TSX",extensions:["tsx"],load(){return V(()=>Promise.resolve().then(()=>Zu),void 0).then(n=>n.javascript({jsx:!0,typescript:!0}))}}),I.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return V(()=>Promise.resolve().then(()=>Zu),void 0).then(n=>n.javascript({typescript:!0}))}}),I.of({name:"WebAssembly",extensions:["wat","wast"],load(){return V(()=>import("./index-B4L7DgZe.js"),__vite__mapDeps([17,1,2,3,4,5,6])).then(n=>n.wast())}}),I.of({name:"XML",alias:["rss","wsdl","xsd"],extensions:["xml","xsl","xsd","svg"],load(){return V(()=>import("./index-DWGivvfr.js"),__vite__mapDeps([18,1,2,3,4,5,6])).then(n=>n.xml())}}),I.of({name:"YAML",alias:["yml"],extensions:["yaml","yml"],load(){return V(()=>import("./index-BD1OjTxN.js"),__vite__mapDeps([19,1,2,3,4,5,6])).then(n=>n.yaml())}}),I.of({name:"APL",extensions:["dyalog","apl"],load(){return V(()=>import("./apl-B4CMkyY2.js"),[]).then(n=>j(n.apl))}}),I.of({name:"PGP",alias:["asciiarmor"],extensions:["asc","pgp","sig"],load(){return V(()=>import("./asciiarmor-Df11BRmG.js"),[]).then(n=>j(n.asciiArmor))}}),I.of({name:"ASN.1",extensions:["asn","asn1"],load(){return V(()=>import("./asn1-CGOzndHr.js"),[]).then(n=>j(n.asn1({})))}}),I.of({name:"Asterisk",filename:/^extensions\.conf$/i,load(){return V(()=>import("./asterisk-B-8jnY81.js"),[]).then(n=>j(n.asterisk))}}),I.of({name:"Brainfuck",extensions:["b","bf"],load(){return V(()=>import("./brainfuck-C4LP7Hcl.js"),[]).then(n=>j(n.brainfuck))}}),I.of({name:"Cobol",extensions:["cob","cpy"],load(){return V(()=>import("./cobol-XrqhtCFE.js"),[]).then(n=>j(n.cobol))}}),I.of({name:"C#",alias:["csharp","cs"],extensions:["cs"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.csharp))}}),I.of({name:"Clojure",extensions:["clj","cljc","cljx"],load(){return V(()=>import("./clojure-BMjYHr_A.js"),[]).then(n=>j(n.clojure))}}),I.of({name:"ClojureScript",extensions:["cljs"],load(){return V(()=>import("./clojure-BMjYHr_A.js"),[]).then(n=>j(n.clojure))}}),I.of({name:"Closure Stylesheets (GSS)",extensions:["gss"],load(){return V(()=>import("./css-BnMrqG3P.js"),[]).then(n=>j(n.gss))}}),I.of({name:"CMake",extensions:["cmake","cmake.in"],filename:/^CMakeLists\.txt$/,load(){return V(()=>import("./cmake-BQqOBYOt.js"),[]).then(n=>j(n.cmake))}}),I.of({name:"CoffeeScript",alias:["coffee","coffee-script"],extensions:["coffee"],load(){return V(()=>import("./coffeescript-S37ZYGWr.js"),[]).then(n=>j(n.coffeeScript))}}),I.of({name:"Common Lisp",alias:["lisp"],extensions:["cl","lisp","el"],load(){return V(()=>import("./commonlisp-DBKNyK5s.js"),[]).then(n=>j(n.commonLisp))}}),I.of({name:"Cypher",extensions:["cyp","cypher"],load(){return V(()=>import("./cypher-C_CwsFkJ.js"),[]).then(n=>j(n.cypher))}}),I.of({name:"Cython",extensions:["pyx","pxd","pxi"],load(){return V(()=>import("./python-BuPzkPfP.js"),[]).then(n=>j(n.cython))}}),I.of({name:"Crystal",extensions:["cr"],load(){return V(()=>import("./crystal-SjHAIU92.js"),[]).then(n=>j(n.crystal))}}),I.of({name:"D",extensions:["d"],load(){return V(()=>import("./d-pRatUO7H.js"),[]).then(n=>j(n.d))}}),I.of({name:"Dart",extensions:["dart"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.dart))}}),I.of({name:"diff",extensions:["diff","patch"],load(){return V(()=>import("./diff-DbItnlRl.js"),[]).then(n=>j(n.diff))}}),I.of({name:"Dockerfile",filename:/^Dockerfile$/,load(){return V(()=>import("./dockerfile-BuNIbK2j.js"),__vite__mapDeps([20,21])).then(n=>j(n.dockerFile))}}),I.of({name:"DTD",extensions:["dtd"],load(){return V(()=>import("./dtd-DF_7sFjM.js"),[]).then(n=>j(n.dtd))}}),I.of({name:"Dylan",extensions:["dylan","dyl","intr"],load(){return V(()=>import("./dylan-DwRh75JA.js"),[]).then(n=>j(n.dylan))}}),I.of({name:"EBNF",load(){return V(()=>import("./ebnf-CDyGwa7X.js"),[]).then(n=>j(n.ebnf))}}),I.of({name:"ECL",extensions:["ecl"],load(){return V(()=>import("./ecl-Cabwm37j.js"),[]).then(n=>j(n.ecl))}}),I.of({name:"edn",extensions:["edn"],load(){return V(()=>import("./clojure-BMjYHr_A.js"),[]).then(n=>j(n.clojure))}}),I.of({name:"Eiffel",extensions:["e"],load(){return V(()=>import("./eiffel-CnydiIhH.js"),[]).then(n=>j(n.eiffel))}}),I.of({name:"Elm",extensions:["elm"],load(){return V(()=>import("./elm-vLlmbW-K.js"),[]).then(n=>j(n.elm))}}),I.of({name:"Erlang",extensions:["erl"],load(){return V(()=>import("./erlang-BNw1qcRV.js"),[]).then(n=>j(n.erlang))}}),I.of({name:"Esper",load(){return V(()=>import("./sql-C4g8LzGK.js"),[]).then(n=>j(n.esper))}}),I.of({name:"Factor",extensions:["factor"],load(){return V(()=>import("./factor-D8pE9siL.js"),__vite__mapDeps([22,21])).then(n=>j(n.factor))}}),I.of({name:"FCL",load(){return V(()=>import("./fcl-Kvtd6kyn.js"),[]).then(n=>j(n.fcl))}}),I.of({name:"Forth",extensions:["forth","fth","4th"],load(){return V(()=>import("./forth-Ffai-XNe.js"),[]).then(n=>j(n.forth))}}),I.of({name:"Fortran",extensions:["f","for","f77","f90","f95"],load(){return V(()=>import("./fortran-DYz_wnZ1.js"),[]).then(n=>j(n.fortran))}}),I.of({name:"F#",alias:["fsharp"],extensions:["fs"],load(){return V(()=>import("./mllike-C_8OmSiT.js"),[]).then(n=>j(n.fSharp))}}),I.of({name:"Gas",extensions:["s"],load(){return V(()=>import("./gas-Bneqetm1.js"),[]).then(n=>j(n.gas))}}),I.of({name:"Gherkin",extensions:["feature"],load(){return V(()=>import("./gherkin-heZmZLOM.js"),[]).then(n=>j(n.gherkin))}}),I.of({name:"Groovy",extensions:["groovy","gradle"],filename:/^Jenkinsfile$/,load(){return V(()=>import("./groovy-DKLxxR9y.js"),[]).then(n=>j(n.groovy))}}),I.of({name:"Haskell",extensions:["hs"],load(){return V(()=>import("./haskell-BWDZoCOh.js"),[]).then(n=>j(n.haskell))}}),I.of({name:"Haxe",extensions:["hx"],load(){return V(()=>import("./haxe-pv4rovob.js"),[]).then(n=>j(n.haxe))}}),I.of({name:"HXML",extensions:["hxml"],load(){return V(()=>import("./haxe-pv4rovob.js"),[]).then(n=>j(n.hxml))}}),I.of({name:"HTTP",load(){return V(()=>import("./http-DBlCnlav.js"),[]).then(n=>j(n.http))}}),I.of({name:"IDL",extensions:["pro"],load(){return V(()=>import("./idl-BEugSyMb.js"),[]).then(n=>j(n.idl))}}),I.of({name:"JSON-LD",alias:["jsonld"],extensions:["jsonld"],load(){return V(()=>import("./javascript-iSgyE4tI.js"),[]).then(n=>j(n.jsonld))}}),I.of({name:"Jinja2",extensions:["j2","jinja","jinja2"],load(){return V(()=>import("./jinja2-C4DGRd-O.js"),[]).then(n=>j(n.jinja2))}}),I.of({name:"Julia",extensions:["jl"],load(){return V(()=>import("./julia-DuME0IfC.js"),[]).then(n=>j(n.julia))}}),I.of({name:"Kotlin",extensions:["kt","kts"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.kotlin))}}),I.of({name:"LiveScript",alias:["ls"],extensions:["ls"],load(){return V(()=>import("./livescript-k3uCVVjK.js"),[]).then(n=>j(n.liveScript))}}),I.of({name:"Lua",extensions:["lua"],load(){return V(()=>import("./lua-BgMRiT3U.js"),[]).then(n=>j(n.lua))}}),I.of({name:"mIRC",extensions:["mrc"],load(){return V(()=>import("./mirc-CjQqDB4T.js"),[]).then(n=>j(n.mirc))}}),I.of({name:"Mathematica",extensions:["m","nb","wl","wls"],load(){return V(()=>import("./mathematica-DTrFuWx2.js"),[]).then(n=>j(n.mathematica))}}),I.of({name:"Modelica",extensions:["mo"],load(){return V(()=>import("./modelica-Dc1JOy9r.js"),[]).then(n=>j(n.modelica))}}),I.of({name:"MUMPS",extensions:["mps"],load(){return V(()=>import("./mumps-BT43cFF4.js"),[]).then(n=>j(n.mumps))}}),I.of({name:"Mbox",extensions:["mbox"],load(){return V(()=>import("./mbox-CNhZ1qSd.js"),[]).then(n=>j(n.mbox))}}),I.of({name:"Nginx",filename:/nginx.*\.conf$/i,load(){return V(()=>import("./nginx-DdIZxoE0.js"),[]).then(n=>j(n.nginx))}}),I.of({name:"NSIS",extensions:["nsh","nsi"],load(){return V(()=>import("./nsis-CEAdamBV.js"),__vite__mapDeps([23,21])).then(n=>j(n.nsis))}}),I.of({name:"NTriples",extensions:["nt","nq"],load(){return V(()=>import("./ntriples-BfvgReVJ.js"),[]).then(n=>j(n.ntriples))}}),I.of({name:"Objective-C",alias:["objective-c","objc"],extensions:["m"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.objectiveC))}}),I.of({name:"Objective-C++",alias:["objective-c++","objc++"],extensions:["mm"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.objectiveCpp))}}),I.of({name:"OCaml",extensions:["ml","mli","mll","mly"],load(){return V(()=>import("./mllike-C_8OmSiT.js"),[]).then(n=>j(n.oCaml))}}),I.of({name:"Octave",extensions:["m"],load(){return V(()=>import("./octave-Ck1zUtKM.js"),[]).then(n=>j(n.octave))}}),I.of({name:"Oz",extensions:["oz"],load(){return V(()=>import("./oz-BzwKVEFT.js"),[]).then(n=>j(n.oz))}}),I.of({name:"Pascal",extensions:["p","pas"],load(){return V(()=>import("./pascal-B1wCu0_E.js"),[]).then(n=>j(n.pascal))}}),I.of({name:"Perl",extensions:["pl","pm"],load(){return V(()=>import("./perl-CdXCOZ3F.js"),[]).then(n=>j(n.perl))}}),I.of({name:"Pig",extensions:["pig"],load(){return V(()=>import("./pig-CevX1Tat.js"),[]).then(n=>j(n.pig))}}),I.of({name:"PowerShell",extensions:["ps1","psd1","psm1"],load(){return V(()=>import("./powershell-CFHJl5sT.js"),[]).then(n=>j(n.powerShell))}}),I.of({name:"Properties files",alias:["ini","properties"],extensions:["properties","ini","in"],load(){return V(()=>import("./properties-C78fOPTZ.js"),[]).then(n=>j(n.properties))}}),I.of({name:"ProtoBuf",extensions:["proto"],load(){return V(()=>import("./protobuf-ChK-085T.js"),[]).then(n=>j(n.protobuf))}}),I.of({name:"Pug",alias:["jade"],extensions:["pug","jade"],load(){return V(()=>import("./pug-BmUsPMDj.js"),__vite__mapDeps([24,25])).then(n=>j(n.pug))}}),I.of({name:"Puppet",extensions:["pp"],load(){return V(()=>import("./puppet-DMA9R1ak.js"),[]).then(n=>j(n.puppet))}}),I.of({name:"Q",extensions:["q"],load(){return V(()=>import("./q-ZnEupP5q.js"),[]).then(n=>j(n.q))}}),I.of({name:"R",alias:["rscript"],extensions:["r","R"],load(){return V(()=>import("./r-DUYO_cvP.js"),[]).then(n=>j(n.r))}}),I.of({name:"RPM Changes",load(){return V(()=>import("./rpm-CTu-6PCP.js"),[]).then(n=>j(n.rpmChanges))}}),I.of({name:"RPM Spec",extensions:["spec"],load(){return V(()=>import("./rpm-CTu-6PCP.js"),[]).then(n=>j(n.rpmSpec))}}),I.of({name:"Ruby",alias:["jruby","macruby","rake","rb","rbx"],extensions:["rb"],filename:/^(Gemfile|Rakefile)$/,load(){return V(()=>import("./ruby-B2Rjki9n.js"),[]).then(n=>j(n.ruby))}}),I.of({name:"SAS",extensions:["sas"],load(){return V(()=>import("./sas-B4kiWyti.js"),[]).then(n=>j(n.sas))}}),I.of({name:"Scala",extensions:["scala"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.scala))}}),I.of({name:"Scheme",extensions:["scm","ss"],load(){return V(()=>import("./scheme-C41bIUwD.js"),[]).then(n=>j(n.scheme))}}),I.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return V(()=>import("./shell-CjFT_Tl9.js"),[]).then(n=>j(n.shell))}}),I.of({name:"Sieve",extensions:["siv","sieve"],load(){return V(()=>import("./sieve-C3Gn_uJK.js"),[]).then(n=>j(n.sieve))}}),I.of({name:"Smalltalk",extensions:["st"],load(){return V(()=>import("./smalltalk-CnHTOXQT.js"),[]).then(n=>j(n.smalltalk))}}),I.of({name:"Solr",load(){return V(()=>import("./solr-DehyRSwq.js"),[]).then(n=>j(n.solr))}}),I.of({name:"SML",extensions:["sml","sig","fun","smackspec"],load(){return V(()=>import("./mllike-C_8OmSiT.js"),[]).then(n=>j(n.sml))}}),I.of({name:"SPARQL",alias:["sparul"],extensions:["rq","sparql"],load(){return V(()=>import("./sparql-DkYu6x3z.js"),[]).then(n=>j(n.sparql))}}),I.of({name:"Spreadsheet",alias:["excel","formula"],load(){return V(()=>import("./spreadsheet-BCZA_wO0.js"),[]).then(n=>j(n.spreadsheet))}}),I.of({name:"Squirrel",extensions:["nut"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.squirrel))}}),I.of({name:"Stylus",extensions:["styl"],load(){return V(()=>import("./stylus-BdAi1jBa.js"),[]).then(n=>j(n.stylus))}}),I.of({name:"Swift",extensions:["swift"],load(){return V(()=>import("./swift-BzpIVaGY.js"),[]).then(n=>j(n.swift))}}),I.of({name:"sTeX",load(){return V(()=>import("./stex-C3f8Ysf7.js"),[]).then(n=>j(n.stex))}}),I.of({name:"LaTeX",alias:["tex"],extensions:["text","ltx","tex"],load(){return V(()=>import("./stex-C3f8Ysf7.js"),[]).then(n=>j(n.stex))}}),I.of({name:"SystemVerilog",extensions:["v","sv","svh"],load(){return V(()=>import("./verilog-C6RDOZhf.js"),[]).then(n=>j(n.verilog))}}),I.of({name:"Tcl",extensions:["tcl"],load(){return V(()=>import("./tcl-DVfN8rqt.js"),[]).then(n=>j(n.tcl))}}),I.of({name:"Textile",extensions:["textile"],load(){return V(()=>import("./textile-CnDTJFAw.js"),[]).then(n=>j(n.textile))}}),I.of({name:"TiddlyWiki",load(){return V(()=>import("./tiddlywiki-DO-Gjzrf.js"),[]).then(n=>j(n.tiddlyWiki))}}),I.of({name:"Tiki wiki",load(){return V(()=>import("./tiki-DGYXhP31.js"),[]).then(n=>j(n.tiki))}}),I.of({name:"TOML",extensions:["toml"],load(){return V(()=>import("./toml-BXUEaScT.js"),[]).then(n=>j(n.toml))}}),I.of({name:"Troff",extensions:["1","2","3","4","5","6","7","8","9"],load(){return V(()=>import("./troff-wAsdV37c.js"),[]).then(n=>j(n.troff))}}),I.of({name:"TTCN",extensions:["ttcn","ttcn3","ttcnpp"],load(){return V(()=>import("./ttcn-CiGrtVSZ.js"),[]).then(n=>j(n.ttcn))}}),I.of({name:"TTCN_CFG",extensions:["cfg"],load(){return V(()=>import("./ttcn-cfg-BIkV9KBc.js"),[]).then(n=>j(n.ttcnCfg))}}),I.of({name:"Turtle",extensions:["ttl"],load(){return V(()=>import("./turtle-B1tBg_DP.js"),[]).then(n=>j(n.turtle))}}),I.of({name:"Web IDL",extensions:["webidl"],load(){return V(()=>import("./webidl-ZXfAyPTL.js"),[]).then(n=>j(n.webIDL))}}),I.of({name:"VB.NET",extensions:["vb"],load(){return V(()=>import("./vb-CmGdzxic.js"),[]).then(n=>j(n.vb))}}),I.of({name:"VBScript",extensions:["vbs"],load(){return V(()=>import("./vbscript-BuJXcnF6.js"),[]).then(n=>j(n.vbScript))}}),I.of({name:"Velocity",extensions:["vtl"],load(){return V(()=>import("./velocity-D8B20fx6.js"),[]).then(n=>j(n.velocity))}}),I.of({name:"Verilog",extensions:["v"],load(){return V(()=>import("./verilog-C6RDOZhf.js"),[]).then(n=>j(n.verilog))}}),I.of({name:"VHDL",extensions:["vhd","vhdl"],load(){return V(()=>import("./vhdl-lSbBsy5d.js"),[]).then(n=>j(n.vhdl))}}),I.of({name:"XQuery",extensions:["xy","xquery"],load(){return V(()=>import("./xquery-WRlm2TX8.js"),[]).then(n=>j(n.xQuery))}}),I.of({name:"Yacas",extensions:["ys"],load(){return V(()=>import("./yacas-BJ4BC0dw.js"),[]).then(n=>j(n.yacas))}}),I.of({name:"Z80",extensions:["z80"],load(){return V(()=>import("./z80-Hz9HOZM7.js"),[]).then(n=>j(n.z80))}}),I.of({name:"MscGen",extensions:["mscgen","mscin","msc"],load(){return V(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(n=>j(n.mscgen))}}),I.of({name:"Xù",extensions:["xu"],load(){return V(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(n=>j(n.xu))}}),I.of({name:"MsGenny",extensions:["msgenny"],load(){return V(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(n=>j(n.msgenny))}}),I.of({name:"Vue",extensions:["vue"],load(){return V(()=>import("./index-Czk6-ejp.js"),__vite__mapDeps([26,1,2,3,4,5,6])).then(n=>n.vue())}}),I.of({name:"Angular Template",load(){return V(()=>import("./index-CIykCf4V.js"),__vite__mapDeps([27,1,2,3,4,5,6])).then(n=>n.angular())}})],uk="#2e3440",Yb="#3b4252",hk="#434c5e",Bu="#4c566a",fk="#e5e9f0",AO="#eceff4",gg="#8fbcbb",dk="#88c0d0",sG="#81a1c1",tr="#5e81ac",oG="#bf616a",lo="#d08770",mg="#ebcb8b",pk="#a3be8c",lG="#b48ead",gk="#d30102",Ub=AO,Og=Ub,aG="#ffffff",bg=Yb,cG=Ub,mk=Yb,uG=J.theme({"&":{color:uk,backgroundColor:aG},".cm-content":{caretColor:mk},".cm-cursor, .cm-dropCursor":{borderLeftColor:mk},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:cG},".cm-panels":{backgroundColor:Ub,color:Bu},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:`1px solid ${Bu}`},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:fk},".cm-activeLine":{backgroundColor:Og},".cm-selectionMatch":{backgroundColor:fk},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{outline:`1px solid ${Bu}`},"&.cm-focused .cm-matchingBracket":{backgroundColor:AO},".cm-gutters":{backgroundColor:AO,color:uk,border:"none"},".cm-activeLineGutter":{backgroundColor:Og},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:bg},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:bg,borderBottomColor:bg},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:Og,color:Bu}}},{dark:!1}),hG=Xc.define([{tag:E.keyword,color:tr},{tag:[E.name,E.deleted,E.character,E.propertyName,E.macroName],color:lo},{tag:[E.variableName],color:lo},{tag:[E.function(E.variableName)],color:tr},{tag:[E.labelName],color:sG},{tag:[E.color,E.constant(E.name),E.standard(E.name)],color:tr},{tag:[E.definition(E.name),E.separator],color:pk},{tag:[E.brace],color:gg},{tag:[E.annotation],color:gk},{tag:[E.number,E.changed,E.annotation,E.modifier,E.self,E.namespace],color:dk},{tag:[E.typeName,E.className],color:mg},{tag:[E.operator,E.operatorKeyword],color:pk},{tag:[E.tagName],color:lG},{tag:[E.squareBracket],color:oG},{tag:[E.angleBracket],color:lo},{tag:[E.attributeName],color:mg},{tag:[E.regexp],color:tr},{tag:[E.quote],color:Yb},{tag:[E.string],color:lo},{tag:E.link,color:gg,textDecoration:"underline",textUnderlinePosition:"under"},{tag:[E.url,E.escape,E.special(E.string)],color:lo},{tag:[E.meta],color:dk},{tag:[E.comment],color:hk,fontStyle:"italic"},{tag:E.strong,fontWeight:"bold",color:tr},{tag:E.emphasis,fontStyle:"italic",color:tr},{tag:E.strikethrough,textDecoration:"line-through"},{tag:E.heading,fontWeight:"bold",color:tr},{tag:E.special(E.heading1),fontWeight:"bold",color:tr},{tag:E.heading1,fontWeight:"bold",color:tr},{tag:[E.heading2,E.heading3,E.heading4],fontWeight:"bold",color:tr},{tag:[E.heading5,E.heading6],color:tr},{tag:[E.atom,E.bool,E.special(E.variableName)],color:lo},{tag:[E.processingInstruction,E.inserted],color:gg},{tag:[E.contentSeparator],color:mg},{tag:E.invalid,color:hk,borderBottom:`1px dotted ${gk}`}]),UA=[uG,a$(hG)];function Je(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){var i=t[r];typeof i=="string"?n.setAttribute(r,i):i!=null&&(n[r]=i)}e++}for(;en.normalize("NFKD"):n=>n;class Jo{constructor(e,t,r=0,i=e.length,s,o){this.test=o,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(r,i),this.bufferStart=r,this.normalize=s?l=>s(Ok(l)):Ok,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return jt(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=ob(e),r=this.bufferStart+this.bufferPos;this.bufferPos+=zn(e);let i=this.normalize(t);for(let s=0,o=r;;s++){let l=i.charCodeAt(s),a=this.match(l,o,this.bufferPos+this.bufferStart);if(s==i.length-1){if(a)return this.value=a,this;break}o==r&&sthis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let r=this.curLineStart+t.index,i=r+t[0].length;if(this.matchPos=Af(this.text,i+(r==i?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(rthis.value.to)&&(!this.test||this.test(r,i,t)))return this.value={from:r,to:i,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=r||i.to<=t){let l=new Ro(t,e.sliceString(t,r));return xg.set(e,l),l}if(i.from==t&&i.to==r)return i;let{text:s,from:o}=i;return o>t&&(s=e.sliceString(t,o)+s,o=t),i.to=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let r=this.flat.from+t.index,i=r+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,i,t)))return this.value={from:r,to:i,match:t},this.matchPos=Af(this.text,i+(r==i?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Ro.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(JA.prototype[Symbol.iterator]=e9.prototype[Symbol.iterator]=function(){return this});function fG(n){try{return new RegExp(n,Gb),!0}catch{return!1}}function Af(n,e){if(e>=n.length)return e;let t=n.lineAt(e),r;for(;e=56320&&r<57344;)e++;return e}function QO(n){let e=String(n.state.doc.lineAt(n.state.selection.main.head).number),t=Je("input",{class:"cm-textfield",name:"line",value:e}),r=Je("form",{class:"cm-gotoLine",onkeydown:s=>{s.keyCode==27?(s.preventDefault(),n.dispatch({effects:Qf.of(!1)}),n.focus()):s.keyCode==13&&(s.preventDefault(),i())},onsubmit:s=>{s.preventDefault(),i()}},Je("label",n.state.phrase("Go to line"),": ",t)," ",Je("button",{class:"cm-button",type:"submit"},n.state.phrase("go")));function i(){let s=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(t.value);if(!s)return;let{state:o}=n,l=o.doc.lineAt(o.selection.main.head),[,a,c,u,h]=s,f=u?+u.slice(1):0,d=c?+c:l.number;if(c&&h){let m=d/100;a&&(m=m*(a=="-"?-1:1)+l.number/o.doc.lines),d=Math.round(o.doc.lines*m)}else c&&a&&(d=d*(a=="-"?-1:1)+l.number);let p=o.doc.line(Math.max(1,Math.min(o.doc.lines,d))),g=F.cursor(p.from+Math.max(0,Math.min(f,p.length)));n.dispatch({effects:[Qf.of(!1),J.scrollIntoView(g.from,{y:"center"})],selection:g}),n.focus()}return{dom:r}}const Qf=Se.define(),bk=vt.define({create(){return!0},update(n,e){for(let t of e.effects)t.is(Qf)&&(n=t.value);return n},provide:n=>Xa.from(n,e=>e?QO:null)}),dG=n=>{let e=ja(n,QO);if(!e){let t=[Qf.of(!0)];n.state.field(bk,!1)==null&&t.push(Se.appendConfig.of([bk,pG])),n.dispatch({effects:t}),e=ja(n,QO)}return e&&e.dom.querySelector("input").select(),!0},pG=J.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}}),gG={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},mG=fe.define({combine(n){return Jr(n,gG,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function OG(n){return[wG,vG]}const bG=Oe.mark({class:"cm-selectionMatch"}),xG=Oe.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function xk(n,e,t,r){return(t==0||n(e.sliceDoc(t-1,t))!=ut.Word)&&(r==e.doc.length||n(e.sliceDoc(r,r+1))!=ut.Word)}function yG(n,e,t,r){return n(e.sliceDoc(t,t+1))==ut.Word&&n(e.sliceDoc(r-1,r))==ut.Word}const vG=xt.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.selectionSet||n.docChanged||n.viewportChanged)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=n.state.facet(mG),{state:t}=n,r=t.selection;if(r.ranges.length>1)return Oe.none;let i=r.main,s,o=null;if(i.empty){if(!e.highlightWordAroundCursor)return Oe.none;let a=t.wordAt(i.head);if(!a)return Oe.none;o=t.charCategorizer(i.head),s=t.sliceDoc(a.from,a.to)}else{let a=i.to-i.from;if(a200)return Oe.none;if(e.wholeWords){if(s=t.sliceDoc(i.from,i.to),o=t.charCategorizer(i.head),!(xk(o,t,i.from,i.to)&&yG(o,t,i.from,i.to)))return Oe.none}else if(s=t.sliceDoc(i.from,i.to),!s)return Oe.none}let l=[];for(let a of n.visibleRanges){let c=new Jo(t.doc,s,a.from,a.to);for(;!c.next().done;){let{from:u,to:h}=c.value;if((!o||xk(o,t,u,h))&&(i.empty&&u<=i.from&&h>=i.to?l.push(xG.range(u,h)):(u>=i.to||h<=i.from)&&l.push(bG.range(u,h)),l.length>e.maxMatches))return Oe.none}}return Oe.set(l)}},{decorations:n=>n.decorations}),wG=J.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),SG=({state:n,dispatch:e})=>{let{selection:t}=n,r=F.create(t.ranges.map(i=>n.wordAt(i.head)||F.cursor(i.head)),t.mainIndex);return r.eq(t)?!1:(e(n.update({selection:r})),!0)};function kG(n,e){let{main:t,ranges:r}=n.selection,i=n.wordAt(t.head),s=i&&i.from==t.from&&i.to==t.to;for(let o=!1,l=new Jo(n.doc,e,r[r.length-1].to);;)if(l.next(),l.done){if(o)return null;l=new Jo(n.doc,e,0,Math.max(0,r[r.length-1].from-1)),o=!0}else{if(o&&r.some(a=>a.from==l.value.from))continue;if(s){let a=n.wordAt(l.value.from);if(!a||a.from!=l.value.from||a.to!=l.value.to)continue}return l.value}}const CG=({state:n,dispatch:e})=>{let{ranges:t}=n.selection;if(t.some(s=>s.from===s.to))return SG({state:n,dispatch:e});let r=n.sliceDoc(t[0].from,t[0].to);if(n.selection.ranges.some(s=>n.sliceDoc(s.from,s.to)!=r))return!1;let i=kG(n,r);return i?(e(n.update({selection:n.selection.addRange(F.range(i.from,i.to),!1),effects:J.scrollIntoView(i.to)})),!0):!1},Sl=fe.define({combine(n){return Jr(n,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new DG(e),scrollToMatch:e=>J.scrollIntoView(e)})}});class t9{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||fG(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,r)=>r=="n"?` +`,nG={defaultPreset:"react",presets:[{name:"react",meta:"live react",label:"React",sandpackTemplate:"react",sandpackTheme:"light",snippetFileName:"/App.js",snippetLanguage:"jsx",initialSnippetContent:tG}]},YA=be(nG),rG=gt(n=>{n.link(n.pipe(rG,ct(YA),ui(([e,t])=>{const r=e?t.presets.find(i=>i.name===e):t.presets.find(i=>i.name==t.defaultPreset);if(!r)throw new Error(`No sandpack preset found with name ${e}`);return{code:r.initialSnippetContent??"",language:r.snippetLanguage??"jsx",meta:r.meta}})),Md)});function j(n){return new Yo(Pb.define(n))}function $i(n){return V(()=>import("./index-BsyXQ4Po.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>e.sql({dialect:e[n]}))}const iG=[I.of({name:"C",extensions:["c","h","ino"],load(){return V(()=>import("./index-D5QN3wsq.js"),__vite__mapDeps([7,1,2,3,4,5,6])).then(n=>n.cpp())}}),I.of({name:"C++",alias:["cpp"],extensions:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],load(){return V(()=>import("./index-D5QN3wsq.js"),__vite__mapDeps([7,1,2,3,4,5,6])).then(n=>n.cpp())}}),I.of({name:"CQL",alias:["cassandra"],extensions:["cql"],load(){return $i("Cassandra")}}),I.of({name:"CSS",extensions:["css"],load(){return V(()=>Promise.resolve().then(()=>kY),void 0).then(n=>n.css())}}),I.of({name:"Go",extensions:["go"],load(){return V(()=>import("./index-CB9V-exR.js"),__vite__mapDeps([8,1,2,3,4,5,6])).then(n=>n.go())}}),I.of({name:"HTML",alias:["xhtml"],extensions:["html","htm","handlebars","hbs"],load(){return V(()=>Promise.resolve().then(()=>JU),void 0).then(n=>n.html())}}),I.of({name:"Java",extensions:["java"],load(){return V(()=>import("./index-D97Cskqz.js"),__vite__mapDeps([9,1,2,3,4,5,6])).then(n=>n.java())}}),I.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return V(()=>Promise.resolve().then(()=>Zu),void 0).then(n=>n.javascript())}}),I.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return V(()=>import("./index-DOC88JTU.js"),__vite__mapDeps([10,1,2,3,4,5,6])).then(n=>n.json())}}),I.of({name:"JSX",extensions:["jsx"],load(){return V(()=>Promise.resolve().then(()=>Zu),void 0).then(n=>n.javascript({jsx:!0}))}}),I.of({name:"LESS",extensions:["less"],load(){return V(()=>import("./index-DPGV2Jmk.js"),__vite__mapDeps([11,1,2,3,4,5,6])).then(n=>n.less())}}),I.of({name:"Liquid",extensions:["liquid"],load(){return V(()=>import("./index-Ai9Weebq.js"),__vite__mapDeps([12,1,2,3,4,5,6])).then(n=>n.liquid())}}),I.of({name:"MariaDB SQL",load(){return $i("MariaSQL")}}),I.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return V(()=>Promise.resolve().then(()=>gee),void 0).then(n=>n.markdown())}}),I.of({name:"MS SQL",load(){return $i("MSSQL")}}),I.of({name:"MySQL",load(){return $i("MySQL")}}),I.of({name:"PHP",extensions:["php","php3","php4","php5","php7","phtml"],load(){return V(()=>import("./index-C46J882Q.js"),__vite__mapDeps([13,1,2,3,4,5,6])).then(n=>n.php())}}),I.of({name:"PLSQL",extensions:["pls"],load(){return $i("PLSQL")}}),I.of({name:"PostgreSQL",load(){return $i("PostgreSQL")}}),I.of({name:"Python",extensions:["BUILD","bzl","py","pyw"],filename:/^(BUCK|BUILD)$/,load(){return V(()=>import("./index-C0D5lmsC.js"),__vite__mapDeps([14,1,2,3,4,5,6])).then(n=>n.python())}}),I.of({name:"Rust",extensions:["rs"],load(){return V(()=>import("./index-3vXbTmOw.js"),__vite__mapDeps([15,1,2,3,4,5,6])).then(n=>n.rust())}}),I.of({name:"Sass",extensions:["sass"],load(){return V(()=>import("./index-DUeiJTUn.js"),__vite__mapDeps([16,1,2,3,4,5,6])).then(n=>n.sass({indented:!0}))}}),I.of({name:"SCSS",extensions:["scss"],load(){return V(()=>import("./index-DUeiJTUn.js"),__vite__mapDeps([16,1,2,3,4,5,6])).then(n=>n.sass())}}),I.of({name:"SQL",extensions:["sql"],load(){return $i("StandardSQL")}}),I.of({name:"SQLite",load(){return $i("SQLite")}}),I.of({name:"TSX",extensions:["tsx"],load(){return V(()=>Promise.resolve().then(()=>Zu),void 0).then(n=>n.javascript({jsx:!0,typescript:!0}))}}),I.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return V(()=>Promise.resolve().then(()=>Zu),void 0).then(n=>n.javascript({typescript:!0}))}}),I.of({name:"WebAssembly",extensions:["wat","wast"],load(){return V(()=>import("./index-C95wco15.js"),__vite__mapDeps([17,1,2,3,4,5,6])).then(n=>n.wast())}}),I.of({name:"XML",alias:["rss","wsdl","xsd"],extensions:["xml","xsl","xsd","svg"],load(){return V(()=>import("./index-DqyaIzih.js"),__vite__mapDeps([18,1,2,3,4,5,6])).then(n=>n.xml())}}),I.of({name:"YAML",alias:["yml"],extensions:["yaml","yml"],load(){return V(()=>import("./index-B9vDB2b7.js"),__vite__mapDeps([19,1,2,3,4,5,6])).then(n=>n.yaml())}}),I.of({name:"APL",extensions:["dyalog","apl"],load(){return V(()=>import("./apl-B4CMkyY2.js"),[]).then(n=>j(n.apl))}}),I.of({name:"PGP",alias:["asciiarmor"],extensions:["asc","pgp","sig"],load(){return V(()=>import("./asciiarmor-Df11BRmG.js"),[]).then(n=>j(n.asciiArmor))}}),I.of({name:"ASN.1",extensions:["asn","asn1"],load(){return V(()=>import("./asn1-CGOzndHr.js"),[]).then(n=>j(n.asn1({})))}}),I.of({name:"Asterisk",filename:/^extensions\.conf$/i,load(){return V(()=>import("./asterisk-B-8jnY81.js"),[]).then(n=>j(n.asterisk))}}),I.of({name:"Brainfuck",extensions:["b","bf"],load(){return V(()=>import("./brainfuck-C4LP7Hcl.js"),[]).then(n=>j(n.brainfuck))}}),I.of({name:"Cobol",extensions:["cob","cpy"],load(){return V(()=>import("./cobol-XrqhtCFE.js"),[]).then(n=>j(n.cobol))}}),I.of({name:"C#",alias:["csharp","cs"],extensions:["cs"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.csharp))}}),I.of({name:"Clojure",extensions:["clj","cljc","cljx"],load(){return V(()=>import("./clojure-BMjYHr_A.js"),[]).then(n=>j(n.clojure))}}),I.of({name:"ClojureScript",extensions:["cljs"],load(){return V(()=>import("./clojure-BMjYHr_A.js"),[]).then(n=>j(n.clojure))}}),I.of({name:"Closure Stylesheets (GSS)",extensions:["gss"],load(){return V(()=>import("./css-BnMrqG3P.js"),[]).then(n=>j(n.gss))}}),I.of({name:"CMake",extensions:["cmake","cmake.in"],filename:/^CMakeLists\.txt$/,load(){return V(()=>import("./cmake-BQqOBYOt.js"),[]).then(n=>j(n.cmake))}}),I.of({name:"CoffeeScript",alias:["coffee","coffee-script"],extensions:["coffee"],load(){return V(()=>import("./coffeescript-S37ZYGWr.js"),[]).then(n=>j(n.coffeeScript))}}),I.of({name:"Common Lisp",alias:["lisp"],extensions:["cl","lisp","el"],load(){return V(()=>import("./commonlisp-DBKNyK5s.js"),[]).then(n=>j(n.commonLisp))}}),I.of({name:"Cypher",extensions:["cyp","cypher"],load(){return V(()=>import("./cypher-C_CwsFkJ.js"),[]).then(n=>j(n.cypher))}}),I.of({name:"Cython",extensions:["pyx","pxd","pxi"],load(){return V(()=>import("./python-BuPzkPfP.js"),[]).then(n=>j(n.cython))}}),I.of({name:"Crystal",extensions:["cr"],load(){return V(()=>import("./crystal-SjHAIU92.js"),[]).then(n=>j(n.crystal))}}),I.of({name:"D",extensions:["d"],load(){return V(()=>import("./d-pRatUO7H.js"),[]).then(n=>j(n.d))}}),I.of({name:"Dart",extensions:["dart"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.dart))}}),I.of({name:"diff",extensions:["diff","patch"],load(){return V(()=>import("./diff-DbItnlRl.js"),[]).then(n=>j(n.diff))}}),I.of({name:"Dockerfile",filename:/^Dockerfile$/,load(){return V(()=>import("./dockerfile-BuNIbK2j.js"),__vite__mapDeps([20,21])).then(n=>j(n.dockerFile))}}),I.of({name:"DTD",extensions:["dtd"],load(){return V(()=>import("./dtd-DF_7sFjM.js"),[]).then(n=>j(n.dtd))}}),I.of({name:"Dylan",extensions:["dylan","dyl","intr"],load(){return V(()=>import("./dylan-DwRh75JA.js"),[]).then(n=>j(n.dylan))}}),I.of({name:"EBNF",load(){return V(()=>import("./ebnf-CDyGwa7X.js"),[]).then(n=>j(n.ebnf))}}),I.of({name:"ECL",extensions:["ecl"],load(){return V(()=>import("./ecl-Cabwm37j.js"),[]).then(n=>j(n.ecl))}}),I.of({name:"edn",extensions:["edn"],load(){return V(()=>import("./clojure-BMjYHr_A.js"),[]).then(n=>j(n.clojure))}}),I.of({name:"Eiffel",extensions:["e"],load(){return V(()=>import("./eiffel-CnydiIhH.js"),[]).then(n=>j(n.eiffel))}}),I.of({name:"Elm",extensions:["elm"],load(){return V(()=>import("./elm-vLlmbW-K.js"),[]).then(n=>j(n.elm))}}),I.of({name:"Erlang",extensions:["erl"],load(){return V(()=>import("./erlang-BNw1qcRV.js"),[]).then(n=>j(n.erlang))}}),I.of({name:"Esper",load(){return V(()=>import("./sql-C4g8LzGK.js"),[]).then(n=>j(n.esper))}}),I.of({name:"Factor",extensions:["factor"],load(){return V(()=>import("./factor-D8pE9siL.js"),__vite__mapDeps([22,21])).then(n=>j(n.factor))}}),I.of({name:"FCL",load(){return V(()=>import("./fcl-Kvtd6kyn.js"),[]).then(n=>j(n.fcl))}}),I.of({name:"Forth",extensions:["forth","fth","4th"],load(){return V(()=>import("./forth-Ffai-XNe.js"),[]).then(n=>j(n.forth))}}),I.of({name:"Fortran",extensions:["f","for","f77","f90","f95"],load(){return V(()=>import("./fortran-DYz_wnZ1.js"),[]).then(n=>j(n.fortran))}}),I.of({name:"F#",alias:["fsharp"],extensions:["fs"],load(){return V(()=>import("./mllike-C_8OmSiT.js"),[]).then(n=>j(n.fSharp))}}),I.of({name:"Gas",extensions:["s"],load(){return V(()=>import("./gas-Bneqetm1.js"),[]).then(n=>j(n.gas))}}),I.of({name:"Gherkin",extensions:["feature"],load(){return V(()=>import("./gherkin-heZmZLOM.js"),[]).then(n=>j(n.gherkin))}}),I.of({name:"Groovy",extensions:["groovy","gradle"],filename:/^Jenkinsfile$/,load(){return V(()=>import("./groovy-DKLxxR9y.js"),[]).then(n=>j(n.groovy))}}),I.of({name:"Haskell",extensions:["hs"],load(){return V(()=>import("./haskell-BWDZoCOh.js"),[]).then(n=>j(n.haskell))}}),I.of({name:"Haxe",extensions:["hx"],load(){return V(()=>import("./haxe-pv4rovob.js"),[]).then(n=>j(n.haxe))}}),I.of({name:"HXML",extensions:["hxml"],load(){return V(()=>import("./haxe-pv4rovob.js"),[]).then(n=>j(n.hxml))}}),I.of({name:"HTTP",load(){return V(()=>import("./http-DBlCnlav.js"),[]).then(n=>j(n.http))}}),I.of({name:"IDL",extensions:["pro"],load(){return V(()=>import("./idl-BEugSyMb.js"),[]).then(n=>j(n.idl))}}),I.of({name:"JSON-LD",alias:["jsonld"],extensions:["jsonld"],load(){return V(()=>import("./javascript-iSgyE4tI.js"),[]).then(n=>j(n.jsonld))}}),I.of({name:"Jinja2",extensions:["j2","jinja","jinja2"],load(){return V(()=>import("./jinja2-C4DGRd-O.js"),[]).then(n=>j(n.jinja2))}}),I.of({name:"Julia",extensions:["jl"],load(){return V(()=>import("./julia-DuME0IfC.js"),[]).then(n=>j(n.julia))}}),I.of({name:"Kotlin",extensions:["kt","kts"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.kotlin))}}),I.of({name:"LiveScript",alias:["ls"],extensions:["ls"],load(){return V(()=>import("./livescript-k3uCVVjK.js"),[]).then(n=>j(n.liveScript))}}),I.of({name:"Lua",extensions:["lua"],load(){return V(()=>import("./lua-BgMRiT3U.js"),[]).then(n=>j(n.lua))}}),I.of({name:"mIRC",extensions:["mrc"],load(){return V(()=>import("./mirc-CjQqDB4T.js"),[]).then(n=>j(n.mirc))}}),I.of({name:"Mathematica",extensions:["m","nb","wl","wls"],load(){return V(()=>import("./mathematica-DTrFuWx2.js"),[]).then(n=>j(n.mathematica))}}),I.of({name:"Modelica",extensions:["mo"],load(){return V(()=>import("./modelica-Dc1JOy9r.js"),[]).then(n=>j(n.modelica))}}),I.of({name:"MUMPS",extensions:["mps"],load(){return V(()=>import("./mumps-BT43cFF4.js"),[]).then(n=>j(n.mumps))}}),I.of({name:"Mbox",extensions:["mbox"],load(){return V(()=>import("./mbox-CNhZ1qSd.js"),[]).then(n=>j(n.mbox))}}),I.of({name:"Nginx",filename:/nginx.*\.conf$/i,load(){return V(()=>import("./nginx-DdIZxoE0.js"),[]).then(n=>j(n.nginx))}}),I.of({name:"NSIS",extensions:["nsh","nsi"],load(){return V(()=>import("./nsis-CEAdamBV.js"),__vite__mapDeps([23,21])).then(n=>j(n.nsis))}}),I.of({name:"NTriples",extensions:["nt","nq"],load(){return V(()=>import("./ntriples-BfvgReVJ.js"),[]).then(n=>j(n.ntriples))}}),I.of({name:"Objective-C",alias:["objective-c","objc"],extensions:["m"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.objectiveC))}}),I.of({name:"Objective-C++",alias:["objective-c++","objc++"],extensions:["mm"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.objectiveCpp))}}),I.of({name:"OCaml",extensions:["ml","mli","mll","mly"],load(){return V(()=>import("./mllike-C_8OmSiT.js"),[]).then(n=>j(n.oCaml))}}),I.of({name:"Octave",extensions:["m"],load(){return V(()=>import("./octave-Ck1zUtKM.js"),[]).then(n=>j(n.octave))}}),I.of({name:"Oz",extensions:["oz"],load(){return V(()=>import("./oz-BzwKVEFT.js"),[]).then(n=>j(n.oz))}}),I.of({name:"Pascal",extensions:["p","pas"],load(){return V(()=>import("./pascal-B1wCu0_E.js"),[]).then(n=>j(n.pascal))}}),I.of({name:"Perl",extensions:["pl","pm"],load(){return V(()=>import("./perl-CdXCOZ3F.js"),[]).then(n=>j(n.perl))}}),I.of({name:"Pig",extensions:["pig"],load(){return V(()=>import("./pig-CevX1Tat.js"),[]).then(n=>j(n.pig))}}),I.of({name:"PowerShell",extensions:["ps1","psd1","psm1"],load(){return V(()=>import("./powershell-CFHJl5sT.js"),[]).then(n=>j(n.powerShell))}}),I.of({name:"Properties files",alias:["ini","properties"],extensions:["properties","ini","in"],load(){return V(()=>import("./properties-C78fOPTZ.js"),[]).then(n=>j(n.properties))}}),I.of({name:"ProtoBuf",extensions:["proto"],load(){return V(()=>import("./protobuf-ChK-085T.js"),[]).then(n=>j(n.protobuf))}}),I.of({name:"Pug",alias:["jade"],extensions:["pug","jade"],load(){return V(()=>import("./pug-BmUsPMDj.js"),__vite__mapDeps([24,25])).then(n=>j(n.pug))}}),I.of({name:"Puppet",extensions:["pp"],load(){return V(()=>import("./puppet-DMA9R1ak.js"),[]).then(n=>j(n.puppet))}}),I.of({name:"Q",extensions:["q"],load(){return V(()=>import("./q-ZnEupP5q.js"),[]).then(n=>j(n.q))}}),I.of({name:"R",alias:["rscript"],extensions:["r","R"],load(){return V(()=>import("./r-DUYO_cvP.js"),[]).then(n=>j(n.r))}}),I.of({name:"RPM Changes",load(){return V(()=>import("./rpm-CTu-6PCP.js"),[]).then(n=>j(n.rpmChanges))}}),I.of({name:"RPM Spec",extensions:["spec"],load(){return V(()=>import("./rpm-CTu-6PCP.js"),[]).then(n=>j(n.rpmSpec))}}),I.of({name:"Ruby",alias:["jruby","macruby","rake","rb","rbx"],extensions:["rb"],filename:/^(Gemfile|Rakefile)$/,load(){return V(()=>import("./ruby-B2Rjki9n.js"),[]).then(n=>j(n.ruby))}}),I.of({name:"SAS",extensions:["sas"],load(){return V(()=>import("./sas-B4kiWyti.js"),[]).then(n=>j(n.sas))}}),I.of({name:"Scala",extensions:["scala"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.scala))}}),I.of({name:"Scheme",extensions:["scm","ss"],load(){return V(()=>import("./scheme-C41bIUwD.js"),[]).then(n=>j(n.scheme))}}),I.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return V(()=>import("./shell-CjFT_Tl9.js"),[]).then(n=>j(n.shell))}}),I.of({name:"Sieve",extensions:["siv","sieve"],load(){return V(()=>import("./sieve-C3Gn_uJK.js"),[]).then(n=>j(n.sieve))}}),I.of({name:"Smalltalk",extensions:["st"],load(){return V(()=>import("./smalltalk-CnHTOXQT.js"),[]).then(n=>j(n.smalltalk))}}),I.of({name:"Solr",load(){return V(()=>import("./solr-DehyRSwq.js"),[]).then(n=>j(n.solr))}}),I.of({name:"SML",extensions:["sml","sig","fun","smackspec"],load(){return V(()=>import("./mllike-C_8OmSiT.js"),[]).then(n=>j(n.sml))}}),I.of({name:"SPARQL",alias:["sparul"],extensions:["rq","sparql"],load(){return V(()=>import("./sparql-DkYu6x3z.js"),[]).then(n=>j(n.sparql))}}),I.of({name:"Spreadsheet",alias:["excel","formula"],load(){return V(()=>import("./spreadsheet-BCZA_wO0.js"),[]).then(n=>j(n.spreadsheet))}}),I.of({name:"Squirrel",extensions:["nut"],load(){return V(()=>import("./clike-DWq2Y8ae.js"),[]).then(n=>j(n.squirrel))}}),I.of({name:"Stylus",extensions:["styl"],load(){return V(()=>import("./stylus-BdAi1jBa.js"),[]).then(n=>j(n.stylus))}}),I.of({name:"Swift",extensions:["swift"],load(){return V(()=>import("./swift-BzpIVaGY.js"),[]).then(n=>j(n.swift))}}),I.of({name:"sTeX",load(){return V(()=>import("./stex-C3f8Ysf7.js"),[]).then(n=>j(n.stex))}}),I.of({name:"LaTeX",alias:["tex"],extensions:["text","ltx","tex"],load(){return V(()=>import("./stex-C3f8Ysf7.js"),[]).then(n=>j(n.stex))}}),I.of({name:"SystemVerilog",extensions:["v","sv","svh"],load(){return V(()=>import("./verilog-C6RDOZhf.js"),[]).then(n=>j(n.verilog))}}),I.of({name:"Tcl",extensions:["tcl"],load(){return V(()=>import("./tcl-DVfN8rqt.js"),[]).then(n=>j(n.tcl))}}),I.of({name:"Textile",extensions:["textile"],load(){return V(()=>import("./textile-CnDTJFAw.js"),[]).then(n=>j(n.textile))}}),I.of({name:"TiddlyWiki",load(){return V(()=>import("./tiddlywiki-DO-Gjzrf.js"),[]).then(n=>j(n.tiddlyWiki))}}),I.of({name:"Tiki wiki",load(){return V(()=>import("./tiki-DGYXhP31.js"),[]).then(n=>j(n.tiki))}}),I.of({name:"TOML",extensions:["toml"],load(){return V(()=>import("./toml-BXUEaScT.js"),[]).then(n=>j(n.toml))}}),I.of({name:"Troff",extensions:["1","2","3","4","5","6","7","8","9"],load(){return V(()=>import("./troff-wAsdV37c.js"),[]).then(n=>j(n.troff))}}),I.of({name:"TTCN",extensions:["ttcn","ttcn3","ttcnpp"],load(){return V(()=>import("./ttcn-CiGrtVSZ.js"),[]).then(n=>j(n.ttcn))}}),I.of({name:"TTCN_CFG",extensions:["cfg"],load(){return V(()=>import("./ttcn-cfg-BIkV9KBc.js"),[]).then(n=>j(n.ttcnCfg))}}),I.of({name:"Turtle",extensions:["ttl"],load(){return V(()=>import("./turtle-B1tBg_DP.js"),[]).then(n=>j(n.turtle))}}),I.of({name:"Web IDL",extensions:["webidl"],load(){return V(()=>import("./webidl-ZXfAyPTL.js"),[]).then(n=>j(n.webIDL))}}),I.of({name:"VB.NET",extensions:["vb"],load(){return V(()=>import("./vb-CmGdzxic.js"),[]).then(n=>j(n.vb))}}),I.of({name:"VBScript",extensions:["vbs"],load(){return V(()=>import("./vbscript-BuJXcnF6.js"),[]).then(n=>j(n.vbScript))}}),I.of({name:"Velocity",extensions:["vtl"],load(){return V(()=>import("./velocity-D8B20fx6.js"),[]).then(n=>j(n.velocity))}}),I.of({name:"Verilog",extensions:["v"],load(){return V(()=>import("./verilog-C6RDOZhf.js"),[]).then(n=>j(n.verilog))}}),I.of({name:"VHDL",extensions:["vhd","vhdl"],load(){return V(()=>import("./vhdl-lSbBsy5d.js"),[]).then(n=>j(n.vhdl))}}),I.of({name:"XQuery",extensions:["xy","xquery"],load(){return V(()=>import("./xquery-WRlm2TX8.js"),[]).then(n=>j(n.xQuery))}}),I.of({name:"Yacas",extensions:["ys"],load(){return V(()=>import("./yacas-BJ4BC0dw.js"),[]).then(n=>j(n.yacas))}}),I.of({name:"Z80",extensions:["z80"],load(){return V(()=>import("./z80-Hz9HOZM7.js"),[]).then(n=>j(n.z80))}}),I.of({name:"MscGen",extensions:["mscgen","mscin","msc"],load(){return V(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(n=>j(n.mscgen))}}),I.of({name:"Xù",extensions:["xu"],load(){return V(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(n=>j(n.xu))}}),I.of({name:"MsGenny",extensions:["msgenny"],load(){return V(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(n=>j(n.msgenny))}}),I.of({name:"Vue",extensions:["vue"],load(){return V(()=>import("./index-qkal7za7.js"),__vite__mapDeps([26,1,2,3,4,5,6])).then(n=>n.vue())}}),I.of({name:"Angular Template",load(){return V(()=>import("./index-BokeEoEU.js"),__vite__mapDeps([27,1,2,3,4,5,6])).then(n=>n.angular())}})],uk="#2e3440",Yb="#3b4252",hk="#434c5e",Bu="#4c566a",fk="#e5e9f0",AO="#eceff4",gg="#8fbcbb",dk="#88c0d0",sG="#81a1c1",tr="#5e81ac",oG="#bf616a",lo="#d08770",mg="#ebcb8b",pk="#a3be8c",lG="#b48ead",gk="#d30102",Ub=AO,Og=Ub,aG="#ffffff",bg=Yb,cG=Ub,mk=Yb,uG=J.theme({"&":{color:uk,backgroundColor:aG},".cm-content":{caretColor:mk},".cm-cursor, .cm-dropCursor":{borderLeftColor:mk},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:cG},".cm-panels":{backgroundColor:Ub,color:Bu},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:`1px solid ${Bu}`},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:fk},".cm-activeLine":{backgroundColor:Og},".cm-selectionMatch":{backgroundColor:fk},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{outline:`1px solid ${Bu}`},"&.cm-focused .cm-matchingBracket":{backgroundColor:AO},".cm-gutters":{backgroundColor:AO,color:uk,border:"none"},".cm-activeLineGutter":{backgroundColor:Og},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:bg},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:bg,borderBottomColor:bg},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:Og,color:Bu}}},{dark:!1}),hG=Xc.define([{tag:E.keyword,color:tr},{tag:[E.name,E.deleted,E.character,E.propertyName,E.macroName],color:lo},{tag:[E.variableName],color:lo},{tag:[E.function(E.variableName)],color:tr},{tag:[E.labelName],color:sG},{tag:[E.color,E.constant(E.name),E.standard(E.name)],color:tr},{tag:[E.definition(E.name),E.separator],color:pk},{tag:[E.brace],color:gg},{tag:[E.annotation],color:gk},{tag:[E.number,E.changed,E.annotation,E.modifier,E.self,E.namespace],color:dk},{tag:[E.typeName,E.className],color:mg},{tag:[E.operator,E.operatorKeyword],color:pk},{tag:[E.tagName],color:lG},{tag:[E.squareBracket],color:oG},{tag:[E.angleBracket],color:lo},{tag:[E.attributeName],color:mg},{tag:[E.regexp],color:tr},{tag:[E.quote],color:Yb},{tag:[E.string],color:lo},{tag:E.link,color:gg,textDecoration:"underline",textUnderlinePosition:"under"},{tag:[E.url,E.escape,E.special(E.string)],color:lo},{tag:[E.meta],color:dk},{tag:[E.comment],color:hk,fontStyle:"italic"},{tag:E.strong,fontWeight:"bold",color:tr},{tag:E.emphasis,fontStyle:"italic",color:tr},{tag:E.strikethrough,textDecoration:"line-through"},{tag:E.heading,fontWeight:"bold",color:tr},{tag:E.special(E.heading1),fontWeight:"bold",color:tr},{tag:E.heading1,fontWeight:"bold",color:tr},{tag:[E.heading2,E.heading3,E.heading4],fontWeight:"bold",color:tr},{tag:[E.heading5,E.heading6],color:tr},{tag:[E.atom,E.bool,E.special(E.variableName)],color:lo},{tag:[E.processingInstruction,E.inserted],color:gg},{tag:[E.contentSeparator],color:mg},{tag:E.invalid,color:hk,borderBottom:`1px dotted ${gk}`}]),UA=[uG,a$(hG)];function Je(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var r in t)if(Object.prototype.hasOwnProperty.call(t,r)){var i=t[r];typeof i=="string"?n.setAttribute(r,i):i!=null&&(n[r]=i)}e++}for(;en.normalize("NFKD"):n=>n;class Jo{constructor(e,t,r=0,i=e.length,s,o){this.test=o,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(r,i),this.bufferStart=r,this.normalize=s?l=>s(Ok(l)):Ok,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return jt(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=ob(e),r=this.bufferStart+this.bufferPos;this.bufferPos+=zn(e);let i=this.normalize(t);for(let s=0,o=r;;s++){let l=i.charCodeAt(s),a=this.match(l,o,this.bufferPos+this.bufferStart);if(s==i.length-1){if(a)return this.value=a,this;break}o==r&&sthis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let r=this.curLineStart+t.index,i=r+t[0].length;if(this.matchPos=Af(this.text,i+(r==i?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(rthis.value.to)&&(!this.test||this.test(r,i,t)))return this.value={from:r,to:i,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=r||i.to<=t){let l=new Ro(t,e.sliceString(t,r));return xg.set(e,l),l}if(i.from==t&&i.to==r)return i;let{text:s,from:o}=i;return o>t&&(s=e.sliceString(t,o)+s,o=t),i.to=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let r=this.flat.from+t.index,i=r+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,i,t)))return this.value={from:r,to:i,match:t},this.matchPos=Af(this.text,i+(r==i?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Ro.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(JA.prototype[Symbol.iterator]=e9.prototype[Symbol.iterator]=function(){return this});function fG(n){try{return new RegExp(n,Gb),!0}catch{return!1}}function Af(n,e){if(e>=n.length)return e;let t=n.lineAt(e),r;for(;e=56320&&r<57344;)e++;return e}function QO(n){let e=String(n.state.doc.lineAt(n.state.selection.main.head).number),t=Je("input",{class:"cm-textfield",name:"line",value:e}),r=Je("form",{class:"cm-gotoLine",onkeydown:s=>{s.keyCode==27?(s.preventDefault(),n.dispatch({effects:Qf.of(!1)}),n.focus()):s.keyCode==13&&(s.preventDefault(),i())},onsubmit:s=>{s.preventDefault(),i()}},Je("label",n.state.phrase("Go to line"),": ",t)," ",Je("button",{class:"cm-button",type:"submit"},n.state.phrase("go")));function i(){let s=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(t.value);if(!s)return;let{state:o}=n,l=o.doc.lineAt(o.selection.main.head),[,a,c,u,h]=s,f=u?+u.slice(1):0,d=c?+c:l.number;if(c&&h){let m=d/100;a&&(m=m*(a=="-"?-1:1)+l.number/o.doc.lines),d=Math.round(o.doc.lines*m)}else c&&a&&(d=d*(a=="-"?-1:1)+l.number);let p=o.doc.line(Math.max(1,Math.min(o.doc.lines,d))),g=F.cursor(p.from+Math.max(0,Math.min(f,p.length)));n.dispatch({effects:[Qf.of(!1),J.scrollIntoView(g.from,{y:"center"})],selection:g}),n.focus()}return{dom:r}}const Qf=Se.define(),bk=vt.define({create(){return!0},update(n,e){for(let t of e.effects)t.is(Qf)&&(n=t.value);return n},provide:n=>Xa.from(n,e=>e?QO:null)}),dG=n=>{let e=ja(n,QO);if(!e){let t=[Qf.of(!0)];n.state.field(bk,!1)==null&&t.push(Se.appendConfig.of([bk,pG])),n.dispatch({effects:t}),e=ja(n,QO)}return e&&e.dom.querySelector("input").select(),!0},pG=J.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}}),gG={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},mG=fe.define({combine(n){return Jr(n,gG,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function OG(n){return[wG,vG]}const bG=Oe.mark({class:"cm-selectionMatch"}),xG=Oe.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function xk(n,e,t,r){return(t==0||n(e.sliceDoc(t-1,t))!=ut.Word)&&(r==e.doc.length||n(e.sliceDoc(r,r+1))!=ut.Word)}function yG(n,e,t,r){return n(e.sliceDoc(t,t+1))==ut.Word&&n(e.sliceDoc(r-1,r))==ut.Word}const vG=xt.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.selectionSet||n.docChanged||n.viewportChanged)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=n.state.facet(mG),{state:t}=n,r=t.selection;if(r.ranges.length>1)return Oe.none;let i=r.main,s,o=null;if(i.empty){if(!e.highlightWordAroundCursor)return Oe.none;let a=t.wordAt(i.head);if(!a)return Oe.none;o=t.charCategorizer(i.head),s=t.sliceDoc(a.from,a.to)}else{let a=i.to-i.from;if(a200)return Oe.none;if(e.wholeWords){if(s=t.sliceDoc(i.from,i.to),o=t.charCategorizer(i.head),!(xk(o,t,i.from,i.to)&&yG(o,t,i.from,i.to)))return Oe.none}else if(s=t.sliceDoc(i.from,i.to),!s)return Oe.none}let l=[];for(let a of n.visibleRanges){let c=new Jo(t.doc,s,a.from,a.to);for(;!c.next().done;){let{from:u,to:h}=c.value;if((!o||xk(o,t,u,h))&&(i.empty&&u<=i.from&&h>=i.to?l.push(xG.range(u,h)):(u>=i.to||h<=i.from)&&l.push(bG.range(u,h)),l.length>e.maxMatches))return Oe.none}}return Oe.set(l)}},{decorations:n=>n.decorations}),wG=J.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),SG=({state:n,dispatch:e})=>{let{selection:t}=n,r=F.create(t.ranges.map(i=>n.wordAt(i.head)||F.cursor(i.head)),t.mainIndex);return r.eq(t)?!1:(e(n.update({selection:r})),!0)};function kG(n,e){let{main:t,ranges:r}=n.selection,i=n.wordAt(t.head),s=i&&i.from==t.from&&i.to==t.to;for(let o=!1,l=new Jo(n.doc,e,r[r.length-1].to);;)if(l.next(),l.done){if(o)return null;l=new Jo(n.doc,e,0,Math.max(0,r[r.length-1].from-1)),o=!0}else{if(o&&r.some(a=>a.from==l.value.from))continue;if(s){let a=n.wordAt(l.value.from);if(!a||a.from!=l.value.from||a.to!=l.value.to)continue}return l.value}}const CG=({state:n,dispatch:e})=>{let{ranges:t}=n.selection;if(t.some(s=>s.from===s.to))return SG({state:n,dispatch:e});let r=n.sliceDoc(t[0].from,t[0].to);if(n.selection.ranges.some(s=>n.sliceDoc(s.from,s.to)!=r))return!1;let i=kG(n,r);return i?(e(n.update({selection:n.selection.addRange(F.range(i.from,i.to),!1),effects:J.scrollIntoView(i.to)})),!0):!1},Sl=fe.define({combine(n){return Jr(n,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new DG(e),scrollToMatch:e=>J.scrollIntoView(e)})}});class t9{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||fG(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,r)=>r=="n"?` `:r=="r"?"\r":r=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord}create(){return this.regexp?new EG(this):new PG(this)}getCursor(e,t=0,r){let i=e.doc?e:Ae.create({doc:e});return r==null&&(r=i.doc.length),this.regexp?po(this,i,t,r):fo(this,i,t,r)}}class n9{constructor(e){this.spec=e}}function fo(n,e,t,r){return new Jo(e.doc,n.unquoted,t,r,n.caseSensitive?void 0:i=>i.toLowerCase(),n.wholeWord?_G(e.doc,e.charCategorizer(e.selection.main.head)):void 0)}function _G(n,e){return(t,r,i,s)=>((s>t||s+i.length=t)return null;i.push(r.value)}return i}highlight(e,t,r,i){let s=fo(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,e.doc.length));for(;!s.next().done;)i(s.value.from,s.value.to)}}function po(n,e,t,r){return new JA(e.doc,n.search,{ignoreCase:!n.caseSensitive,test:n.wholeWord?TG(e.charCategorizer(e.selection.main.head)):void 0},t,r)}function Rf(n,e){return n.slice(Yt(n,e,!1),e)}function Mf(n,e){return n.slice(e,Yt(n,e))}function TG(n){return(e,t,r)=>!r[0].length||(n(Rf(r.input,r.index))!=ut.Word||n(Mf(r.input,r.index))!=ut.Word)&&(n(Mf(r.input,r.index+r[0].length))!=ut.Word||n(Rf(r.input,r.index+r[0].length))!=ut.Word)}class EG extends n9{nextMatch(e,t,r){let i=po(this.spec,e,r,e.doc.length).next();return i.done&&(i=po(this.spec,e,0,t).next()),i.done?null:i.value}prevMatchInRange(e,t,r){for(let i=1;;i++){let s=Math.max(t,r-i*1e4),o=po(this.spec,e,s,r),l=null;for(;!o.next().done;)l=o.value;if(l&&(s==t||l.from>s+10))return l;if(s==t)return null}}prevMatch(e,t,r){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,r,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g,(t,r)=>r=="$"?"$":r=="&"?e.match[0]:r!="0"&&+r=t)return null;i.push(r.value)}return i}highlight(e,t,r,i){let s=po(this.spec,e,Math.max(0,t-250),Math.min(r+250,e.doc.length));for(;!s.next().done;)i(s.value.from,s.value.to)}}const nc=Se.define(),Kb=Se.define(),Ui=vt.define({create(n){return new yg(RO(n).create(),null)},update(n,e){for(let t of e.effects)t.is(nc)?n=new yg(t.value.create(),n.panel):t.is(Kb)&&(n=new yg(n.query,t.value?Jb:null));return n},provide:n=>Xa.from(n,e=>e.panel)});class yg{constructor(e,t){this.query=e,this.panel=t}}const $G=Oe.mark({class:"cm-searchMatch"}),AG=Oe.mark({class:"cm-searchMatch cm-searchMatch-selected"}),QG=xt.fromClass(class{constructor(n){this.view=n,this.decorations=this.highlight(n.state.field(Ui))}update(n){let e=n.state.field(Ui);(e!=n.startState.field(Ui)||n.docChanged||n.selectionSet||n.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:n,panel:e}){if(!e||!n.spec.valid)return Oe.none;let{view:t}=this,r=new Dn;for(let i=0,s=t.visibleRanges,o=s.length;is[i+1].from-2*250;)a=s[++i].to;n.highlight(t.state,l,a,(c,u)=>{let h=t.state.selection.ranges.some(f=>f.from==c&&f.to==u);r.add(c,u,h?AG:$G)})}return r.finish()}},{decorations:n=>n.decorations});function Hc(n){return e=>{let t=e.state.field(Ui,!1);return t&&t.query.spec.valid?n(e,t):s9(e)}}const Lf=Hc((n,{query:e})=>{let{to:t}=n.state.selection.main,r=e.nextMatch(n.state,t,t);if(!r)return!1;let i=F.single(r.from,r.to),s=n.state.facet(Sl);return n.dispatch({selection:i,effects:[ex(n,r),s.scrollToMatch(i.main,n)],userEvent:"select.search"}),i9(n),!0}),If=Hc((n,{query:e})=>{let{state:t}=n,{from:r}=t.selection.main,i=e.prevMatch(t,r,r);if(!i)return!1;let s=F.single(i.from,i.to),o=n.state.facet(Sl);return n.dispatch({selection:s,effects:[ex(n,i),o.scrollToMatch(s.main,n)],userEvent:"select.search"}),i9(n),!0}),RG=Hc((n,{query:e})=>{let t=e.matchAll(n.state,1e3);return!t||!t.length?!1:(n.dispatch({selection:F.create(t.map(r=>F.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),MG=({state:n,dispatch:e})=>{let t=n.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:r,to:i}=t.main,s=[],o=0;for(let l=new Jo(n.doc,n.sliceDoc(r,i));!l.next().done;){if(s.length>1e3)return!1;l.value.from==r&&(o=s.length),s.push(F.range(l.value.from,l.value.to))}return e(n.update({selection:F.create(s,o),userEvent:"select.search.matches"})),!0},yk=Hc((n,{query:e})=>{let{state:t}=n,{from:r,to:i}=t.selection.main;if(t.readOnly)return!1;let s=e.nextMatch(t,r,r);if(!s)return!1;let o=[],l,a,c=[];if(s.from==r&&s.to==i&&(a=t.toText(e.getReplacement(s)),o.push({from:s.from,to:s.to,insert:a}),s=e.nextMatch(t,s.from,s.to),c.push(J.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(r).number)+"."))),s){let u=o.length==0||o[0].from>=s.to?0:s.to-s.from-a.length;l=F.single(s.from-u,s.to-u),c.push(ex(n,s)),c.push(t.facet(Sl).scrollToMatch(l.main,n))}return n.dispatch({changes:o,selection:l,effects:c,userEvent:"input.replace"}),!0}),LG=Hc((n,{query:e})=>{if(n.state.readOnly)return!1;let t=e.matchAll(n.state,1e9).map(i=>{let{from:s,to:o}=i;return{from:s,to:o,insert:e.getReplacement(i)}});if(!t.length)return!1;let r=n.state.phrase("replaced $ matches",t.length)+".";return n.dispatch({changes:t,effects:J.announce.of(r),userEvent:"input.replace.all"}),!0});function Jb(n){return n.state.facet(Sl).createPanel(n)}function RO(n,e){var t,r,i,s,o;let l=n.selection.main,a=l.empty||l.to>l.from+100?"":n.sliceDoc(l.from,l.to);if(e&&!a)return e;let c=n.facet(Sl);return new t9({search:((t=e==null?void 0:e.literal)!==null&&t!==void 0?t:c.literal)?a:a.replace(/\n/g,"\\n"),caseSensitive:(r=e==null?void 0:e.caseSensitive)!==null&&r!==void 0?r:c.caseSensitive,literal:(i=e==null?void 0:e.literal)!==null&&i!==void 0?i:c.literal,regexp:(s=e==null?void 0:e.regexp)!==null&&s!==void 0?s:c.regexp,wholeWord:(o=e==null?void 0:e.wholeWord)!==null&&o!==void 0?o:c.wholeWord})}function r9(n){let e=ja(n,Jb);return e&&e.dom.querySelector("[main-field]")}function i9(n){let e=r9(n);e&&e==n.root.activeElement&&e.select()}const s9=n=>{let e=n.state.field(Ui,!1);if(e&&e.panel){let t=r9(n);if(t&&t!=n.root.activeElement){let r=RO(n.state,e.query.spec);r.valid&&n.dispatch({effects:nc.of(r)}),t.focus(),t.select()}}else n.dispatch({effects:[Kb.of(!0),e?nc.of(RO(n.state,e.query.spec)):Se.appendConfig.of(VG)]});return!0},o9=n=>{let e=n.state.field(Ui,!1);if(!e||!e.panel)return!1;let t=ja(n,Jb);return t&&t.dom.contains(n.root.activeElement)&&n.focus(),n.dispatch({effects:Kb.of(!1)}),!0},IG=[{key:"Mod-f",run:s9,scope:"editor search-panel"},{key:"F3",run:Lf,shift:If,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:Lf,shift:If,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:o9,scope:"editor search-panel"},{key:"Mod-Shift-l",run:MG},{key:"Mod-Alt-g",run:dG},{key:"Mod-d",run:CG,preventDefault:!0}];class DG{constructor(e){this.view=e;let t=this.query=e.state.field(Ui).query.spec;this.commit=this.commit.bind(this),this.searchField=Je("input",{value:t.search,placeholder:Pn(e,"Find"),"aria-label":Pn(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=Je("input",{value:t.replace,placeholder:Pn(e,"Replace"),"aria-label":Pn(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=Je("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=Je("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=Je("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function r(i,s,o){return Je("button",{class:"cm-button",name:i,onclick:s,type:"button"},o)}this.dom=Je("div",{onkeydown:i=>this.keydown(i),class:"cm-search"},[this.searchField,r("next",()=>Lf(e),[Pn(e,"next")]),r("prev",()=>If(e),[Pn(e,"previous")]),r("select",()=>RG(e),[Pn(e,"all")]),Je("label",null,[this.caseField,Pn(e,"match case")]),Je("label",null,[this.reField,Pn(e,"regexp")]),Je("label",null,[this.wordField,Pn(e,"by word")]),...e.state.readOnly?[]:[Je("br"),this.replaceField,r("replace",()=>yk(e),[Pn(e,"replace")]),r("replaceAll",()=>LG(e),[Pn(e,"replace all")])],Je("button",{name:"close",onclick:()=>o9(e),"aria-label":Pn(e,"close"),type:"button"},["×"])])}commit(){let e=new t9({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:nc.of(e)}))}keydown(e){_j(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?If:Lf)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),yk(this.view))}update(e){for(let t of e.transactions)for(let r of t.effects)r.is(nc)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(Sl).top}}function Pn(n,e){return n.state.phrase(e)}const Fu=30,zu=/[\s\.,:;?!]/;function ex(n,{from:e,to:t}){let r=n.state.doc.lineAt(e),i=n.state.doc.lineAt(t).to,s=Math.max(r.from,e-Fu),o=Math.min(i,t+Fu),l=n.state.sliceDoc(s,o);if(s!=r.from){for(let a=0;al.length-Fu;a--)if(!zu.test(l[a-1])&&zu.test(l[a])){l=l.slice(0,a);break}}return J.announce.of(`${n.state.phrase("current match")}. ${l} ${n.state.phrase("on line")} ${r.number}.`)}const NG=J.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),VG=[Ui,wr.low(QG),NG];class ZG{constructor(e,t,r){this.from=e,this.to=t,this.diagnostic=r}}class Cs{constructor(e,t,r){this.diagnostics=e,this.panel=t,this.selected=r}static init(e,t,r){let i=e,s=r.facet(rc).markerFilter;s&&(i=s(i,r));let o=Oe.set(i.map(l=>l.from==l.to||l.from==l.to-1&&r.doc.lineAt(l.from).to==l.from?Oe.widget({widget:new YG(l),diagnostic:l}).range(l.from):Oe.mark({attributes:{class:"cm-lintRange cm-lintRange-"+l.severity+(l.markClass?" "+l.markClass:"")},diagnostic:l}).range(l.from,l.to)),!0);return new Cs(o,t,el(o))}}function el(n,e=null,t=0){let r=null;return n.between(t,1e9,(i,s,{spec:o})=>{if(!(e&&o.diagnostic!=e))return r=new ZG(i,s,o.diagnostic),!1}),r}function BG(n,e){let t=e.pos,r=e.end||t,i=n.state.facet(rc).hideOn(n,t,r);if(i!=null)return i;let s=n.startState.doc.lineAt(e.pos);return!!(n.effects.some(o=>o.is(l9))||n.changes.touchesRange(s.from,Math.max(s.to,r)))}function FG(n,e){return n.field(Mn,!1)?e:e.concat(Se.appendConfig.of(KG))}const l9=Se.define(),tx=Se.define(),a9=Se.define(),Mn=vt.define({create(){return new Cs(Oe.none,null,null)},update(n,e){if(e.docChanged&&n.diagnostics.size){let t=n.diagnostics.map(e.changes),r=null,i=n.panel;if(n.selected){let s=e.changes.mapPos(n.selected.from,1);r=el(t,n.selected.diagnostic,s)||el(t,null,s)}!t.size&&i&&e.state.facet(rc).autoPanel&&(i=null),n=new Cs(t,i,r)}for(let t of e.effects)if(t.is(l9)){let r=e.state.facet(rc).autoPanel?t.value.length?ic.open:null:n.panel;n=Cs.init(t.value,r,e.state)}else t.is(tx)?n=new Cs(n.diagnostics,t.value?ic.open:null,n.selected):t.is(a9)&&(n=new Cs(n.diagnostics,n.panel,t.value));return n},provide:n=>[Xa.from(n,e=>e.panel),J.decorations.from(n,e=>e.diagnostics)]}),zG=Oe.mark({class:"cm-lintRange cm-lintRange-active"});function jG(n,e,t){let{diagnostics:r}=n.state.field(Mn),i=[],s=2e8,o=0;r.between(e-(t<0?1:0),e+(t>0?1:0),(a,c,{spec:u})=>{e>=a&&e<=c&&(a==c||(e>a||t>0)&&(eu9(n,t,!1)))}const qG=n=>{let e=n.state.field(Mn,!1);(!e||!e.panel)&&n.dispatch({effects:FG(n.state,[tx.of(!0)])});let t=ja(n,ic.open);return t&&t.dom.querySelector(".cm-panel-lint ul").focus(),!0},vk=n=>{let e=n.state.field(Mn,!1);return!e||!e.panel?!1:(n.dispatch({effects:tx.of(!1)}),!0)},WG=n=>{let e=n.state.field(Mn,!1);if(!e)return!1;let t=n.state.selection.main,r=e.diagnostics.iter(t.to+1);return!r.value&&(r=e.diagnostics.iter(0),!r.value||r.from==t.from&&r.to==t.to)?!1:(n.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),!0)},HG=[{key:"Mod-Shift-m",run:qG,preventDefault:!0},{key:"F8",run:WG}],rc=fe.define({combine(n){return Object.assign({sources:n.map(e=>e.source).filter(e=>e!=null)},Jr(n.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{needsRefresh:(e,t)=>e?t?r=>e(r)||t(r):e:t}))}});function c9(n){let e=[];if(n)e:for(let{name:t}of n){for(let r=0;rs.toLowerCase()==i.toLowerCase())){e.push(i);continue e}}e.push("")}return e}function u9(n,e,t){var r;let i=t?c9(e.actions):[];return Je("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},Je("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage(n):e.message),(r=e.actions)===null||r===void 0?void 0:r.map((s,o)=>{let l=!1,a=f=>{if(f.preventDefault(),l)return;l=!0;let d=el(n.state.field(Mn).diagnostics,e);d&&s.apply(n,d.from,d.to)},{name:c}=s,u=i[o]?c.indexOf(i[o]):-1,h=u<0?c:[c.slice(0,u),Je("u",c.slice(u,u+1)),c.slice(u+1)];return Je("button",{type:"button",class:"cm-diagnosticAction",onclick:a,onmousedown:a,"aria-label":` Action: ${c}${u<0?"":` (access key "${i[o]})"`}.`},h)}),e.source&&Je("div",{class:"cm-diagnosticSource"},e.source))}class YG extends Sr{constructor(e){super(),this.diagnostic=e}eq(e){return e.diagnostic==this.diagnostic}toDOM(){return Je("span",{class:"cm-lintPoint cm-lintPoint-"+this.diagnostic.severity})}}class wk{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=u9(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class ic{constructor(e){this.view=e,this.items=[];let t=i=>{if(i.keyCode==27)vk(this.view),this.view.focus();else if(i.keyCode==38||i.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(i.keyCode==40||i.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(i.keyCode==36)this.moveSelection(0);else if(i.keyCode==35)this.moveSelection(this.items.length-1);else if(i.keyCode==13)this.view.focus();else if(i.keyCode>=65&&i.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:s}=this.items[this.selectedIndex],o=c9(s.actions);for(let l=0;l{for(let s=0;svk(this.view)},"×")),this.update()}get selectedIndex(){let e=this.view.state.field(Mn).selected;if(!e)return-1;for(let t=0;t{let c=-1,u;for(let h=r;hr&&(this.items.splice(r,c-r),i=!0)),t&&u.diagnostic==t.diagnostic?u.dom.hasAttribute("aria-selected")||(u.dom.setAttribute("aria-selected","true"),s=u):u.dom.hasAttribute("aria-selected")&&u.dom.removeAttribute("aria-selected"),r++});r({sel:s.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:o,panel:l})=>{let a=l.height/this.list.offsetHeight;o.topl.bottom&&(this.list.scrollTop+=(o.bottom-l.bottom)/a)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),i&&this.sync()}sync(){let e=this.list.firstChild;function t(){let r=e;e=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;e!=r.dom;)t();e=r.dom.nextSibling}else this.list.insertBefore(r.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(Mn),r=el(t.diagnostics,this.items[e].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:a9.of(r)})}static open(e){return new ic(e)}}function UG(n,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(n)}')`}function ju(n){return UG(``,'width="6" height="3"')}const GG=J.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:ju("#d11")},".cm-lintRange-warning":{backgroundImage:ju("orange")},".cm-lintRange-info":{backgroundImage:ju("#999")},".cm-lintRange-hint":{backgroundImage:ju("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}}),KG=[Mn,J.decorations.compute([Mn],n=>{let{selected:e,panel:t}=n.field(Mn);return!e||!t||e.from==e.to?Oe.none:Oe.set([zG.range(e.from,e.to)])}),fX(jG,{hideOn:BG}),GG],h9=[yb(),kX(),zj(),BW(),gq(),Qj(),Dj(),Ae.allowMultipleSelections.of(!0),rq(),a$(xq,{fallback:!0}),_q(),xW(),$W(),tX(),iX(),Yj(),OG(),Zc.of([...SW,...zH,...IG,...UW,...hq,...$$,...HG])];function Sk(n,[e,t]){return Math.min(t,Math.max(e,n))}function JG(n){const e=k.useRef({value:n,previous:n});return k.useMemo(()=>(e.current.value!==n&&(e.current.previous=e.current.value,e.current.value=n),e.current.previous),[n])}var eK="VisuallyHidden",nx=k.forwardRef((n,e)=>R.jsx(Me.span,{...n,ref:e,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...n.style}}));nx.displayName=eK;var tK=nx,nK=[" ","Enter","ArrowUp","ArrowDown"],rK=[" ","Enter"],Yc="Select",[Hd,Yd,iK]=P5(Yc),[kl,mte]=Od(Yc,[iK,pl]),Ud=pl(),[sK,Os]=kl(Yc),[oK,lK]=kl(Yc),f9=n=>{const{__scopeSelect:e,children:t,open:r,defaultOpen:i,onOpenChange:s,value:o,defaultValue:l,onValueChange:a,dir:c,name:u,autoComplete:h,disabled:f,required:d,form:p}=n,g=Ud(e),[m,b]=k.useState(null),[O,x]=k.useState(null),[y,v]=k.useState(!1),C=_d(c),[S=!1,_]=yi({prop:r,defaultProp:i,onChange:s}),[P,T]=yi({prop:o,defaultProp:l,onChange:a}),M=k.useRef(null),Q=m?p||!!m.closest("form"):!0,[D,N]=k.useState(new Set),Z=Array.from(D).map(H=>H.props.value).join(";");return R.jsx(p0,{...g,children:R.jsxs(sK,{required:d,scope:e,trigger:m,onTriggerChange:b,valueNode:O,onValueNodeChange:x,valueNodeHasChildren:y,onValueNodeHasChildrenChange:v,contentId:di(),value:P,onValueChange:T,open:S,onOpenChange:_,dir:C,triggerPointerDownPosRef:M,disabled:f,children:[R.jsx(Hd.Provider,{scope:e,children:R.jsx(oK,{scope:n.__scopeSelect,onNativeOptionAdd:k.useCallback(H=>{N(X=>new Set(X).add(H))},[]),onNativeOptionRemove:k.useCallback(H=>{N(X=>{const Y=new Set(X);return Y.delete(H),Y})},[]),children:t})}),Q?R.jsxs(R9,{"aria-hidden":!0,required:d,tabIndex:-1,name:u,autoComplete:h,value:P,onChange:H=>T(H.target.value),disabled:f,form:p,children:[P===void 0?R.jsx("option",{value:""}):null,Array.from(D)]},Z):null]})})};f9.displayName=Yc;var d9="SelectTrigger",p9=k.forwardRef((n,e)=>{const{__scopeSelect:t,disabled:r=!1,...i}=n,s=Ud(t),o=Os(d9,t),l=o.disabled||r,a=tt(e,o.onTriggerChange),c=Yd(t),u=k.useRef("touch"),[h,f,d]=M9(g=>{const m=c().filter(x=>!x.disabled),b=m.find(x=>x.value===o.value),O=L9(m,g,b);O!==void 0&&o.onValueChange(O.value)}),p=g=>{l||(o.onOpenChange(!0),d()),g&&(o.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return R.jsx(wd,{asChild:!0,...s,children:R.jsx(Me.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":Q9(o.value)?"":void 0,...i,ref:a,onClick:Pe(i.onClick,g=>{g.currentTarget.focus(),u.current!=="mouse"&&p(g)}),onPointerDown:Pe(i.onPointerDown,g=>{u.current=g.pointerType;const m=g.target;m.hasPointerCapture(g.pointerId)&&m.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(p(g),g.preventDefault())}),onKeyDown:Pe(i.onKeyDown,g=>{const m=h.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&f(g.key),!(m&&g.key===" ")&&nK.includes(g.key)&&(p(),g.preventDefault())})})})});p9.displayName=d9;var g9="SelectValue",m9=k.forwardRef((n,e)=>{const{__scopeSelect:t,className:r,style:i,children:s,placeholder:o="",...l}=n,a=Os(g9,t),{onValueNodeHasChildrenChange:c}=a,u=s!==void 0,h=tt(e,a.onValueNodeChange);return hn(()=>{c(u)},[c,u]),R.jsx(Me.span,{...l,ref:h,style:{pointerEvents:"none"},children:Q9(a.value)?R.jsx(R.Fragment,{children:o}):s})});m9.displayName=g9;var aK="SelectIcon",O9=k.forwardRef((n,e)=>{const{__scopeSelect:t,children:r,...i}=n;return R.jsx(Me.span,{"aria-hidden":!0,...i,ref:e,children:r||"▼"})});O9.displayName=aK;var cK="SelectPortal",b9=n=>R.jsx(kc,{asChild:!0,...n});b9.displayName=cK;var Hs="SelectContent",x9=k.forwardRef((n,e)=>{const t=Os(Hs,n.__scopeSelect),[r,i]=k.useState();if(hn(()=>{i(new DocumentFragment)},[]),!t.open){const s=r;return s?Lo.createPortal(R.jsx(y9,{scope:n.__scopeSelect,children:R.jsx(Hd.Slot,{scope:n.__scopeSelect,children:R.jsx("div",{children:n.children})})}),s):null}return R.jsx(v9,{...n,ref:e})});x9.displayName=Hs;var ir=10,[y9,bs]=kl(Hs),uK="SelectContentImpl",v9=k.forwardRef((n,e)=>{const{__scopeSelect:t,position:r="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:s,onPointerDownOutside:o,side:l,sideOffset:a,align:c,alignOffset:u,arrowPadding:h,collisionBoundary:f,collisionPadding:d,sticky:p,hideWhenDetached:g,avoidCollisions:m,...b}=n,O=Os(Hs,t),[x,y]=k.useState(null),[v,C]=k.useState(null),S=tt(e,q=>y(q)),[_,P]=k.useState(null),[T,M]=k.useState(null),Q=Yd(t),[D,N]=k.useState(!1),Z=k.useRef(!1);k.useEffect(()=>{if(x)return O0(x)},[x]),s0();const H=k.useCallback(q=>{const[K,...he]=Q().map(Ce=>Ce.ref.current),[de]=he.slice(-1),ve=document.activeElement;for(const Ce of q)if(Ce===ve||(Ce==null||Ce.scrollIntoView({block:"nearest"}),Ce===K&&v&&(v.scrollTop=0),Ce===de&&v&&(v.scrollTop=v.scrollHeight),Ce==null||Ce.focus(),document.activeElement!==ve))return},[Q,v]),X=k.useCallback(()=>H([_,x]),[H,_,x]);k.useEffect(()=>{D&&X()},[D,X]);const{onOpenChange:Y,triggerPointerDownPosRef:ne}=O;k.useEffect(()=>{if(x){let q={x:0,y:0};const K=de=>{var ve,Ce;q={x:Math.abs(Math.round(de.pageX)-(((ve=ne.current)==null?void 0:ve.x)??0)),y:Math.abs(Math.round(de.pageY)-(((Ce=ne.current)==null?void 0:Ce.y)??0))}},he=de=>{q.x<=10&&q.y<=10?de.preventDefault():x.contains(de.target)||Y(!1),document.removeEventListener("pointermove",K),ne.current=null};return ne.current!==null&&(document.addEventListener("pointermove",K),document.addEventListener("pointerup",he,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",K),document.removeEventListener("pointerup",he,{capture:!0})}}},[x,Y,ne]),k.useEffect(()=>{const q=()=>Y(!1);return window.addEventListener("blur",q),window.addEventListener("resize",q),()=>{window.removeEventListener("blur",q),window.removeEventListener("resize",q)}},[Y]);const[pe,ye]=M9(q=>{const K=Q().filter(ve=>!ve.disabled),he=K.find(ve=>ve.ref.current===document.activeElement),de=L9(K,q,he);de&&setTimeout(()=>de.ref.current.focus())}),we=k.useCallback((q,K,he)=>{const de=!Z.current&&!he;(O.value!==void 0&&O.value===K||de)&&(P(q),de&&(Z.current=!0))},[O.value]),De=k.useCallback(()=>x==null?void 0:x.focus(),[x]),Ee=k.useCallback((q,K,he)=>{const de=!Z.current&&!he;(O.value!==void 0&&O.value===K||de)&&M(q)},[O.value]),Le=r==="popper"?MO:w9,Qe=Le===MO?{side:l,sideOffset:a,align:c,alignOffset:u,arrowPadding:h,collisionBoundary:f,collisionPadding:d,sticky:p,hideWhenDetached:g,avoidCollisions:m}:{};return R.jsx(y9,{scope:t,content:x,viewport:v,onViewportChange:C,itemRefCallback:we,selectedItem:_,onItemLeave:De,itemTextRefCallback:Ee,focusSelectedItem:X,selectedItemText:T,position:r,isPositioned:D,searchRef:pe,children:R.jsx(kd,{as:Ns,allowPinchZoom:!0,children:R.jsx(bd,{asChild:!0,trapped:O.open,onMountAutoFocus:q=>{q.preventDefault()},onUnmountAutoFocus:Pe(i,q=>{var K;(K=O.trigger)==null||K.focus({preventScroll:!0}),q.preventDefault()}),children:R.jsx(wc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:q=>q.preventDefault(),onDismiss:()=>O.onOpenChange(!1),children:R.jsx(Le,{role:"listbox",id:O.contentId,"data-state":O.open?"open":"closed",dir:O.dir,onContextMenu:q=>q.preventDefault(),...b,...Qe,onPlaced:()=>N(!0),ref:S,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:Pe(b.onKeyDown,q=>{const K=q.ctrlKey||q.altKey||q.metaKey;if(q.key==="Tab"&&q.preventDefault(),!K&&q.key.length===1&&ye(q.key),["ArrowUp","ArrowDown","Home","End"].includes(q.key)){let de=Q().filter(ve=>!ve.disabled).map(ve=>ve.ref.current);if(["ArrowUp","End"].includes(q.key)&&(de=de.slice().reverse()),["ArrowUp","ArrowDown"].includes(q.key)){const ve=q.target,Ce=de.indexOf(ve);de=de.slice(Ce+1)}setTimeout(()=>H(de)),q.preventDefault()}})})})})})})});v9.displayName=uK;var hK="SelectItemAlignedPosition",w9=k.forwardRef((n,e)=>{const{__scopeSelect:t,onPlaced:r,...i}=n,s=Os(Hs,t),o=bs(Hs,t),[l,a]=k.useState(null),[c,u]=k.useState(null),h=tt(e,S=>u(S)),f=Yd(t),d=k.useRef(!1),p=k.useRef(!0),{viewport:g,selectedItem:m,selectedItemText:b,focusSelectedItem:O}=o,x=k.useCallback(()=>{if(s.trigger&&s.valueNode&&l&&c&&g&&m&&b){const S=s.trigger.getBoundingClientRect(),_=c.getBoundingClientRect(),P=s.valueNode.getBoundingClientRect(),T=b.getBoundingClientRect();if(s.dir!=="rtl"){const ve=T.left-_.left,Ce=P.left-ve,Ne=S.left-Ce,He=S.width+Ne,Rt=Math.max(He,_.width),Mt=window.innerWidth-ir,Vt=Sk(Ce,[ir,Math.max(ir,Mt-Rt)]);l.style.minWidth=He+"px",l.style.left=Vt+"px"}else{const ve=_.right-T.right,Ce=window.innerWidth-P.right-ve,Ne=window.innerWidth-S.right-Ce,He=S.width+Ne,Rt=Math.max(He,_.width),Mt=window.innerWidth-ir,Vt=Sk(Ce,[ir,Math.max(ir,Mt-Rt)]);l.style.minWidth=He+"px",l.style.right=Vt+"px"}const M=f(),Q=window.innerHeight-ir*2,D=g.scrollHeight,N=window.getComputedStyle(c),Z=parseInt(N.borderTopWidth,10),H=parseInt(N.paddingTop,10),X=parseInt(N.borderBottomWidth,10),Y=parseInt(N.paddingBottom,10),ne=Z+H+D+Y+X,pe=Math.min(m.offsetHeight*5,ne),ye=window.getComputedStyle(g),we=parseInt(ye.paddingTop,10),De=parseInt(ye.paddingBottom,10),Ee=S.top+S.height/2-ir,Le=Q-Ee,Qe=m.offsetHeight/2,q=m.offsetTop+Qe,K=Z+H+q,he=ne-K;if(K<=Ee){const ve=M.length>0&&m===M[M.length-1].ref.current;l.style.bottom="0px";const Ce=c.clientHeight-g.offsetTop-g.offsetHeight,Ne=Math.max(Le,Qe+(ve?De:0)+Ce+X),He=K+Ne;l.style.height=He+"px"}else{const ve=M.length>0&&m===M[0].ref.current;l.style.top="0px";const Ne=Math.max(Ee,Z+g.offsetTop+(ve?we:0)+Qe)+he;l.style.height=Ne+"px",g.scrollTop=K-Ee+g.offsetTop}l.style.margin=`${ir}px 0`,l.style.minHeight=pe+"px",l.style.maxHeight=Q+"px",r==null||r(),requestAnimationFrame(()=>d.current=!0)}},[f,s.trigger,s.valueNode,l,c,g,m,b,s.dir,r]);hn(()=>x(),[x]);const[y,v]=k.useState();hn(()=>{c&&v(window.getComputedStyle(c).zIndex)},[c]);const C=k.useCallback(S=>{S&&p.current===!0&&(x(),O==null||O(),p.current=!1)},[x,O]);return R.jsx(dK,{scope:t,contentWrapper:l,shouldExpandOnScrollRef:d,onScrollButtonChange:C,children:R.jsx("div",{ref:a,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:y},children:R.jsx(Me.div,{...i,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});w9.displayName=hK;var fK="SelectPopperPosition",MO=k.forwardRef((n,e)=>{const{__scopeSelect:t,align:r="start",collisionPadding:i=ir,...s}=n,o=Ud(t);return R.jsx(g0,{...o,...s,ref:e,align:r,collisionPadding:i,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});MO.displayName=fK;var[dK,rx]=kl(Hs,{}),LO="SelectViewport",S9=k.forwardRef((n,e)=>{const{__scopeSelect:t,nonce:r,...i}=n,s=bs(LO,t),o=rx(LO,t),l=tt(e,s.onViewportChange),a=k.useRef(0);return R.jsxs(R.Fragment,{children:[R.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),R.jsx(Hd.Slot,{scope:t,children:R.jsx(Me.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:Pe(i.onScroll,c=>{const u=c.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:f}=o;if(f!=null&&f.current&&h){const d=Math.abs(a.current-u.scrollTop);if(d>0){const p=window.innerHeight-ir*2,g=parseFloat(h.style.minHeight),m=parseFloat(h.style.height),b=Math.max(g,m);if(b0?y:0,h.style.justifyContent="flex-end")}}}a.current=u.scrollTop})})})]})});S9.displayName=LO;var k9="SelectGroup",[pK,gK]=kl(k9),mK=k.forwardRef((n,e)=>{const{__scopeSelect:t,...r}=n,i=di();return R.jsx(pK,{scope:t,id:i,children:R.jsx(Me.div,{role:"group","aria-labelledby":i,...r,ref:e})})});mK.displayName=k9;var C9="SelectLabel",OK=k.forwardRef((n,e)=>{const{__scopeSelect:t,...r}=n,i=gK(C9,t);return R.jsx(Me.div,{id:i.id,...r,ref:e})});OK.displayName=C9;var Df="SelectItem",[bK,_9]=kl(Df),P9=k.forwardRef((n,e)=>{const{__scopeSelect:t,value:r,disabled:i=!1,textValue:s,...o}=n,l=Os(Df,t),a=bs(Df,t),c=l.value===r,[u,h]=k.useState(s??""),[f,d]=k.useState(!1),p=tt(e,O=>{var x;return(x=a.itemRefCallback)==null?void 0:x.call(a,O,r,i)}),g=di(),m=k.useRef("touch"),b=()=>{i||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return R.jsx(bK,{scope:t,value:r,disabled:i,textId:g,isSelected:c,onItemTextChange:k.useCallback(O=>{h(x=>x||((O==null?void 0:O.textContent)??"").trim())},[]),children:R.jsx(Hd.ItemSlot,{scope:t,value:r,disabled:i,textValue:u,children:R.jsx(Me.div,{role:"option","aria-labelledby":g,"data-highlighted":f?"":void 0,"aria-selected":c&&f,"data-state":c?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...o,ref:p,onFocus:Pe(o.onFocus,()=>d(!0)),onBlur:Pe(o.onBlur,()=>d(!1)),onClick:Pe(o.onClick,()=>{m.current!=="mouse"&&b()}),onPointerUp:Pe(o.onPointerUp,()=>{m.current==="mouse"&&b()}),onPointerDown:Pe(o.onPointerDown,O=>{m.current=O.pointerType}),onPointerMove:Pe(o.onPointerMove,O=>{var x;m.current=O.pointerType,i?(x=a.onItemLeave)==null||x.call(a):m.current==="mouse"&&O.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Pe(o.onPointerLeave,O=>{var x;O.currentTarget===document.activeElement&&((x=a.onItemLeave)==null||x.call(a))}),onKeyDown:Pe(o.onKeyDown,O=>{var y;((y=a.searchRef)==null?void 0:y.current)!==""&&O.key===" "||(rK.includes(O.key)&&b(),O.key===" "&&O.preventDefault())})})})})});P9.displayName=Df;var Jl="SelectItemText",T9=k.forwardRef((n,e)=>{const{__scopeSelect:t,className:r,style:i,...s}=n,o=Os(Jl,t),l=bs(Jl,t),a=_9(Jl,t),c=lK(Jl,t),[u,h]=k.useState(null),f=tt(e,b=>h(b),a.onItemTextChange,b=>{var O;return(O=l.itemTextRefCallback)==null?void 0:O.call(l,b,a.value,a.disabled)}),d=u==null?void 0:u.textContent,p=k.useMemo(()=>R.jsx("option",{value:a.value,disabled:a.disabled,children:d},a.value),[a.disabled,a.value,d]),{onNativeOptionAdd:g,onNativeOptionRemove:m}=c;return hn(()=>(g(p),()=>m(p)),[g,m,p]),R.jsxs(R.Fragment,{children:[R.jsx(Me.span,{id:a.textId,...s,ref:f}),a.isSelected&&o.valueNode&&!o.valueNodeHasChildren?Lo.createPortal(s.children,o.valueNode):null]})});T9.displayName=Jl;var E9="SelectItemIndicator",xK=k.forwardRef((n,e)=>{const{__scopeSelect:t,...r}=n;return _9(E9,t).isSelected?R.jsx(Me.span,{"aria-hidden":!0,...r,ref:e}):null});xK.displayName=E9;var IO="SelectScrollUpButton",yK=k.forwardRef((n,e)=>{const t=bs(IO,n.__scopeSelect),r=rx(IO,n.__scopeSelect),[i,s]=k.useState(!1),o=tt(e,r.onScrollButtonChange);return hn(()=>{if(t.viewport&&t.isPositioned){let l=function(){const c=a.scrollTop>0;s(c)};const a=t.viewport;return l(),a.addEventListener("scroll",l),()=>a.removeEventListener("scroll",l)}},[t.viewport,t.isPositioned]),i?R.jsx($9,{...n,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:a}=t;l&&a&&(l.scrollTop=l.scrollTop-a.offsetHeight)}}):null});yK.displayName=IO;var DO="SelectScrollDownButton",vK=k.forwardRef((n,e)=>{const t=bs(DO,n.__scopeSelect),r=rx(DO,n.__scopeSelect),[i,s]=k.useState(!1),o=tt(e,r.onScrollButtonChange);return hn(()=>{if(t.viewport&&t.isPositioned){let l=function(){const c=a.scrollHeight-a.clientHeight,u=Math.ceil(a.scrollTop)a.removeEventListener("scroll",l)}},[t.viewport,t.isPositioned]),i?R.jsx($9,{...n,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:a}=t;l&&a&&(l.scrollTop=l.scrollTop+a.offsetHeight)}}):null});vK.displayName=DO;var $9=k.forwardRef((n,e)=>{const{__scopeSelect:t,onAutoScroll:r,...i}=n,s=bs("SelectScrollButton",t),o=k.useRef(null),l=Yd(t),a=k.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return k.useEffect(()=>()=>a(),[a]),hn(()=>{var u;const c=l().find(h=>h.ref.current===document.activeElement);(u=c==null?void 0:c.ref.current)==null||u.scrollIntoView({block:"nearest"})},[l]),R.jsx(Me.div,{"aria-hidden":!0,...i,ref:e,style:{flexShrink:0,...i.style},onPointerDown:Pe(i.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(r,50))}),onPointerMove:Pe(i.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),o.current===null&&(o.current=window.setInterval(r,50))}),onPointerLeave:Pe(i.onPointerLeave,()=>{a()})})}),wK="SelectSeparator",A9=k.forwardRef((n,e)=>{const{__scopeSelect:t,...r}=n;return R.jsx(Me.div,{"aria-hidden":!0,...r,ref:e})});A9.displayName=wK;var NO="SelectArrow",SK=k.forwardRef((n,e)=>{const{__scopeSelect:t,...r}=n,i=Ud(t),s=Os(NO,t),o=bs(NO,t);return s.open&&o.position==="popper"?R.jsx(m0,{...i,...r,ref:e}):null});SK.displayName=NO;function Q9(n){return n===""||n===void 0}var R9=k.forwardRef((n,e)=>{const{value:t,...r}=n,i=k.useRef(null),s=tt(e,i),o=JG(t);return k.useEffect(()=>{const l=i.current,a=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(a,"value").set;if(o!==t&&u){const h=new Event("change",{bubbles:!0});u.call(l,t),l.dispatchEvent(h)}},[o,t]),R.jsx(nx,{asChild:!0,children:R.jsx("select",{...r,ref:s,defaultValue:t})})});R9.displayName="BubbleSelect";function M9(n){const e=Hr(n),t=k.useRef(""),r=k.useRef(0),i=k.useCallback(o=>{const l=t.current+o;e(l),function a(c){t.current=c,window.clearTimeout(r.current),c!==""&&(r.current=window.setTimeout(()=>a(""),1e3))}(l)},[e]),s=k.useCallback(()=>{t.current="",window.clearTimeout(r.current)},[]);return k.useEffect(()=>()=>window.clearTimeout(r.current),[]),[t,i,s]}function L9(n,e,t){const i=e.length>1&&Array.from(e).every(c=>c===e[0])?e[0]:e,s=t?n.indexOf(t):-1;let o=kK(n,Math.max(s,0));i.length===1&&(o=o.filter(c=>c!==t));const a=o.find(c=>c.textValue.toLowerCase().startsWith(i.toLowerCase()));return a!==t?a:void 0}function kK(n,e){return n.map((t,r)=>n[(e+r)%n.length])}var CK=f9,_K=p9,PK=m9,TK=O9,EK=b9,$K=x9,AK=S9,QK=P9,RK=T9,MK=A9,[Gd,Ote]=Od("Tooltip",[pl]),Kd=pl(),I9="TooltipProvider",LK=700,VO="tooltip.open",[IK,ix]=Gd(I9),D9=n=>{const{__scopeTooltip:e,delayDuration:t=LK,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:s}=n,[o,l]=k.useState(!0),a=k.useRef(!1),c=k.useRef(0);return k.useEffect(()=>{const u=c.current;return()=>window.clearTimeout(u)},[]),R.jsx(IK,{scope:e,isOpenDelayed:o,delayDuration:t,onOpen:k.useCallback(()=>{window.clearTimeout(c.current),l(!1)},[]),onClose:k.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:a,onPointerInTransitChange:k.useCallback(u=>{a.current=u},[]),disableHoverableContent:i,children:s})};D9.displayName=I9;var Jd="Tooltip",[DK,Uc]=Gd(Jd),N9=n=>{const{__scopeTooltip:e,children:t,open:r,defaultOpen:i=!1,onOpenChange:s,disableHoverableContent:o,delayDuration:l}=n,a=ix(Jd,n.__scopeTooltip),c=Kd(e),[u,h]=k.useState(null),f=di(),d=k.useRef(0),p=o??a.disableHoverableContent,g=l??a.delayDuration,m=k.useRef(!1),[b=!1,O]=yi({prop:r,defaultProp:i,onChange:S=>{S?(a.onOpen(),document.dispatchEvent(new CustomEvent(VO))):a.onClose(),s==null||s(S)}}),x=k.useMemo(()=>b?m.current?"delayed-open":"instant-open":"closed",[b]),y=k.useCallback(()=>{window.clearTimeout(d.current),m.current=!1,O(!0)},[O]),v=k.useCallback(()=>{window.clearTimeout(d.current),O(!1)},[O]),C=k.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>{m.current=!0,O(!0)},g)},[g,O]);return k.useEffect(()=>()=>window.clearTimeout(d.current),[]),R.jsx(p0,{...c,children:R.jsx(DK,{scope:e,contentId:f,open:b,stateAttribute:x,trigger:u,onTriggerChange:h,onTriggerEnter:k.useCallback(()=>{a.isOpenDelayed?C():y()},[a.isOpenDelayed,C,y]),onTriggerLeave:k.useCallback(()=>{p?v():window.clearTimeout(d.current)},[v,p]),onOpen:y,onClose:v,disableHoverableContent:p,children:t})})};N9.displayName=Jd;var ZO="TooltipTrigger",V9=k.forwardRef((n,e)=>{const{__scopeTooltip:t,...r}=n,i=Uc(ZO,t),s=ix(ZO,t),o=Kd(t),l=k.useRef(null),a=tt(e,l,i.onTriggerChange),c=k.useRef(!1),u=k.useRef(!1),h=k.useCallback(()=>c.current=!1,[]);return k.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),R.jsx(wd,{asChild:!0,...o,children:R.jsx(Me.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:a,onPointerMove:Pe(n.onPointerMove,f=>{f.pointerType!=="touch"&&!u.current&&!s.isPointerInTransitRef.current&&(i.onTriggerEnter(),u.current=!0)}),onPointerLeave:Pe(n.onPointerLeave,()=>{i.onTriggerLeave(),u.current=!1}),onPointerDown:Pe(n.onPointerDown,()=>{c.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:Pe(n.onFocus,()=>{c.current||i.onOpen()}),onBlur:Pe(n.onBlur,i.onClose),onClick:Pe(n.onClick,i.onClose)})})});V9.displayName=ZO;var sx="TooltipPortal",[NK,VK]=Gd(sx,{forceMount:void 0}),Z9=n=>{const{__scopeTooltip:e,forceMount:t,children:r,container:i}=n,s=Uc(sx,e);return R.jsx(NK,{scope:e,forceMount:t,children:R.jsx(ps,{present:t||s.open,children:R.jsx(kc,{asChild:!0,container:i,children:r})})})};Z9.displayName=sx;var tl="TooltipContent",B9=k.forwardRef((n,e)=>{const t=VK(tl,n.__scopeTooltip),{forceMount:r=t.forceMount,side:i="top",...s}=n,o=Uc(tl,n.__scopeTooltip);return R.jsx(ps,{present:r||o.open,children:o.disableHoverableContent?R.jsx(F9,{side:i,...s,ref:e}):R.jsx(ZK,{side:i,...s,ref:e})})}),ZK=k.forwardRef((n,e)=>{const t=Uc(tl,n.__scopeTooltip),r=ix(tl,n.__scopeTooltip),i=k.useRef(null),s=tt(e,i),[o,l]=k.useState(null),{trigger:a,onClose:c}=t,u=i.current,{onPointerInTransitChange:h}=r,f=k.useCallback(()=>{l(null),h(!1)},[h]),d=k.useCallback((p,g)=>{const m=p.currentTarget,b={x:p.clientX,y:p.clientY},O=zK(b,m.getBoundingClientRect()),x=jK(b,O),y=XK(g.getBoundingClientRect()),v=WK([...x,...y]);l(v),h(!0)},[h]);return k.useEffect(()=>()=>f(),[f]),k.useEffect(()=>{if(a&&u){const p=m=>d(m,u),g=m=>d(m,a);return a.addEventListener("pointerleave",p),u.addEventListener("pointerleave",g),()=>{a.removeEventListener("pointerleave",p),u.removeEventListener("pointerleave",g)}}},[a,u,d,f]),k.useEffect(()=>{if(o){const p=g=>{const m=g.target,b={x:g.clientX,y:g.clientY},O=(a==null?void 0:a.contains(m))||(u==null?void 0:u.contains(m)),x=!qK(b,o);O?f():x&&(f(),c())};return document.addEventListener("pointermove",p),()=>document.removeEventListener("pointermove",p)}},[a,u,o,c,f]),R.jsx(F9,{...n,ref:s})}),[BK,FK]=Gd(Jd,{isInside:!1}),F9=k.forwardRef((n,e)=>{const{__scopeTooltip:t,children:r,"aria-label":i,onEscapeKeyDown:s,onPointerDownOutside:o,...l}=n,a=Uc(tl,t),c=Kd(t),{onClose:u}=a;return k.useEffect(()=>(document.addEventListener(VO,u),()=>document.removeEventListener(VO,u)),[u]),k.useEffect(()=>{if(a.trigger){const h=f=>{const d=f.target;d!=null&&d.contains(a.trigger)&&u()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[a.trigger,u]),R.jsx(wc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:h=>h.preventDefault(),onDismiss:u,children:R.jsxs(g0,{"data-state":a.stateAttribute,...c,...l,ref:e,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[R.jsx(F_,{children:r}),R.jsx(BK,{scope:t,isInside:!0,children:R.jsx(tK,{id:a.contentId,role:"tooltip",children:i||r})})]})})});B9.displayName=tl;var z9="TooltipArrow",j9=k.forwardRef((n,e)=>{const{__scopeTooltip:t,...r}=n,i=Kd(t);return FK(z9,t).isInside?null:R.jsx(m0,{...i,...r,ref:e})});j9.displayName=z9;function zK(n,e){const t=Math.abs(e.top-n.y),r=Math.abs(e.bottom-n.y),i=Math.abs(e.right-n.x),s=Math.abs(e.left-n.x);switch(Math.min(t,r,i,s)){case s:return"left";case i:return"right";case t:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function jK(n,e,t=5){const r=[];switch(e){case"top":r.push({x:n.x-t,y:n.y+t},{x:n.x+t,y:n.y+t});break;case"bottom":r.push({x:n.x-t,y:n.y-t},{x:n.x+t,y:n.y-t});break;case"left":r.push({x:n.x+t,y:n.y-t},{x:n.x+t,y:n.y+t});break;case"right":r.push({x:n.x-t,y:n.y-t},{x:n.x-t,y:n.y+t});break}return r}function XK(n){const{top:e,right:t,bottom:r,left:i}=n;return[{x:i,y:e},{x:t,y:e},{x:t,y:r},{x:i,y:r}]}function qK(n,e){const{x:t,y:r}=n;let i=!1;for(let s=0,o=e.length-1;sr!=u>r&&t<(c-l)*(r-a)/(u-a)+l&&(i=!i)}return i}function WK(n){const e=n.slice();return e.sort((t,r)=>t.xr.x?1:t.yr.y?1:0),HK(e)}function HK(n){if(n.length<=1)return n.slice();const e=[];for(let r=0;r=2;){const s=e[e.length-1],o=e[e.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))e.pop();else break}e.push(i)}e.pop();const t=[];for(let r=n.length-1;r>=0;r--){const i=n[r];for(;t.length>=2;){const s=t[t.length-1],o=t[t.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))t.pop();else break}t.push(i)}return t.pop(),e.length===1&&t.length===1&&e[0].x===t[0].x&&e[0].y===t[0].y?e:e.concat(t)}var X9=D9,q9=N9,W9=V9,H9=Z9,Y9=B9,YK=j9;const Gc=w.forwardRef(({title:n,children:e},t)=>{const r=Nt(Gs);return w.createElement(X9,{delayDuration:100},w.createElement(q9,null,w.createElement(W9,{ref:t,asChild:!0},w.createElement("span",{className:W.tooltipTrigger},e)),w.createElement(H9,{container:r==null?void 0:r.current},w.createElement(Y9,{className:Fe(W.tooltipContent),sideOffset:10},n))))}),UK=w.forwardRef(({children:n,className:e,...t},r)=>w.createElement(QK,{...t,ref:r,className:Fe(e,W.selectItem)},w.createElement(RK,null,n))),GK=({title:n,placeholder:e,className:t})=>{const[r,i]=yt(In,Tt);return w.createElement(Gc,{title:n},w.createElement(_K,{"aria-label":e,className:Fe(W.selectTrigger,t),"data-toolbar-item":!0,disabled:r},w.createElement(PK,{placeholder:e}),w.createElement(TK,{className:W.selectDropdownArrow},i("arrow_drop_down"))))},KK=({children:n,className:e=W.selectContainer})=>{const t=Nt(Gs);return w.createElement(EK,{container:t==null?void 0:t.current},w.createElement($K,{className:Fe(e,"mdxeditor-select-content"),onCloseAutoFocus:r=>{r.preventDefault()},position:"popper"},w.createElement(AK,{"data-editor-dropdown":!0},n)))},U9=n=>w.createElement(CK,{value:n.value||void 0,onValueChange:n.onChange},w.createElement(GK,{title:n.triggerTitle,placeholder:n.placeholder}),w.createElement(KK,null,n.items.map((e,t)=>e==="separator"?w.createElement(MK,{key:t}):w.createElement(UK,{key:t,value:e.value},e.label)))),kk="__EMPTY_VALUE__",JK=({language:n,nodeKey:e,code:t,focusEmitter:r})=>{const i=mt(),{parentEditor:s,lexicalNode:o}=Rm(),[l,a,c,u,h]=yt(In,FO,zO,Tt,BO),f=eG(e,"codeblock",n,r),{setCode:d}=Rm(),p=w.useRef(null),g=w.useRef(null),m=w.useRef(d);return m.current=d,f.current={getCodemirror:()=>p.current},w.useEffect(()=>((async()=>{const b=[...a,h9,UA,yb(),J.lineWrapping,J.updateListener.of(({state:O})=>{m.current(O.doc.toString())})];if(l&&b.push(Ae.readOnly.of(!0)),n!==""&&c){const O=iG.find(x=>x.name===n||x.alias.includes(n)||x.extensions.includes(n));if(O)try{const x=await O.load();b.push(x.extension)}catch{console.warn("failed to load language support for",n)}}g.current.innerHTML="",p.current=new J({parent:g.current,state:Ae.create({doc:t,extensions:b})})})(),()=>{var b;(b=p.current)==null||b.destroy(),p.current=null}),[l,n]),w.createElement("div",{className:W.codeMirrorWrapper,onKeyDown:b=>{b.stopPropagation()}},w.createElement("div",{className:W.codeMirrorToolbar},w.createElement(U9,{value:n,onChange:b=>{s.update(()=>{o.setLanguage(b===kk?"":b),setTimeout(()=>{s.update(()=>{o.getLatest().select()})})})},triggerTitle:i("codeBlock.selectLanguage","Select code block language"),placeholder:i("codeBlock.inlineLanguage","Language"),items:Object.entries(h).map(([b,O])=>({value:b||kk,label:O}))}),w.createElement("button",{className:W.iconButton,type:"button",title:i("codeblock.delete","Delete code block"),onClick:b=>{b.preventDefault(),s.update(()=>{o.remove()})}},u("delete_small"))),w.createElement("div",{ref:g}))},BO=be({js:"JavaScript",ts:"TypeScript",tsx:"TypeScript (React)",jsx:"JavaScript (React)",css:"CSS"}),eJ=gt(n=>{n.link(n.pipe(eJ,ui(({language:e,code:t})=>({code:t,language:e,meta:""}))),Md)}),FO=be([]),zO=be(!0),tJ=Nn({update(n,e){n.pubIn({[BO]:e==null?void 0:e.codeBlockLanguages,[FO]:(e==null?void 0:e.codeMirrorExtensions)??[],[zO]:(e==null?void 0:e.autoLoadLanguageSupport)??!0})},init(n,e){n.pubIn({[BO]:e==null?void 0:e.codeBlockLanguages,[FO]:(e==null?void 0:e.codeMirrorExtensions)??[],[AF]:nJ((e==null?void 0:e.codeBlockLanguages)??{}),[zO]:(e==null?void 0:e.autoLoadLanguageSupport)??!0})}});function nJ(n){return{match(e,t){return!!Object.hasOwn(n,e??"")&&!t},priority:1,Editor:JK}}function rJ(n){try{const e=n.anchor,t=n.focus,r=n.anchor.getNode(),i=n.focus.getNode();return r===i?r:n.isBackward()?sy(t)?r:i:sy(e)?r:i}catch{return null}}function G9(n){const e=le(),t=window.getSelection(),r=document.activeElement,i=n.getRootElement();if(e!==null&&t!==null&&i!==null&&i.contains(t.anchorNode)&&n.isEditable()){const s=t.getRangeAt(0);let o;if(t.isCollapsed){let l=t.anchorNode;(l==null?void 0:l.nodeType)==3&&(l=l.parentNode),o=l.getBoundingClientRect(),o.width=0}else if(t.anchorNode===i){let l=i;for(;l.firstElementChild!=null;)l=l.firstElementChild;o=l.getBoundingClientRect()}else o=s.getBoundingClientRect();return{top:Math.round(o.top),left:Math.round(o.left),width:Math.round(o.width),height:Math.round(o.height)}}else if(!r||r.className!=="link-input")return null;return null}function iJ({url:n,title:e,onSubmit:t,onCancel:r,linkAutocompleteSuggestions:i}){const{register:s,handleSubmit:o,control:l,setValue:a,reset:c}=AP({values:{url:n,title:e}}),u=mt();return w.createElement("form",{onSubmit:h=>{o(t)(h),h.stopPropagation(),h.preventDefault()},onReset:h=>{h.stopPropagation(),r()},className:Fe(W.multiFieldForm,W.linkDialogEditForm)},w.createElement("div",{className:W.formField},w.createElement("label",{htmlFor:"link-url"},u("createLink.url","URL")),w.createElement(rT,{register:s,initialInputValue:n,inputName:"url",suggestions:i,setValue:a,control:l,placeholder:u("createLink.urlPlaceholder","Select or paste an URL"),autofocus:!0})),w.createElement("div",{className:W.formField},w.createElement("label",{htmlFor:"link-title"},u("createLink.title","Title")),w.createElement("input",{id:"link-title",className:W.textInput,size:40,...s("title")})),w.createElement("div",{style:{display:"flex",justifyContent:"flex-end",gap:"var(--spacing-2)"}},w.createElement("button",{type:"submit",title:u("createLink.saveTooltip","Set URL"),"aria-label":u("createLink.saveTooltip","Set URL"),className:Fe(W.primaryButton)},u("dialogControls.save","Save")),w.createElement("button",{type:"reset",title:u("createLink.cancelTooltip","Cancel change"),"aria-label":u("createLink.cancelTooltip","Cancel change"),className:Fe(W.secondaryButton)},u("dialogControls.cancel","Cancel"))))}const sJ=()=>{const[n,e,t,r,i,s]=yt(Gs,ft,Tt,mn,r3,i3),o=at(K9),l=at(J9),a=at(e3),c=at(t3),u=at(n3);w.useEffect(()=>{const m=()=>{e==null||e.getEditorState().read(()=>{o(!0)})};return window.addEventListener("resize",m),window.addEventListener("scroll",m),()=>{window.removeEventListener("resize",m),window.removeEventListener("scroll",m)}},[e,o]);const[h,f]=w.useState(!1),d=mt(),p=r.rectangle,g=r.type==="preview"&&r.url.startsWith("http");return w.createElement(v0,{open:r.type!=="inactive"},w.createElement(yV,{"data-visible":r.type==="edit",className:W.linkDialogAnchor,style:{top:`${(p==null?void 0:p.top)??0}px`,left:`${(p==null?void 0:p.left)??0}px`,width:`${(p==null?void 0:p.width)??0}px`,height:`${(p==null?void 0:p.height)??0}px`}}),w.createElement(w0,{container:n==null?void 0:n.current},w.createElement(vV,{className:Fe(W.linkDialogPopoverContent),sideOffset:5,onOpenAutoFocus:m=>{m.preventDefault()},key:r.linkNodeKey},r.type==="edit"&&w.createElement(iJ,{url:r.url,title:r.title,onSubmit:l,onCancel:a.bind(null),linkAutocompleteSuggestions:i}),r.type==="preview"&&w.createElement(w.Fragment,null,w.createElement("a",{className:W.linkDialogPreviewAnchor,href:r.url,...g?{target:"_blank",rel:"noreferrer"}:{},onClick:m=>{s!==null&&(m.preventDefault(),s(r.url))},title:g?d("linkPreview.open","Open {{url}} in new window",{url:r.url}):r.url},w.createElement("span",null,r.url),g&&t("open_in_new")),w.createElement(vg,{onClick:()=>{c()},title:d("linkPreview.edit","Edit link URL"),"aria-label":d("linkPreview.edit","Edit link URL")},t("edit")),w.createElement(X9,null,w.createElement(q9,{open:h},w.createElement(W9,{asChild:!0},w.createElement(vg,{title:d("linkPreview.copyToClipboard","Copy to clipboard"),"aria-label":d("linkPreview.copyToClipboard","Copy to clipboard"),onClick:()=>{window.navigator.clipboard.writeText(r.url).then(()=>{f(!0),setTimeout(()=>{f(!1)},1e3)})}},t(h?"check":"content_copy"))),w.createElement(H9,{container:n==null?void 0:n.current},w.createElement(Y9,{className:Fe(W.tooltipContent),sideOffset:5},d("linkPreview.copied","Copied!"),w.createElement(YK,null))))),w.createElement(vg,{title:d("linkPreview.remove","Remove link"),"aria-label":d("linkPreview.remove","Remove link"),onClick:()=>{u()}},t("link_off"))),w.createElement(S0,{className:W.popoverArrow}))))},vg=w.forwardRef(({className:n,...e},t)=>w.createElement("button",{className:Fe(W.actionButton,n),ref:t,...e}));function jO(n){if(!n)return null;const e=rJ(n);if(e===null)return null;const t=e.getParent();return Pm(t)?t:Pm(e)?e:null}const K9=gt(),mn=be({type:"inactive"},n=>{n.pub(zh,e=>e.registerCommand(uc,()=>n.getValue(mn).type==="preview"?(n.pub(mn,{type:"inactive"}),!0):!1,lt)),n.pub(zh,e=>e.registerCommand(SC,t=>{if(t.key==="k"&&(Zh?t.metaKey:t.ctrlKey)&&!n.getValue(In)){const r=le();return U(r)?(n.pub(ox),t.stopPropagation(),t.preventDefault(),!0):!1}return!1},Jg)),n.link(n.pipe(t3,ct(mn),ui(([,e])=>{if(e.type==="preview")return{type:"edit",initialUrl:e.url,url:e.url,title:e.title,linkNodeKey:e.linkNodeKey,rectangle:e.rectangle};throw new Error("Cannot switch to edit mode when not in preview mode")})),mn),n.sub(n.pipe(J9,ct(ft,mn,Vo)),([e,t,r,i])=>{var s,o;const l=((s=e.url)==null?void 0:s.trim())??"",a=((o=e.title)==null?void 0:o.trim())??"";if(l!==""){if(i!=null&&i.isCollapsed()){const c=a||l;t==null||t.update(()=>{const u=jO(i);if(u)u.setURL(l),u.setTitle(a);else{const h=La(l,{title:a});h.append(Ot(c)),ll([h]),h.select()}},{discrete:!0})}else t==null||t.dispatchCommand(Tm,{url:l,title:a});n.pub(mn,{type:"preview",linkNodeKey:r.linkNodeKey,rectangle:r.rectangle,title:a,url:l})}else r.type==="edit"&&r.initialUrl!==""&&(t==null||t.dispatchCommand(Tm,null)),n.pub(mn,{type:"inactive"})}),n.link(n.pipe(e3,ct(mn,ft),ui(([,e,t])=>{if(e.type==="edit")return t==null||t.focus(),e.initialUrl===""?{type:"inactive"}:{type:"preview",url:e.initialUrl,linkNodeKey:e.linkNodeKey,rectangle:e.rectangle};throw new Error("Cannot cancel edit when not in edit mode")})),mn),n.link(n.pipe(n.combine(Vo,K9),ct(ft,mn,In),ui(([[e],t,r,i])=>{if(U(e)&&t&&!i){const s=jO(e);return s?{type:"preview",url:s.getURL(),linkNodeKey:s.getKey(),title:s.getTitle(),rectangle:G9(t)}:{type:"inactive"}}else return{type:"inactive"}})),mn)}),J9=gt(),e3=os();os();const t3=os(),n3=os(n=>{n.sub(n.pipe(n3,ct(ft)),([,e])=>{e==null||e.dispatchCommand(Tm,null)})}),ox=os(n=>{n.sub(n.pipe(ox,ct(Vo,ft),ac(([,e])=>U(e))),([,e,t])=>{t==null||t.focus(()=>{t.getEditorState().read(()=>{const r=jO(e),i=G9(t);r?n.pub(mn,{type:"edit",initialUrl:r.getURL(),initialTitle:r.getTitle()??"",url:r.getURL(),title:r.getTitle()??"",linkNodeKey:r.getKey(),rectangle:i}):n.pub(mn,{type:"edit",initialUrl:"",initialTitle:"",title:"",url:"",linkNodeKey:"",rectangle:i})})})})}),r3=be([]),i3=be(null),oJ=Nn({init(n,e){n.pub(hl,(e==null?void 0:e.LinkDialog)??sJ),n.pub(i3,(e==null?void 0:e.onClickLinkCallback)??null)},update(n,e={}){n.pub(r3,e.linkAutocompleteSuggestions??[])}});function lx(n,e){return w.forwardRef((t,r)=>{const i=Fe(e.className,t.className);return w.createElement(n,{...e,...t,className:i,ref:r})})}function lJ(n){return({title:e,children:t,...r})=>w.createElement(n,{...r},w.createElement(Gc,{title:e},t))}const aJ=({readOnly:n,children:e,className:t})=>w.createElement(E0,{className:Fe("mdxeditor-toolbar",W.toolbarRoot,{[W.readOnlyToolbarRoot]:n},t),...n?{tabIndex:-1}:{}},e),cJ=lx(Hi,{className:W.toolbarButton,"data-toolbar-item":!0}),Kc=lJ(cJ),s3=lx(ch,{className:W.toolbarToggleItem,"data-toolbar-item":!0});lx(Ed,{type:"single",className:W.toolbarToggleSingleGroup});const o3=w.forwardRef(({on:n,title:e,children:t,disabled:r,...i},s)=>w.createElement(Ed,{type:"single",className:W.toolbarToggleSingleGroup,...i,value:n?"on":"off",ref:s},w.createElement(s3,{title:e,value:"on",disabled:r},w.createElement(Gc,{title:e},t)))),l3=({items:n})=>w.createElement("div",{className:W.toolbarGroupOfGroups},n.map((e,t)=>w.createElement(o3,{key:t,title:e.title,on:e.active,onValueChange:r=>{e.onChange(r==="on")},disabled:e.disabled},e.contents))),a3=({value:n,onChange:e,className:t,items:r})=>{const i=mt();return w.createElement("div",{className:W.toolbarGroupOfGroups},w.createElement(Ed,{"aria-label":i("toolbar.toggleGroup","toggle group"),type:"single",className:Fe(W.toolbarToggleSingleGroup,t),onValueChange:e,value:n||"",onFocus:s=>{s.preventDefault()}},r.map((s,o)=>w.createElement(s3,{key:o,"aria-label":s.title,value:s.value},w.createElement(Gc,{title:s.title},s.contents)))))};function Ck(n){return Object.hasOwn(n,"when")}const uJ=({options:n})=>{const e=Nt(dd),t=w.useMemo(()=>{const r=n.find(i=>{if(Ck(i)){if(i.when(e))return!0}else return!0});return r?Ck(r)?r.contents():r.fallback():null},[n,e]);return w.createElement("div",{style:{display:"flex"}},t)},hJ=G5,wg=be(()=>null),Sg=be(""),_k=()=>"This is an empty toolbar. Pass `{toolbarContents: () => { return <>toolbar components }}` to the toolbarPlugin to customize it.",fJ=Nn({init(n,e){n.pubIn({[wg]:(e==null?void 0:e.toolbarContents)??_k,[Sg]:(e==null?void 0:e.toolbarClassName)??"",[h6]:()=>{const[t,r,i]=yt(wg,In,Sg);return w.createElement(aJ,{className:i,readOnly:r},t())}})},update(n,e){n.pub(wg,(e==null?void 0:e.toolbarContents)??_k),n.pub(Sg,(e==null?void 0:e.toolbarClassName)??"")}});class kt{constructor(e,t,r,i){this.fromA=e,this.toA=t,this.fromB=r,this.toB=i}offset(e,t=e){return new kt(this.fromA+e,this.toA+e,this.fromB+t,this.toB+t)}}function Ys(n,e,t,r,i,s){if(n==r)return[];let o=ax(n,e,t,r,i,s),l=cx(n,e+o,t,r,i+o,s);e+=o,t-=l,i+=o,s-=l;let a=t-e,c=s-i;if(!a||!c)return[new kt(e,t,i,s)];if(a>c){let h=n.slice(e,t).indexOf(r.slice(i,s));if(h>-1)return[new kt(e,e+h,i,i),new kt(e+h+c,t,s,s)]}else if(c>a){let h=r.slice(i,s).indexOf(n.slice(e,t));if(h>-1)return[new kt(e,e,i,i+h),new kt(t,t,i+h+a,s)]}if(a==1||c==1)return[new kt(e,t,i,s)];let u=h3(n,e,t,r,i,s);if(u){let[h,f,d]=u;return Ys(n,e,h,r,i,f).concat(Ys(n,h+d,t,r,f+d,s))}return dJ(n,e,t,r,i,s)}let ea=1e9;function dJ(n,e,t,r,i,s){let o=t-e,l=s-i;if(ea<1e9&&Math.min(o,l)>ea*16)return Math.min(o,l)>ea*64?[new kt(e,t,i,s)]:Pk(n,e,t,r,i,s);let a=Math.ceil((o+l)/2);kg.reset(a),Cg.reset(a);let c=(d,p)=>n.charCodeAt(e+d)==r.charCodeAt(i+p),u=(d,p)=>n.charCodeAt(t-d-1)==r.charCodeAt(s-p-1),h=(o-l)%2!=0?Cg:null,f=h?null:kg;for(let d=0;dea)return Pk(n,e,t,r,i,s);let p=kg.advance(d,o,l,a,h,!1,c)||Cg.advance(d,o,l,a,f,!0,u);if(p)return pJ(n,e,t,e+p[0],r,i,s,i+p[1])}return[new kt(e,t,i,s)]}class c3{constructor(){this.vec=[]}reset(e){this.len=e<<1;for(let t=0;tt)this.end+=2;else if(h>r)this.start+=2;else if(s){let f=i+(t-r)-a;if(f>=0&&f=t-u)return[d,i+d-f]}else{let d=t-s.vec[f];if(u>=d)return[u,h]}}}return null}}const kg=new c3,Cg=new c3;function pJ(n,e,t,r,i,s,o,l){let a=!1;return!nl(n,r)&&++r==t&&(a=!0),!nl(i,l)&&++l==o&&(a=!0),a?[new kt(e,t,s,o)]:Ys(n,e,r,i,s,l).concat(Ys(n,r,t,i,l,o))}function u3(n,e){let t=1,r=Math.min(n,e);for(;tt||u>s||n.slice(l,c)!=r.slice(a,u)){if(o==1)return l-e-(nl(n,l)?0:1);o=o>>1}else{if(c==t||u==s)return c-e;l=c,a=u}}}function cx(n,e,t,r,i,s){if(e==t||i==s||n.charCodeAt(t-1)!=r.charCodeAt(s-1))return 0;let o=u3(t-e,s-i);for(let l=t,a=s;;){let c=l-o,u=a-o;if(c>1}else{if(c==e||u==i)return t-c;l=c,a=u}}}function XO(n,e,t,r,i,s,o,l){let a=r.slice(i,s),c=null;for(;;){if(c||o=t)break;let f=n.slice(u,h),d=-1;for(;(d=a.indexOf(f,d+1))!=-1;){let p=ax(n,h,t,r,i+d+f.length,s),g=cx(n,e,u,r,i,i+d),m=f.length+p+g;(!c||c[2]>1}}function h3(n,e,t,r,i,s){let o=t-e,l=s-i;if(oi.fromA-e&&r.toB>i.fromB-e&&(n[t-1]=new kt(r.fromA,i.toA,r.fromB,i.toB),n.splice(t--,1))}}function gJ(n,e,t){for(;;){f3(t,1);let r=!1;for(let i=0;i3||l>3){let a=i==n.length-1?e.length:n[i+1].fromA,c=s.fromA-r,u=a-s.toA,h=Ek(e,s.fromA,Math.min(c,5)),f=Tk(e,s.toA,Math.min(u,5)),d=s.fromA-h,p=f-s.toA;if(!o||!l){let g=Math.max(o,l),[m,b,O]=o?[e,s.fromA,s.toA]:[t,s.fromB,s.toB];d&&p&&(g>d&&e.slice(h,s.fromA)==m.slice(O-d,O)?(s=n[i]=new kt(h,h+o,s.fromB-d,s.toB-d),h=s.fromA,f=Tk(e,s.toA,Math.min(a-s.toA,5))):g>p&&e.slice(s.toA,f)==m.slice(b,b+p)&&(s=n[i]=new kt(f-o,f,s.fromB+p,s.toB+p),f=s.toA,h=Ek(e,s.fromA,Math.min(s.fromA-r,5))),d=s.fromA-h,p=f-s.toA)}if(d||p)s=n[i]=new kt(s.fromA-d,s.toA+p,s.fromB-d,s.toB+p);else if(o){if(!l){let g=Ak(e,s.fromA,s.toA),m,b=g<0?-1:$k(e,s.toA,s.fromA);g>-1&&(m=g-s.fromA)<=u&&e.slice(s.fromA,g)==e.slice(s.toA,s.toA+m)?s=n[i]=s.offset(m):b>-1&&(m=s.toA-b)>=c&&t.slice(s.fromA-m,s.fromA)==t.slice(b,s.toA)&&(s=n[i]=s.offset(-m))}}else{let g=Ak(t,s.fromB,s.toB),m,b=g<0?-1:$k(t,s.toB,s.fromB);g>-1&&(m=g-s.fromB)<=u&&t.slice(s.fromB,g)==t.slice(s.toB,s.toB+m)?s=n[i]=s.offset(m):b>-1&&(m=s.toB-b)>=c&&t.slice(s.fromB-m,s.fromB)==t.slice(b,s.toB)&&(s=n[i]=s.offset(-m))}r=s.toA}}return f3(n,3),n}let Rs;try{Rs=new RegExp("[\\p{Alphabetic}\\p{Number}]","u")}catch{}function d3(n){return n>48&&n<58||n>64&&n<91||n>96&&n<123}function p3(n,e){if(e==n.length)return 0;let t=n.charCodeAt(e);return t<192?d3(t)?1:0:Rs?!m3(t)||e==n.length-1?Rs.test(String.fromCharCode(t))?1:0:Rs.test(n.slice(e,e+2))?2:0:0}function g3(n,e){if(!e)return 0;let t=n.charCodeAt(e-1);return t<192?d3(t)?1:0:Rs?!O3(t)||e==1?Rs.test(String.fromCharCode(t))?1:0:Rs.test(n.slice(e-2,e))?2:0:0}function Tk(n,e,t){if(e==n.length||!g3(n,e))return e;for(let r=e,i=e+t;;){let s=p3(n,r);if(!s)return r;if(r+=s,r>i)return e}}function Ek(n,e,t){if(!e||!p3(n,e))return e;for(let r=e,i=e-t;;){let s=g3(n,r);if(!s)return r;if(r-=s,rn>=55296&&n<=56319,O3=n=>n>=56320&&n<=57343;function nl(n,e){return!e||e==n.length||!m3(n.charCodeAt(e-1))||!O3(n.charCodeAt(e))}function OJ(n,e,t){var r;return ea=((r=t==null?void 0:t.scanLimit)!==null&&r!==void 0?r:1e9)>>1,gJ(n,e,Ys(n,0,n.length,e,0,e.length))}function b3(n,e,t){return mJ(OJ(n,e,t),n,e)}const Ir=fe.define({combine:n=>n[0]}),qO=Se.define(),rl=vt.define({create(n){return null},update(n,e){for(let t of e.effects)t.is(qO)&&(n=t.value);return n}});class Mo{constructor(e,t,r,i,s){this.changes=e,this.fromA=t,this.toA=r,this.fromB=i,this.toB=s}offset(e,t){return e||t?new Mo(this.changes,this.fromA+e,this.toA+e,this.fromB+t,this.toB+t):this}get endA(){return Math.max(this.fromA,this.toA-1)}get endB(){return Math.max(this.fromB,this.toB-1)}static build(e,t,r){return x3(b3(e.toString(),t.toString(),r),e,t,0,0)}static updateA(e,t,r,i,s){return Ik(Lk(e,i,!0,r.length),e,t,r,s)}static updateB(e,t,r,i,s){return Ik(Lk(e,i,!1,t.length),e,t,r,s)}}function Qk(n,e,t,r){let i=t.lineAt(n),s=r.lineAt(e);return i.to==n&&s.to==e&&nu+1&&g>h+1)break;f.push(d.offset(-a+r,-c+i)),[u,h]=Rk(d.toA+r,d.toB+i,e,t),o++}s.push(new Mo(f,a,Math.max(a,u),c,Math.max(c,h)))}return s}const Xu=1e3;function Mk(n,e,t,r){let i=0,s=n.length;for(;;){if(i==s){let u=0,h=0;i&&({toA:u,toB:h}=n[i-1]);let f=e-(t?u:h);return[u+f,h+f]}let o=i+s>>1,l=n[o],[a,c]=t?[l.fromA,l.toA]:[l.fromB,l.toB];if(a>e)s=o;else if(c<=e)i=o+1;else return r?[l.fromA,l.fromB]:[l.toA,l.toB]}}function Lk(n,e,t,r){let i=[];return e.iterChangedRanges((s,o,l,a)=>{let c=0,u=t?e.length:r,h=0,f=t?r:e.length;s>Xu&&([c,h]=Mk(n,s-Xu,t,!0)),o=c?i[i.length-1]={fromA:p.fromA,fromB:p.fromB,toA:u,toB:f,diffA:p.diffA+g,diffB:p.diffB+m}:i.push({fromA:c,toA:u,fromB:h,toB:f,diffA:g,diffB:m})}),i}function Ik(n,e,t,r,i){if(!n.length)return e;let s=[];for(let o=0,l=0,a=0,c=0;;o++){let u=o==n.length?null:n[o],h=u?u.fromA+l:t.length,f=u?u.fromB+a:r.length;for(;ch||m.toB+a>f)break;s.push(m.offset(l,a)),c++}if(!u)break;let d=u.toA+l+u.diffA,p=u.toB+a+u.diffB,g=b3(t.sliceString(h,d),r.sliceString(f,p),i);for(let m of x3(g,t,r,h,f))s.push(m);for(l+=u.diffA,a+=u.diffB;cd&&m.fromB+a>p)break;c++}}return s}const bJ={scanLimit:500},y3=xt.fromClass(class{constructor(n){({deco:this.deco,gutter:this.gutter}=Vk(n))}update(n){(n.docChanged||n.viewportChanged||xJ(n.startState,n.state)||yJ(n.startState,n.state))&&({deco:this.deco,gutter:this.gutter}=Vk(n.view))}},{decorations:n=>n.deco}),qu=wr.low(DE({class:"cm-changeGutter",markers:n=>{var e;return((e=n.plugin(y3))===null||e===void 0?void 0:e.gutter)||Ze.empty}}));function xJ(n,e){return n.field(rl,!1)!=e.field(rl,!1)}function yJ(n,e){return n.facet(Ir)!=e.facet(Ir)}const Dk=Oe.line({class:"cm-changedLine"}),vJ=Oe.mark({class:"cm-changedText"}),wJ=Oe.mark({tagName:"ins",class:"cm-insertedLine"}),SJ=Oe.mark({tagName:"del",class:"cm-deletedLine"}),Nk=new class extends Gr{constructor(){super(...arguments),this.elementClass="cm-changedLineGutter"}};function kJ(n,e,t,r,i,s){let o=t?n.fromA:n.fromB,l=t?n.toA:n.toB,a=0;if(o!=l){i.add(o,o,Dk),i.add(o,l,t?SJ:wJ),s&&s.add(o,o,Nk);for(let c=e.iterRange(o,l-1),u=o;!c.next().done;){if(c.lineBreak){u++,i.add(u,u,Dk),s&&s.add(u,u,Nk);continue}let h=u+c.value.length;if(r)for(;a=c)break;(s?u.toA:u.toB)>a&&kJ(u,n.state.doc,s,r,o,l)}return{deco:o.finish(),gutter:l&&l.finish()}}class Wu extends Sr{constructor(e){super(),this.height=e}eq(e){return this.height==e.height}toDOM(){let e=document.createElement("div");return e.className="cm-mergeSpacer",e.style.height=this.height+"px",e}updateDOM(e){return e.style.height=this.height+"px",!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}}const Nf=Se.define({map:(n,e)=>n.map(e)}),ta=vt.define({create:()=>Oe.none,update:(n,e)=>{for(let t of e.effects)if(t.is(Nf))return t.value;return n.map(e.changes)},provide:n=>J.decorations.from(n)}),Hu=.01;function Zk(n,e){if(n.size!=e.size)return!1;let t=n.iter(),r=e.iter();for(;t.value;){if(t.from!=r.from||Math.abs(t.value.spec.widget.height-r.value.spec.widget.height)>1)return!1;t.next(),r.next()}return!0}function CJ(n,e,t){let r=new Dn,i=new Dn,s=n.state.field(ta).iter(),o=e.state.field(ta).iter(),l=0,a=0,c=0,u=0,h=n.viewport,f=e.viewport;for(let m=0;;m++){let b=mHu&&(u+=C,i.add(a,a,Oe.widget({widget:new Wu(C),block:!0,side:-1})))}if(O>l+1e3&&lh.from&&af.from){let y=Math.min(h.from-l,f.from-a);l+=y,a+=y,m--}else if(b)l=b.toA,a=b.toB;else break;for(;s.value&&s.fromHu&&i.add(e.state.doc.length,e.state.doc.length,Oe.widget({widget:new Wu(d),block:!0,side:1}));let p=r.finish(),g=i.finish();Zk(p,n.state.field(ta))||n.dispatch({effects:Nf.of(p)}),Zk(g,e.state.field(ta))||e.dispatch({effects:Nf.of(g)})}const WO=Se.define({map:(n,e)=>e.mapPos(n)});class _J extends Sr{constructor(e){super(),this.lines=e}eq(e){return this.lines==e.lines}toDOM(e){let t=document.createElement("div");return t.className="cm-collapsedLines",t.textContent="⦚ "+e.state.phrase("$ unchanged lines",this.lines)+" ⦚",t.addEventListener("click",r=>{let i=e.posAtDOM(r.target);e.dispatch({effects:WO.of(i)});let{side:s,sibling:o}=e.state.facet(Ir);o&&o().dispatch({effects:WO.of(PJ(i,e.state.field(rl),s=="a"))})}),t}ignoreEvent(e){return e instanceof MouseEvent}get estimatedHeight(){return 27}}function PJ(n,e,t){let r=0,i=0;for(let s=0;;s++){let o=s=n)return i+(n-r);[r,i]=t?[o.toA,o.toB]:[o.toB,o.toA]}}const TJ=vt.define({create(n){return Oe.none},update(n,e){n=n.map(e.changes);for(let t of e.effects)t.is(WO)&&(n=n.update({filter:r=>r!=t.value}));return n},provide:n=>J.decorations.from(n)});function Bk({margin:n=3,minSize:e=4}){return TJ.init(t=>EJ(t,n,e))}function EJ(n,e,t){let r=new Dn,i=n.facet(Ir).side=="a",s=n.field(rl),o=1;for(let l=0;;l++){let a=l=t&&r.add(n.doc.line(c).from,n.doc.line(u).to,Oe.replace({widget:new _J(h),block:!0})),!a)break;o=n.doc.lineAt(Math.min(n.doc.length,i?a.toA:a.toB)).number}return r.finish()}const $J=J.styleModule.of(new vi({".cm-mergeView":{overflowY:"auto"},".cm-mergeViewEditors":{display:"flex",alignItems:"stretch"},".cm-mergeViewEditor":{flexGrow:1,flexBasis:0,overflow:"hidden"},".cm-merge-revert":{width:"1.6em",flexGrow:0,flexShrink:0,position:"relative"},".cm-merge-revert button":{position:"absolute",display:"block",width:"100%",boxSizing:"border-box",textAlign:"center",background:"none",border:"none",font:"inherit",cursor:"pointer"}})),AJ=J.baseTheme({".cm-mergeView & .cm-scroller, .cm-mergeView &":{height:"auto !important",overflowY:"visible !important"},"&.cm-merge-a .cm-changedLine, .cm-deletedChunk":{backgroundColor:"rgba(160, 128, 100, .08)"},"&.cm-merge-b .cm-changedLine":{backgroundColor:"rgba(100, 160, 128, .08)"},"&light.cm-merge-a .cm-changedText, &light .cm-deletedChunk .cm-deletedText":{background:"linear-gradient(#ee443366, #ee443366) bottom/100% 2px no-repeat"},"&dark.cm-merge-a .cm-changedText, &dark .cm-deletedChunk .cm-deletedText":{background:"linear-gradient(#ffaa9966, #ffaa9966) bottom/100% 2px no-repeat"},"&light.cm-merge-b .cm-changedText":{background:"linear-gradient(#22bb2266, #22bb2266) bottom/100% 2px no-repeat"},"&dark.cm-merge-b .cm-changedText":{background:"linear-gradient(#88ff8866, #88ff8866) bottom/100% 2px no-repeat"},".cm-insertedLine, .cm-deletedLine":{textDecoration:"none"},".cm-deletedChunk":{paddingLeft:"6px","& .cm-chunkButtons":{position:"absolute",insetInlineEnd:"5px"},"& button":{border:"none",cursor:"pointer",color:"white",margin:"0 2px",borderRadius:"3px","&[name=accept]":{background:"#2a2"},"&[name=reject]":{background:"#d43"}}},".cm-collapsedLines":{padding:"5px 5px 5px 10px",cursor:"pointer"},"&light .cm-collapsedLines":{color:"#444",background:"linear-gradient(to bottom, transparent 0, #f3f3f3 30%, #f3f3f3 70%, transparent 100%)"},"&dark .cm-collapsedLines":{color:"#ddd",background:"linear-gradient(to bottom, transparent 0, #222 30%, #222 70%, transparent 100%)"},".cm-changeGutter":{width:"3px",paddingLeft:"1px"},"&light.cm-merge-a .cm-changedLineGutter, &light .cm-deletedLineGutter":{background:"#e43"},"&dark.cm-merge-a .cm-changedLineGutter, &dark .cm-deletedLineGutter":{background:"#fa9"},"&light.cm-merge-b .cm-changedLineGutter":{background:"#2b2"},"&dark.cm-merge-b .cm-changedLineGutter":{background:"#8f8"}}),Fk=new Ol,Yu=new Ol;class QJ{constructor(e){this.revertDOM=null,this.revertToA=!1,this.revertToLeft=!1,this.measuring=-1,this.diffConf=e.diffConfig||bJ;let t=[wr.low(y3),AJ,$J,ta,J.updateListener.of(h=>{this.measuring<0&&(h.heightChanged||h.viewportChanged)&&!h.transactions.some(f=>f.effects.some(d=>d.is(Nf)))&&this.measure()})],r=[Ir.of({side:"a",sibling:()=>this.b,highlightChanges:e.highlightChanges!==!1,markGutter:e.gutter!==!1})];e.gutter!==!1&&r.push(qu);let i=Ae.create({doc:e.a.doc,selection:e.a.selection,extensions:[e.a.extensions||[],J.editorAttributes.of({class:"cm-merge-a"}),Yu.of(r),t]}),s=[Ir.of({side:"b",sibling:()=>this.a,highlightChanges:e.highlightChanges!==!1,markGutter:e.gutter!==!1})];e.gutter!==!1&&s.push(qu);let o=Ae.create({doc:e.b.doc,selection:e.b.selection,extensions:[e.b.extensions||[],J.editorAttributes.of({class:"cm-merge-b"}),Yu.of(s),t]});this.chunks=Mo.build(i.doc,o.doc,this.diffConf);let l=[rl.init(()=>this.chunks),Fk.of(e.collapseUnchanged?Bk(e.collapseUnchanged):[])];i=i.update({effects:Se.appendConfig.of(l)}).state,o=o.update({effects:Se.appendConfig.of(l)}).state,this.dom=document.createElement("div"),this.dom.className="cm-mergeView",this.editorDOM=this.dom.appendChild(document.createElement("div")),this.editorDOM.className="cm-mergeViewEditors";let a=e.orientation||"a-b",c=document.createElement("div");c.className="cm-mergeViewEditor";let u=document.createElement("div");u.className="cm-mergeViewEditor",this.editorDOM.appendChild(a=="a-b"?c:u),this.editorDOM.appendChild(a=="a-b"?u:c),this.a=new J({state:i,parent:c,root:e.root,dispatchTransactions:h=>this.dispatch(h,this.a)}),this.b=new J({state:o,parent:u,root:e.root,dispatchTransactions:h=>this.dispatch(h,this.b)}),this.setupRevertControls(!!e.revertControls,e.revertControls=="b-to-a",e.renderRevertControl),e.parent&&e.parent.appendChild(this.dom),this.scheduleMeasure()}dispatch(e,t){if(e.some(r=>r.docChanged)){let r=e[e.length-1],i=e.reduce((o,l)=>o.compose(l.changes),St.empty(e[0].startState.doc.length));this.chunks=t==this.a?Mo.updateA(this.chunks,r.newDoc,this.b.state.doc,i,this.diffConf):Mo.updateB(this.chunks,this.a.state.doc,r.newDoc,i,this.diffConf),t.update([...e,r.state.update({effects:qO.of(this.chunks)})]);let s=t==this.a?this.b:this.a;s.update([s.state.update({effects:qO.of(this.chunks)})]),this.scheduleMeasure()}else t.update(e)}reconfigure(e){if("diffConfig"in e&&(this.diffConf=e.diffConfig),"orientation"in e){let s=e.orientation!="b-a";if(s!=(this.editorDOM.firstChild==this.a.dom.parentNode)){let o=this.a.dom.parentNode,l=this.b.dom.parentNode;o.remove(),l.remove(),this.editorDOM.insertBefore(s?o:l,this.editorDOM.firstChild),this.editorDOM.appendChild(s?l:o),this.revertToLeft=!this.revertToLeft,this.revertDOM&&(this.revertDOM.textContent="")}}if("revertControls"in e||"renderRevertControl"in e){let s=!!this.revertDOM,o=this.revertToA,l=this.renderRevert;"revertControls"in e&&(s=!!e.revertControls,o=e.revertControls=="b-to-a"),"renderRevertControl"in e&&(l=e.renderRevertControl),this.setupRevertControls(s,o,l)}let t="highlightChanges"in e,r="gutter"in e,i="collapseUnchanged"in e;if(t||r||i){let s=[],o=[];if(t||r){let l=this.a.state.facet(Ir),a=r?e.gutter!==!1:l.markGutter,c=t?e.highlightChanges!==!1:l.highlightChanges;s.push(Yu.reconfigure([Ir.of({side:"a",sibling:()=>this.b,highlightChanges:c,markGutter:a}),a?qu:[]])),o.push(Yu.reconfigure([Ir.of({side:"b",sibling:()=>this.a,highlightChanges:c,markGutter:a}),a?qu:[]]))}if(i){let l=Fk.reconfigure(e.collapseUnchanged?Bk(e.collapseUnchanged):[]);s.push(l),o.push(l)}this.a.dispatch({effects:s}),this.b.dispatch({effects:o})}this.scheduleMeasure()}setupRevertControls(e,t,r){this.revertToA=t,this.revertToLeft=this.revertToA==(this.editorDOM.firstChild==this.a.dom.parentNode),this.renderRevert=r,!e&&this.revertDOM?(this.revertDOM.remove(),this.revertDOM=null):e&&!this.revertDOM?(this.revertDOM=this.editorDOM.insertBefore(document.createElement("div"),this.editorDOM.firstChild.nextSibling),this.revertDOM.addEventListener("mousedown",i=>this.revertClicked(i)),this.revertDOM.className="cm-merge-revert"):this.revertDOM&&(this.revertDOM.textContent="")}scheduleMeasure(){if(this.measuring<0){let e=this.dom.ownerDocument.defaultView||window;this.measuring=e.requestAnimationFrame(()=>{this.measuring=-1,this.measure()})}}measure(){CJ(this.a,this.b,this.chunks),this.revertDOM&&this.updateRevertButtons()}updateRevertButtons(){let e=this.revertDOM,t=e.firstChild,r=this.a.viewport,i=this.b.viewport;for(let s=0;sr.to||o.fromB>i.to)break;if(o.fromA-1&&(this.dom.ownerDocument.defaultView||window).cancelAnimationFrame(this.measuring),this.dom.remove()}}function zk(n){let e=n.nextSibling;return n.remove(),e}class Vf{static create(e,t,r,i,s){let o=i+(i<<8)+e+(t<<4)|0;return new Vf(e,t,r,o,s,[],[])}constructor(e,t,r,i,s,o,l){this.type=e,this.value=t,this.from=r,this.hash=i,this.end=s,this.children=o,this.positions=l,this.hashProp=[[ke.contextHash,i]]}addChild(e,t){e.prop(ke.contextHash)!=this.hash&&(e=new Re(e.type,e.children,e.positions,e.length,this.hashProp)),this.children.push(e),this.positions.push(t)}toTree(e,t=this.end){let r=this.children.length-1;return r>=0&&(t=Math.max(t,this.positions[r]+this.children[r].length+this.from)),new Re(e.types[this.type],this.children,this.positions,t-this.from).balance({makeTree:(i,s,o)=>new Re(Pt.none,i,s,o,this.hashProp)})}}var ee;(function(n){n[n.Document=1]="Document",n[n.CodeBlock=2]="CodeBlock",n[n.FencedCode=3]="FencedCode",n[n.Blockquote=4]="Blockquote",n[n.HorizontalRule=5]="HorizontalRule",n[n.BulletList=6]="BulletList",n[n.OrderedList=7]="OrderedList",n[n.ListItem=8]="ListItem",n[n.ATXHeading1=9]="ATXHeading1",n[n.ATXHeading2=10]="ATXHeading2",n[n.ATXHeading3=11]="ATXHeading3",n[n.ATXHeading4=12]="ATXHeading4",n[n.ATXHeading5=13]="ATXHeading5",n[n.ATXHeading6=14]="ATXHeading6",n[n.SetextHeading1=15]="SetextHeading1",n[n.SetextHeading2=16]="SetextHeading2",n[n.HTMLBlock=17]="HTMLBlock",n[n.LinkReference=18]="LinkReference",n[n.Paragraph=19]="Paragraph",n[n.CommentBlock=20]="CommentBlock",n[n.ProcessingInstructionBlock=21]="ProcessingInstructionBlock",n[n.Escape=22]="Escape",n[n.Entity=23]="Entity",n[n.HardBreak=24]="HardBreak",n[n.Emphasis=25]="Emphasis",n[n.StrongEmphasis=26]="StrongEmphasis",n[n.Link=27]="Link",n[n.Image=28]="Image",n[n.InlineCode=29]="InlineCode",n[n.HTMLTag=30]="HTMLTag",n[n.Comment=31]="Comment",n[n.ProcessingInstruction=32]="ProcessingInstruction",n[n.Autolink=33]="Autolink",n[n.HeaderMark=34]="HeaderMark",n[n.QuoteMark=35]="QuoteMark",n[n.ListMark=36]="ListMark",n[n.LinkMark=37]="LinkMark",n[n.EmphasisMark=38]="EmphasisMark",n[n.CodeMark=39]="CodeMark",n[n.CodeText=40]="CodeText",n[n.CodeInfo=41]="CodeInfo",n[n.LinkTitle=42]="LinkTitle",n[n.LinkLabel=43]="LinkLabel",n[n.URL=44]="URL"})(ee||(ee={}));class RJ{constructor(e,t){this.start=e,this.content=t,this.marks=[],this.parsers=[]}}class MJ{constructor(){this.text="",this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let e=this.skipSpace(this.basePos);this.indent=this.countIndent(e,this.pos,this.indent),this.pos=e,this.next=e==this.text.length?-1:this.text.charCodeAt(e)}skipSpace(e){return ya(this.text,e)}reset(e){for(this.text=e,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.length;)this.markers.pop()}moveBase(e){this.basePos=e,this.baseIndent=this.countIndent(e,this.pos,this.indent)}moveBaseColumn(e){this.baseIndent=e,this.basePos=this.findColumn(e)}addMarker(e){this.markers.push(e)}countIndent(e,t=0,r=0){for(let i=t;i=e.stack[t.depth+1].value+t.baseIndent)return!0;if(t.indent>=t.baseIndent+4)return!1;let r=(n.type==ee.OrderedList?fx:hx)(t,e,!1);return r>0&&(n.type!=ee.BulletList||ux(t,e,!1)<0)&&t.text.charCodeAt(t.pos+r-1)==n.value}const v3={[ee.Blockquote](n,e,t){return t.next!=62?!1:(t.markers.push(Ve(ee.QuoteMark,e.lineStart+t.pos,e.lineStart+t.pos+1)),t.moveBase(t.pos+(Kn(t.text.charCodeAt(t.pos+1))?2:1)),n.end=e.lineStart+t.text.length,!0)},[ee.ListItem](n,e,t){return t.indent-1?!1:(t.moveBaseColumn(t.baseIndent+n.value),!0)},[ee.OrderedList]:jk,[ee.BulletList]:jk,[ee.Document](){return!0}};function Kn(n){return n==32||n==9||n==10||n==13}function ya(n,e=0){for(;et&&Kn(n.charCodeAt(e-1));)e--;return e}function w3(n){if(n.next!=96&&n.next!=126)return-1;let e=n.pos+1;for(;e-1&&n.depth==e.stack.length&&e.parser.leafBlockParsers.indexOf($3.SetextHeading)>-1||r<3?-1:1}function k3(n,e){for(let t=n.stack.length-1;t>=0;t--)if(n.stack[t].type==e)return!0;return!1}function hx(n,e,t){return(n.next==45||n.next==43||n.next==42)&&(n.pos==n.text.length-1||Kn(n.text.charCodeAt(n.pos+1)))&&(!t||k3(e,ee.BulletList)||n.skipSpace(n.pos+2)=48&&i<=57;){r++;if(r==n.text.length)return-1;i=n.text.charCodeAt(r)}return r==n.pos||r>n.pos+9||i!=46&&i!=41||rn.pos+1||n.next!=49)?-1:r+1-n.pos}function C3(n){if(n.next!=35)return-1;let e=n.pos+1;for(;e6?-1:t}function _3(n){if(n.next!=45&&n.next!=61||n.indent>=n.baseIndent+4)return-1;let e=n.pos+1;for(;e/,T3=/\?>/,YO=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*"),ie=w(ee,"?>"),ye=w(te,"]]>"),ge=Y({Text:p.content,"StartTag StartCloseTag EndTag SelfCloseEndTag":p.angleBracket,TagName:p.tagName,"MismatchedCloseTag/TagName":[p.tagName,p.invalid],AttributeName:p.attributeName,AttributeValue:p.attributeValue,Is:p.definitionOperator,"EntityReference CharacterReference":p.character,Comment:p.blockComment,ProcessingInst:p.processingInstruction,DoctypeDecl:p.documentMeta,Cdata:p.special(p.string)}),me=I.deserialize({version:14,states:",SOQOaOOOrOxO'#CfOzOpO'#CiO!tOaO'#CgOOOP'#Cg'#CgO!{OrO'#CrO#TOtO'#CsO#]OpO'#CtOOOP'#DS'#DSOOOP'#Cv'#CvQQOaOOOOOW'#Cw'#CwO#eOxO,59QOOOP,59Q,59QOOOO'#Cx'#CxO#mOpO,59TO#uO!bO,59TOOOP'#C{'#C{O$TOaO,59RO$[OpO'#CoOOOP,59R,59ROOOQ'#C|'#C|O$dOrO,59^OOOP,59^,59^OOOS'#C}'#C}O$lOtO,59_OOOP,59_,59_O$tOpO,59`O$|OpO,59`OOOP-E6t-E6tOOOW-E6u-E6uOOOP1G.l1G.lOOOO-E6v-E6vO%UO!bO1G.oO%UO!bO1G.oO%dOpO'#CkO%lO!bO'#CyO%zO!bO1G.oOOOP1G.o1G.oOOOP1G.w1G.wOOOP-E6y-E6yOOOP1G.m1G.mO&VOpO,59ZO&_OpO,59ZOOOQ-E6z-E6zOOOP1G.x1G.xOOOS-E6{-E6{OOOP1G.y1G.yO&gOpO1G.zO&gOpO1G.zOOOP1G.z1G.zO&oO!bO7+$ZO&}O!bO7+$ZOOOP7+$Z7+$ZOOOP7+$c7+$cO'YOpO,59VO'bOpO,59VO'jO!bO,59eOOOO-E6w-E6wO'xOpO1G.uO'xOpO1G.uOOOP1G.u1G.uO(QOpO7+$fOOOP7+$f7+$fO(YO!bO<d!d;'S%y;'S;=`&_<%lO%yX>iV{WOr%ysv%yw!}%y!}#O?O#O;'S%y;'S;=`&_<%lO%yX?VT{WxPOr%ysv%yw;'S%y;'S;=`&_<%lO%yX?kV{WOr%ysv%yw#W%y#W#X@Q#X;'S%y;'S;=`&_<%lO%yX@VV{WOr%ysv%yw#T%y#T#U@l#U;'S%y;'S;=`&_<%lO%yX@qV{WOr%ysv%yw#h%y#h#iAW#i;'S%y;'S;=`&_<%lO%yXA]V{WOr%ysv%yw#T%y#T#U>d#U;'S%y;'S;=`&_<%lO%yXAwV{WOr%ysv%yw#c%y#c#dB^#d;'S%y;'S;=`&_<%lO%yXBcV{WOr%ysv%yw#V%y#V#WBx#W;'S%y;'S;=`&_<%lO%yXB}V{WOr%ysv%yw#h%y#h#iCd#i;'S%y;'S;=`&_<%lO%yXCiV{WOr%ysv%yw#m%y#m#nDO#n;'S%y;'S;=`&_<%lO%yXDTV{WOr%ysv%yw#d%y#d#eDj#e;'S%y;'S;=`&_<%lO%yXDoV{WOr%ysv%yw#X%y#X#Y9i#Y;'S%y;'S;=`&_<%lO%yXE]T!PP{WOr%ysv%yw;'S%y;'S;=`&_<%lO%yZEuWaQVP{WOr$nrs%_sv$nw!^$n!^!_%y!_;'S$n;'S;=`&e<%lO$n_FhW[UVP{WOr$nrs%_sv$nw!^$n!^!_%y!_;'S$n;'S;=`&e<%lO$nZGXYVP{WOr$nrs%_sv$nw!^$n!^!_%y!_!`$n!`!aGw!a;'S$n;'S;=`&e<%lO$nZHQW!OQVP{WOr$nrs%_sv$nw!^$n!^!_%y!_;'S$n;'S;=`&e<%lO$nZHqYVP{WOr$nrs%_sv$nw!^$n!^!_%y!_#P$n#P#QIa#Q;'S$n;'S;=`&e<%lO$nZIhYVP{WOr$nrs%_sv$nw!^$n!^!_%y!_!`$n!`!aJW!a;'S$n;'S;=`&e<%lO$nZJaWwQVP{WOr$nrs%_sv$nw!^$n!^!_%y!_;'S$n;'S;=`&e<%lO$n",tokenizers:[oe,se,ie,ye,0,1,2,3],topRules:{Document:[0,6]},tokenPrec:0});function h(e,t){let O=t&&t.getChild("TagName");return O?e.sliceString(O.from,O.to):""}function V(e,t){let O=t&&t.firstChild;return!O||O.name!="OpenTag"?"":h(e,O)}function $e(e,t,O){let n=t&&t.getChildren("Attribute").find(l=>l.from<=O&&l.to>=O),a=n&&n.getChild("AttributeName");return a?e.sliceString(a.from,a.to):""}function P(e){for(let t=e&&e.parent;t;t=t.parent)if(t.name=="Element")return t;return null}function ce(e,t){var O;let n=Z(e).resolveInner(t,-1),a=null;for(let l=n;!a&&l.parent;l=l.parent)(l.name=="OpenTag"||l.name=="CloseTag"||l.name=="SelfClosingTag"||l.name=="MismatchedCloseTag")&&(a=l);if(a&&(a.to>t||a.lastChild.type.isError)){let l=a.parent;if(n.name=="TagName")return a.name=="CloseTag"||a.name=="MismatchedCloseTag"?{type:"closeTag",from:n.from,context:l}:{type:"openTag",from:n.from,context:P(l)};if(n.name=="AttributeName")return{type:"attrName",from:n.from,context:a};if(n.name=="AttributeValue")return{type:"attrValue",from:n.from,context:a};let s=n==a||n.name=="Attribute"?n.childBefore(t):n;return(s==null?void 0:s.name)=="StartTag"?{type:"openTag",from:t,context:P(l)}:(s==null?void 0:s.name)=="StartCloseTag"&&s.to<=t?{type:"closeTag",from:t,context:l}:(s==null?void 0:s.name)=="Is"?{type:"attrValue",from:t,context:a}:s?{type:"attrName",from:t,context:a}:null}else if(n.name=="StartCloseTag")return{type:"closeTag",from:t,context:n.parent};for(;n.parent&&n.to==t&&!(!((O=n.lastChild)===null||O===void 0)&&O.type.isError);)n=n.parent;return n.name=="Element"||n.name=="Text"||n.name=="Document"?{type:"tag",from:t,context:n.name=="Element"?n:P(n)}:null}class ue{constructor(t,O,n){this.attrs=O,this.attrValues=n,this.children=[],this.name=t.name,this.completion=Object.assign(Object.assign({type:"type"},t.completion||{}),{label:this.name}),this.openCompletion=Object.assign(Object.assign({},this.completion),{label:"<"+this.name}),this.closeCompletion=Object.assign(Object.assign({},this.completion),{label:"",boost:2}),this.closeNameCompletion=Object.assign(Object.assign({},this.completion),{label:this.name+">"}),this.text=t.textContent?t.textContent.map(a=>({label:a,type:"text"})):[]}}const v=/^[:\-\.\w\u00b7-\uffff]*$/;function R(e){return Object.assign(Object.assign({type:"property"},e.completion||{}),{label:e.name})}function G(e){return typeof e=="string"?{label:`"${e}"`,type:"constant"}:/^"/.test(e.label)?e:Object.assign(Object.assign({},e),{label:`"${e.label}"`})}function pe(e,t){let O=[],n=[],a=Object.create(null);for(let r of t){let m=R(r);O.push(m),r.global&&n.push(m),r.values&&(a[r.name]=r.values.map(G))}let l=[],s=[],S=Object.create(null);for(let r of e){let m=n,y=a;r.attributes&&(m=m.concat(r.attributes.map(o=>typeof o=="string"?O.find(f=>f.label==o)||{label:o,type:"property"}:(o.values&&(y==a&&(y=Object.create(y)),y[o.name]=o.values.map(G)),R(o)))));let u=new ue(r,m,y);S[u.name]=u,l.push(u),r.top&&s.push(u)}s.length||(s=l);for(let r=0;r{var m;let{doc:y}=r.state,u=ce(r.state,r.pos);if(!u||u.type=="tag"&&!r.explicit)return null;let{type:o,from:f,context:$}=u;if(o=="openTag"){let i=s,g=V(y,$);if(g){let c=S[g];i=(c==null?void 0:c.children)||l}return{from:f,options:i.map(c=>c.completion),validFor:v}}else if(o=="closeTag"){let i=V(y,$);return i?{from:f,to:r.pos+(y.sliceString(r.pos,r.pos+1)==">"?1:0),options:[((m=S[i])===null||m===void 0?void 0:m.closeNameCompletion)||{label:i+">",type:"type"}],validFor:v}:null}else if(o=="attrName"){let i=S[h(y,$)];return{from:f,options:(i==null?void 0:i.attrs)||n,validFor:v}}else if(o=="attrValue"){let i=$e(y,$,f);if(!i)return null;let g=S[h(y,$)],c=((g==null?void 0:g.attrValues)||a)[i];return!c||!c.length?null:{from:f,to:r.pos+(y.sliceString(r.pos,r.pos+1)=='"'?1:0),options:c,validFor:/^"[^"]*"?$/}}else if(o=="tag"){let i=V(y,$),g=S[i],c=[],d=$&&$.lastChild;i&&(!d||d.name!="CloseTag"||h(y,d)!=i)&&c.push(g?g.closeCompletion:{label:"",type:"type",boost:2});let C=c.concat(((g==null?void 0:g.children)||($?l:s)).map(T=>T.openCompletion));if($&&(g!=null&&g.text.length)){let T=$.firstChild;T.to>r.pos-20&&!/\S/.test(r.state.sliceDoc(T.to,r.pos))&&(C=C.concat(g.text))}return{from:f,options:C,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}else return null}}const W=j.define({name:"xml",parser:me.configure({props:[U.add({Element(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"OpenTag CloseTag SelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),z.add({Element(e){let t=e.firstChild,O=e.lastChild;return!t||t.name!="OpenTag"?null:{from:t.to,to:O.name=="CloseTag"?O.from:e.to}}}),q.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:""}},indentOnInput:/^\s*<\/$/}});function Ve(e={}){let t=[W.data.of({autocomplete:pe(e.elements||[],e.attributes||[])})];return e.autoCloseTags!==!1&&t.push(Se),new D(W,t)}function N(e,t,O=e.length){if(!t)return"";let n=t.firstChild,a=n&&n.getChild("TagName");return a?e.sliceString(a.from,Math.min(a.to,O)):""}const Se=M.inputHandler.of((e,t,O,n,a)=>{if(e.composing||e.state.readOnly||t!=O||n!=">"&&n!="/"||!W.isActiveAt(e.state,t,-1))return!1;let l=a(),{state:s}=l,S=s.changeByRange(r=>{var m,y,u;let{head:o}=r,f=s.doc.sliceString(o-1,o)==n,$=Z(s).resolveInner(o,-1),i;if(f&&n==">"&&$.name=="EndTag"){let g=$.parent;if(((y=(m=g.parent)===null||m===void 0?void 0:m.lastChild)===null||y===void 0?void 0:y.name)!="CloseTag"&&(i=N(s.doc,g.parent,o))){let c=o+(s.doc.sliceString(o,o+1)===">"?1:0),d=``;return{range:r,changes:{from:o,to:c,insert:d}}}}else if(f&&n=="/"&&$.name=="StartCloseTag"){let g=$.parent;if($.from==o-2&&((u=g.lastChild)===null||u===void 0?void 0:u.name)!="CloseTag"&&(i=N(s.doc,g,o))){let c=o+(s.doc.sliceString(o,o+1)===">"?1:0),d=`${i}>`;return{range:B.cursor(o+d.length,-1),changes:{from:o,to:c,insert:d}}}}return{range:r}});return S.changes.empty?!1:(e.dispatch([l,s.update(S,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});export{Se as autoCloseTags,pe as completeFromSchema,Ve as xml,W as xmlLanguage}; +import{C as A,E as k,s as Y,t as p,b as I,L as j,i as U,f as z,u as q,a as D,o as M,g as Z,p as B}from"./MarkdownEditor-BjREHNgK.js";import"./index-4Hagg-7l.js";import"./index.lazy-BRB6PNxD.js";import"./isAddressEqual-DlPIwSPc.js";import"./secp256k1-CibHJEZu.js";const _=1,F=2,J=3,H=4,L=5,K=35,ee=36,te=37,ne=11,Oe=13;function ae(e){return e==45||e==46||e==58||e>=65&&e<=90||e==95||e>=97&&e<=122||e>=161}function re(e){return e==9||e==10||e==13||e==32}let X=null,Q=null,E=0;function b(e,t){let O=e.pos+t;if(Q==e&&E==O)return X;for(;re(e.peek(t));)t++;let n="";for(;;){let a=e.peek(t);if(!ae(a))break;n+=String.fromCharCode(a),t++}return Q=e,E=O,X=n||null}function x(e,t){this.name=e,this.parent=t,this.hash=t?t.hash:0;for(let O=0;O{if(e.next==60){if(e.advance(),e.next==47){e.advance();let O=b(e,0);if(!O)return e.acceptToken(L);if(t.context&&O==t.context.name)return e.acceptToken(F);for(let n=t.context;n;n=n.parent)if(n.name==O)return e.acceptToken(J,-2);e.acceptToken(H)}else if(e.next!=33&&e.next!=63)return e.acceptToken(_)}},{contextual:!0});function w(e,t){return new k(O=>{let n=0,a=t.charCodeAt(0);e:for(;!(O.next<0);O.advance(),n++)if(O.next==a){for(let l=1;l"),ie=w(ee,"?>"),ye=w(te,"]]>"),ge=Y({Text:p.content,"StartTag StartCloseTag EndTag SelfCloseEndTag":p.angleBracket,TagName:p.tagName,"MismatchedCloseTag/TagName":[p.tagName,p.invalid],AttributeName:p.attributeName,AttributeValue:p.attributeValue,Is:p.definitionOperator,"EntityReference CharacterReference":p.character,Comment:p.blockComment,ProcessingInst:p.processingInstruction,DoctypeDecl:p.documentMeta,Cdata:p.special(p.string)}),me=I.deserialize({version:14,states:",SOQOaOOOrOxO'#CfOzOpO'#CiO!tOaO'#CgOOOP'#Cg'#CgO!{OrO'#CrO#TOtO'#CsO#]OpO'#CtOOOP'#DS'#DSOOOP'#Cv'#CvQQOaOOOOOW'#Cw'#CwO#eOxO,59QOOOP,59Q,59QOOOO'#Cx'#CxO#mOpO,59TO#uO!bO,59TOOOP'#C{'#C{O$TOaO,59RO$[OpO'#CoOOOP,59R,59ROOOQ'#C|'#C|O$dOrO,59^OOOP,59^,59^OOOS'#C}'#C}O$lOtO,59_OOOP,59_,59_O$tOpO,59`O$|OpO,59`OOOP-E6t-E6tOOOW-E6u-E6uOOOP1G.l1G.lOOOO-E6v-E6vO%UO!bO1G.oO%UO!bO1G.oO%dOpO'#CkO%lO!bO'#CyO%zO!bO1G.oOOOP1G.o1G.oOOOP1G.w1G.wOOOP-E6y-E6yOOOP1G.m1G.mO&VOpO,59ZO&_OpO,59ZOOOQ-E6z-E6zOOOP1G.x1G.xOOOS-E6{-E6{OOOP1G.y1G.yO&gOpO1G.zO&gOpO1G.zOOOP1G.z1G.zO&oO!bO7+$ZO&}O!bO7+$ZOOOP7+$Z7+$ZOOOP7+$c7+$cO'YOpO,59VO'bOpO,59VO'jO!bO,59eOOOO-E6w-E6wO'xOpO1G.uO'xOpO1G.uOOOP1G.u1G.uO(QOpO7+$fOOOP7+$f7+$fO(YO!bO<d!d;'S%y;'S;=`&_<%lO%yX>iV{WOr%ysv%yw!}%y!}#O?O#O;'S%y;'S;=`&_<%lO%yX?VT{WxPOr%ysv%yw;'S%y;'S;=`&_<%lO%yX?kV{WOr%ysv%yw#W%y#W#X@Q#X;'S%y;'S;=`&_<%lO%yX@VV{WOr%ysv%yw#T%y#T#U@l#U;'S%y;'S;=`&_<%lO%yX@qV{WOr%ysv%yw#h%y#h#iAW#i;'S%y;'S;=`&_<%lO%yXA]V{WOr%ysv%yw#T%y#T#U>d#U;'S%y;'S;=`&_<%lO%yXAwV{WOr%ysv%yw#c%y#c#dB^#d;'S%y;'S;=`&_<%lO%yXBcV{WOr%ysv%yw#V%y#V#WBx#W;'S%y;'S;=`&_<%lO%yXB}V{WOr%ysv%yw#h%y#h#iCd#i;'S%y;'S;=`&_<%lO%yXCiV{WOr%ysv%yw#m%y#m#nDO#n;'S%y;'S;=`&_<%lO%yXDTV{WOr%ysv%yw#d%y#d#eDj#e;'S%y;'S;=`&_<%lO%yXDoV{WOr%ysv%yw#X%y#X#Y9i#Y;'S%y;'S;=`&_<%lO%yXE]T!PP{WOr%ysv%yw;'S%y;'S;=`&_<%lO%yZEuWaQVP{WOr$nrs%_sv$nw!^$n!^!_%y!_;'S$n;'S;=`&e<%lO$n_FhW[UVP{WOr$nrs%_sv$nw!^$n!^!_%y!_;'S$n;'S;=`&e<%lO$nZGXYVP{WOr$nrs%_sv$nw!^$n!^!_%y!_!`$n!`!aGw!a;'S$n;'S;=`&e<%lO$nZHQW!OQVP{WOr$nrs%_sv$nw!^$n!^!_%y!_;'S$n;'S;=`&e<%lO$nZHqYVP{WOr$nrs%_sv$nw!^$n!^!_%y!_#P$n#P#QIa#Q;'S$n;'S;=`&e<%lO$nZIhYVP{WOr$nrs%_sv$nw!^$n!^!_%y!_!`$n!`!aJW!a;'S$n;'S;=`&e<%lO$nZJaWwQVP{WOr$nrs%_sv$nw!^$n!^!_%y!_;'S$n;'S;=`&e<%lO$n",tokenizers:[oe,se,ie,ye,0,1,2,3],topRules:{Document:[0,6]},tokenPrec:0});function h(e,t){let O=t&&t.getChild("TagName");return O?e.sliceString(O.from,O.to):""}function V(e,t){let O=t&&t.firstChild;return!O||O.name!="OpenTag"?"":h(e,O)}function $e(e,t,O){let n=t&&t.getChildren("Attribute").find(l=>l.from<=O&&l.to>=O),a=n&&n.getChild("AttributeName");return a?e.sliceString(a.from,a.to):""}function P(e){for(let t=e&&e.parent;t;t=t.parent)if(t.name=="Element")return t;return null}function ce(e,t){var O;let n=Z(e).resolveInner(t,-1),a=null;for(let l=n;!a&&l.parent;l=l.parent)(l.name=="OpenTag"||l.name=="CloseTag"||l.name=="SelfClosingTag"||l.name=="MismatchedCloseTag")&&(a=l);if(a&&(a.to>t||a.lastChild.type.isError)){let l=a.parent;if(n.name=="TagName")return a.name=="CloseTag"||a.name=="MismatchedCloseTag"?{type:"closeTag",from:n.from,context:l}:{type:"openTag",from:n.from,context:P(l)};if(n.name=="AttributeName")return{type:"attrName",from:n.from,context:a};if(n.name=="AttributeValue")return{type:"attrValue",from:n.from,context:a};let s=n==a||n.name=="Attribute"?n.childBefore(t):n;return(s==null?void 0:s.name)=="StartTag"?{type:"openTag",from:t,context:P(l)}:(s==null?void 0:s.name)=="StartCloseTag"&&s.to<=t?{type:"closeTag",from:t,context:l}:(s==null?void 0:s.name)=="Is"?{type:"attrValue",from:t,context:a}:s?{type:"attrName",from:t,context:a}:null}else if(n.name=="StartCloseTag")return{type:"closeTag",from:t,context:n.parent};for(;n.parent&&n.to==t&&!(!((O=n.lastChild)===null||O===void 0)&&O.type.isError);)n=n.parent;return n.name=="Element"||n.name=="Text"||n.name=="Document"?{type:"tag",from:t,context:n.name=="Element"?n:P(n)}:null}class ue{constructor(t,O,n){this.attrs=O,this.attrValues=n,this.children=[],this.name=t.name,this.completion=Object.assign(Object.assign({type:"type"},t.completion||{}),{label:this.name}),this.openCompletion=Object.assign(Object.assign({},this.completion),{label:"<"+this.name}),this.closeCompletion=Object.assign(Object.assign({},this.completion),{label:"",boost:2}),this.closeNameCompletion=Object.assign(Object.assign({},this.completion),{label:this.name+">"}),this.text=t.textContent?t.textContent.map(a=>({label:a,type:"text"})):[]}}const v=/^[:\-\.\w\u00b7-\uffff]*$/;function R(e){return Object.assign(Object.assign({type:"property"},e.completion||{}),{label:e.name})}function G(e){return typeof e=="string"?{label:`"${e}"`,type:"constant"}:/^"/.test(e.label)?e:Object.assign(Object.assign({},e),{label:`"${e.label}"`})}function pe(e,t){let O=[],n=[],a=Object.create(null);for(let r of t){let m=R(r);O.push(m),r.global&&n.push(m),r.values&&(a[r.name]=r.values.map(G))}let l=[],s=[],S=Object.create(null);for(let r of e){let m=n,y=a;r.attributes&&(m=m.concat(r.attributes.map(o=>typeof o=="string"?O.find(f=>f.label==o)||{label:o,type:"property"}:(o.values&&(y==a&&(y=Object.create(y)),y[o.name]=o.values.map(G)),R(o)))));let u=new ue(r,m,y);S[u.name]=u,l.push(u),r.top&&s.push(u)}s.length||(s=l);for(let r=0;r{var m;let{doc:y}=r.state,u=ce(r.state,r.pos);if(!u||u.type=="tag"&&!r.explicit)return null;let{type:o,from:f,context:$}=u;if(o=="openTag"){let i=s,g=V(y,$);if(g){let c=S[g];i=(c==null?void 0:c.children)||l}return{from:f,options:i.map(c=>c.completion),validFor:v}}else if(o=="closeTag"){let i=V(y,$);return i?{from:f,to:r.pos+(y.sliceString(r.pos,r.pos+1)==">"?1:0),options:[((m=S[i])===null||m===void 0?void 0:m.closeNameCompletion)||{label:i+">",type:"type"}],validFor:v}:null}else if(o=="attrName"){let i=S[h(y,$)];return{from:f,options:(i==null?void 0:i.attrs)||n,validFor:v}}else if(o=="attrValue"){let i=$e(y,$,f);if(!i)return null;let g=S[h(y,$)],c=((g==null?void 0:g.attrValues)||a)[i];return!c||!c.length?null:{from:f,to:r.pos+(y.sliceString(r.pos,r.pos+1)=='"'?1:0),options:c,validFor:/^"[^"]*"?$/}}else if(o=="tag"){let i=V(y,$),g=S[i],c=[],d=$&&$.lastChild;i&&(!d||d.name!="CloseTag"||h(y,d)!=i)&&c.push(g?g.closeCompletion:{label:"",type:"type",boost:2});let C=c.concat(((g==null?void 0:g.children)||($?l:s)).map(T=>T.openCompletion));if($&&(g!=null&&g.text.length)){let T=$.firstChild;T.to>r.pos-20&&!/\S/.test(r.state.sliceDoc(T.to,r.pos))&&(C=C.concat(g.text))}return{from:f,options:C,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}else return null}}const W=j.define({name:"xml",parser:me.configure({props:[U.add({Element(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"OpenTag CloseTag SelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),z.add({Element(e){let t=e.firstChild,O=e.lastChild;return!t||t.name!="OpenTag"?null:{from:t.to,to:O.name=="CloseTag"?O.from:e.to}}}),q.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:""}},indentOnInput:/^\s*<\/$/}});function Ve(e={}){let t=[W.data.of({autocomplete:pe(e.elements||[],e.attributes||[])})];return e.autoCloseTags!==!1&&t.push(Se),new D(W,t)}function N(e,t,O=e.length){if(!t)return"";let n=t.firstChild,a=n&&n.getChild("TagName");return a?e.sliceString(a.from,Math.min(a.to,O)):""}const Se=M.inputHandler.of((e,t,O,n,a)=>{if(e.composing||e.state.readOnly||t!=O||n!=">"&&n!="/"||!W.isActiveAt(e.state,t,-1))return!1;let l=a(),{state:s}=l,S=s.changeByRange(r=>{var m,y,u;let{head:o}=r,f=s.doc.sliceString(o-1,o)==n,$=Z(s).resolveInner(o,-1),i;if(f&&n==">"&&$.name=="EndTag"){let g=$.parent;if(((y=(m=g.parent)===null||m===void 0?void 0:m.lastChild)===null||y===void 0?void 0:y.name)!="CloseTag"&&(i=N(s.doc,g.parent,o))){let c=o+(s.doc.sliceString(o,o+1)===">"?1:0),d=``;return{range:r,changes:{from:o,to:c,insert:d}}}}else if(f&&n=="/"&&$.name=="StartCloseTag"){let g=$.parent;if($.from==o-2&&((u=g.lastChild)===null||u===void 0?void 0:u.name)!="CloseTag"&&(i=N(s.doc,g,o))){let c=o+(s.doc.sliceString(o,o+1)===">"?1:0),d=`${i}>`;return{range:B.cursor(o+d.length,-1),changes:{from:o,to:c,insert:d}}}}return{range:r}});return S.changes.empty?!1:(e.dispatch([l,s.update(S,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});export{Se as autoCloseTags,pe as completeFromSchema,Ve as xml,W as xmlLanguage}; diff --git a/assets/index-Czk6-ejp.js b/assets/index-qkal7za7.js similarity index 94% rename from assets/index-Czk6-ejp.js rename to assets/index-qkal7za7.js index 095b9d5..ef3a576 100644 --- a/assets/index-Czk6-ejp.js +++ b/assets/index-qkal7za7.js @@ -1 +1 @@ -import{s as p,t as e,L as u,a as l,b as m,l as r,q as b,r as n,v as S}from"./MarkdownEditor-BZjgjvzZ.js";import"./index-CBwDx5gl.js";import"./index.lazy-CnuJ_C2i.js";import"./isAddressEqual-D9iYaUN7.js";import"./secp256k1-B5jMENlr.js";const c=m.deserialize({version:14,states:"%pOVOWOOObQPOOOpOSO'#C_OOOO'#Cp'#CpQVOWOOQxQPOOO!TQQOOQ!YQPOOOOOO,58y,58yO!_OSO,58yOOOO-E6n-E6nO!dQQO'#CqQ{QPOOO!iQPOOQ{QPOOO!qQPOOOOOO1G.e1G.eOOQO,59],59]OOQO-E6o-E6oO!yOpO'#CiO#RO`O'#CiQOQPOOO#ZO#tO'#CmO#fO!bO'#CmOOQO,59T,59TO#qOpO,59TO#vO`O,59TOOOO'#Cr'#CrO#{O#tO,59XOOQO,59X,59XOOOO'#Cs'#CsO$WO!bO,59XOOQO1G.o1G.oOOOO-E6p-E6pOOQO1G.s1G.sOOOO-E6q-E6q",stateData:"$g~OjOS~OQROUROkQO~OWTOXUOZUO`VO~OSXOTWO~OXUO[]OlZO~OY^O~O[_O~OT`O~OYaO~OmcOodO~OmfOogO~O^iOnhO~O_jOphO~ObkOqkOrmO~OcnOsnOtmO~OnpO~OppO~ObkOqkOrrO~OcnOsnOtrO~OWX`~",goto:"!^hPPPiPPPPPPPPPmPPPpPPsy!Q!WTROSRe]Re_QSORYSS[T^Rb[QlfRqlQogRso",nodeNames:"⚠ Content Text Interpolation InterpolationContent }} Entity Attribute VueAttributeName : Identifier @ Is ScriptAttributeValue AttributeScript AttributeScript AttributeName AttributeValue Entity Entity",maxTerm:36,nodeProps:[["isolate",-3,3,13,17,""]],skippedNodes:[0],repeatNodeCount:4,tokenData:"'y~RdXY!aYZ!a]^!apq!ars!rwx!w}!O!|!O!P#t!Q![#y![!]$s!_!`%g!b!c%l!c!}#y#R#S#y#T#j#y#j#k%q#k#o#y%W;'S#y;'S;:j$m<%lO#y~!fSj~XY!aYZ!a]^!apq!a~!wOm~~!|Oo~!b#RX`!b}!O!|!Q![!|![!]!|!c!}!|#R#S!|#T#o!|%W;'S!|;'S;:j#n<%lO!|!b#qP;=`<%l!|~#yOl~%W$QXY#t`!b}!O!|!Q![#y![!]!|!c!}#y#R#S#y#T#o#y%W;'S#y;'S;:j$m<%lO#y%W$pP;=`<%l#y~$zXX~`!b}!O!|!Q![!|![!]!|!c!}!|#R#S!|#T#o!|%W;'S!|;'S;:j#n<%lO!|~%lO[~~%qOZ~%W%xXY#t`!b}!O&e!Q![#y![!]!|!c!}#y#R#S#y#T#o#y%W;'S#y;'S;:j$m<%lO#y!b&jX`!b}!O!|!Q![!|![!]!|!c!}'V#R#S!|#T#o'V%W;'S!|;'S;:j#n<%lO!|!b'^XW!b`!b}!O!|!Q![!|![!]!|!c!}'V#R#S!|#T#o'V%W;'S!|;'S;:j#n<%lO!|",tokenizers:[6,7,new r("b~RP#q#rU~XP#q#r[~aOT~~",17,4),new r("!k~RQvwX#o#p!_~^TU~Opmq!]m!^;'Sm;'S;=`!X<%lOm~pUOpmq!]m!]!^!S!^;'Sm;'S;=`!X<%lOm~!XOU~~![P;=`<%lm~!bP#o#p!e~!jOk~~",72,2),new r("[~RPwxU~ZOp~~",11,15),new r("[~RPrsU~ZOn~~",11,14),new r("!e~RQvwXwx!_~^Tc~Opmq!]m!^;'Sm;'S;=`!X<%lOm~pUOpmq!]m!]!^!S!^;'Sm;'S;=`!X<%lOm~!XOc~~![P;=`<%lm~!dOt~~",66,35),new r("!e~RQrsXvw^~^Or~~cTb~Oprq!]r!^;'Sr;'S;=`!^<%lOr~uUOprq!]r!]!^!X!^;'Sr;'S;=`!^<%lOr~!^Ob~~!aP;=`<%lr~",66,33)],topRules:{Content:[0,1],Attribute:[1,7]},tokenPrec:157}),P=S.parser.configure({top:"SingleExpression"}),o=c.configure({props:[p({Text:e.content,Is:e.definitionOperator,AttributeName:e.attributeName,VueAttributeName:e.keyword,Identifier:e.variableName,"AttributeValue ScriptAttributeValue":e.attributeValue,Entity:e.character,"{{ }}":e.brace,"@ :":e.punctuation})]}),s={parser:P},Q=o.configure({wrap:n((O,t)=>O.name=="InterpolationContent"?s:null)}),g=o.configure({wrap:n((O,t)=>O.name=="AttributeScript"?s:null),top:"Attribute"}),y={parser:Q},R={parser:g},a=b();function i(O){return O.configure({dialect:"selfClosing",wrap:n(X)},"vue")}const T=i(a.language);function X(O,t){switch(O.name){case"Attribute":return/^(@|:|v-)/.test(t.read(O.from,O.from+2))?R:null;case"Text":return y}return null}function k(O={}){let t=a;if(O.base){if(O.base.language.name!="html"||!(O.base.language instanceof u))throw new RangeError("The base option must be the result of calling html(...)");t=O.base}return new l(t.language==a.language?T:i(t.language),[t.support,t.language.data.of({closeBrackets:{brackets:["{",'"']}})])}export{k as vue,T as vueLanguage}; +import{s as p,t as e,L as u,a as l,b as m,l as r,q as b,r as n,v as S}from"./MarkdownEditor-BjREHNgK.js";import"./index-4Hagg-7l.js";import"./index.lazy-BRB6PNxD.js";import"./isAddressEqual-DlPIwSPc.js";import"./secp256k1-CibHJEZu.js";const c=m.deserialize({version:14,states:"%pOVOWOOObQPOOOpOSO'#C_OOOO'#Cp'#CpQVOWOOQxQPOOO!TQQOOQ!YQPOOOOOO,58y,58yO!_OSO,58yOOOO-E6n-E6nO!dQQO'#CqQ{QPOOO!iQPOOQ{QPOOO!qQPOOOOOO1G.e1G.eOOQO,59],59]OOQO-E6o-E6oO!yOpO'#CiO#RO`O'#CiQOQPOOO#ZO#tO'#CmO#fO!bO'#CmOOQO,59T,59TO#qOpO,59TO#vO`O,59TOOOO'#Cr'#CrO#{O#tO,59XOOQO,59X,59XOOOO'#Cs'#CsO$WO!bO,59XOOQO1G.o1G.oOOOO-E6p-E6pOOQO1G.s1G.sOOOO-E6q-E6q",stateData:"$g~OjOS~OQROUROkQO~OWTOXUOZUO`VO~OSXOTWO~OXUO[]OlZO~OY^O~O[_O~OT`O~OYaO~OmcOodO~OmfOogO~O^iOnhO~O_jOphO~ObkOqkOrmO~OcnOsnOtmO~OnpO~OppO~ObkOqkOrrO~OcnOsnOtrO~OWX`~",goto:"!^hPPPiPPPPPPPPPmPPPpPPsy!Q!WTROSRe]Re_QSORYSS[T^Rb[QlfRqlQogRso",nodeNames:"⚠ Content Text Interpolation InterpolationContent }} Entity Attribute VueAttributeName : Identifier @ Is ScriptAttributeValue AttributeScript AttributeScript AttributeName AttributeValue Entity Entity",maxTerm:36,nodeProps:[["isolate",-3,3,13,17,""]],skippedNodes:[0],repeatNodeCount:4,tokenData:"'y~RdXY!aYZ!a]^!apq!ars!rwx!w}!O!|!O!P#t!Q![#y![!]$s!_!`%g!b!c%l!c!}#y#R#S#y#T#j#y#j#k%q#k#o#y%W;'S#y;'S;:j$m<%lO#y~!fSj~XY!aYZ!a]^!apq!a~!wOm~~!|Oo~!b#RX`!b}!O!|!Q![!|![!]!|!c!}!|#R#S!|#T#o!|%W;'S!|;'S;:j#n<%lO!|!b#qP;=`<%l!|~#yOl~%W$QXY#t`!b}!O!|!Q![#y![!]!|!c!}#y#R#S#y#T#o#y%W;'S#y;'S;:j$m<%lO#y%W$pP;=`<%l#y~$zXX~`!b}!O!|!Q![!|![!]!|!c!}!|#R#S!|#T#o!|%W;'S!|;'S;:j#n<%lO!|~%lO[~~%qOZ~%W%xXY#t`!b}!O&e!Q![#y![!]!|!c!}#y#R#S#y#T#o#y%W;'S#y;'S;:j$m<%lO#y!b&jX`!b}!O!|!Q![!|![!]!|!c!}'V#R#S!|#T#o'V%W;'S!|;'S;:j#n<%lO!|!b'^XW!b`!b}!O!|!Q![!|![!]!|!c!}'V#R#S!|#T#o'V%W;'S!|;'S;:j#n<%lO!|",tokenizers:[6,7,new r("b~RP#q#rU~XP#q#r[~aOT~~",17,4),new r("!k~RQvwX#o#p!_~^TU~Opmq!]m!^;'Sm;'S;=`!X<%lOm~pUOpmq!]m!]!^!S!^;'Sm;'S;=`!X<%lOm~!XOU~~![P;=`<%lm~!bP#o#p!e~!jOk~~",72,2),new r("[~RPwxU~ZOp~~",11,15),new r("[~RPrsU~ZOn~~",11,14),new r("!e~RQvwXwx!_~^Tc~Opmq!]m!^;'Sm;'S;=`!X<%lOm~pUOpmq!]m!]!^!S!^;'Sm;'S;=`!X<%lOm~!XOc~~![P;=`<%lm~!dOt~~",66,35),new r("!e~RQrsXvw^~^Or~~cTb~Oprq!]r!^;'Sr;'S;=`!^<%lOr~uUOprq!]r!]!^!X!^;'Sr;'S;=`!^<%lOr~!^Ob~~!aP;=`<%lr~",66,33)],topRules:{Content:[0,1],Attribute:[1,7]},tokenPrec:157}),P=S.parser.configure({top:"SingleExpression"}),o=c.configure({props:[p({Text:e.content,Is:e.definitionOperator,AttributeName:e.attributeName,VueAttributeName:e.keyword,Identifier:e.variableName,"AttributeValue ScriptAttributeValue":e.attributeValue,Entity:e.character,"{{ }}":e.brace,"@ :":e.punctuation})]}),s={parser:P},Q=o.configure({wrap:n((O,t)=>O.name=="InterpolationContent"?s:null)}),g=o.configure({wrap:n((O,t)=>O.name=="AttributeScript"?s:null),top:"Attribute"}),y={parser:Q},R={parser:g},a=b();function i(O){return O.configure({dialect:"selfClosing",wrap:n(X)},"vue")}const T=i(a.language);function X(O,t){switch(O.name){case"Attribute":return/^(@|:|v-)/.test(t.read(O.from,O.from+2))?R:null;case"Text":return y}return null}function k(O={}){let t=a;if(O.base){if(O.base.language.name!="html"||!(O.base.language instanceof u))throw new RangeError("The base option must be the result of calling html(...)");t=O.base}return new l(t.language==a.language?T:i(t.language),[t.support,t.language.data.of({closeBrackets:{brackets:["{",'"']}})])}export{k as vue,T as vueLanguage}; diff --git a/assets/index.lazy-CnuJ_C2i.js b/assets/index.lazy-BRB6PNxD.js similarity index 99% rename from assets/index.lazy-CnuJ_C2i.js rename to assets/index.lazy-BRB6PNxD.js index ad4da20..1ee874f 100644 --- a/assets/index.lazy-CnuJ_C2i.js +++ b/assets/index.lazy-BRB6PNxD.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownEditor-BZjgjvzZ.js","assets/index-CBwDx5gl.js","assets/index-Bx4zt1nf.css"])))=>i.map(i=>d[i]); -var dn=Object.defineProperty;var qt=o=>{throw TypeError(o)};var hn=(o,i,s)=>i in o?dn(o,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):o[i]=s;var U=(o,i,s)=>hn(o,typeof i!="symbol"?i+"":i,s),At=(o,i,s)=>i.has(o)||qt("Cannot "+s);var F=(o,i,s)=>(At(o,i,"read from private field"),s?s.call(o):i.get(o)),Y=(o,i,s)=>i.has(o)?qt("Cannot add the same private member more than once"):i instanceof WeakSet?i.add(o):i.set(o,s),Q=(o,i,s,a)=>(At(o,i,"write to private field"),a?a.call(o,s):i.set(o,s),s),te=(o,i,s)=>(At(o,i,"access private method"),s);import{e as reactExports,o as getChainContractAddress,q as getAction$1,u as toHex,v as packetToBytes,w as readContract,B as BaseError$2,x as getAbiItem,y as AbiEventNotFoundError,z as formatAbiItem,D as toEventSelector,F as keccak256,H as toBytes$4,I as encodeAbiParameters,K as numberToHex,N as encodeFunctionData,P as estimateGas,Q as parseAccount,T as getContractError,U as hexToNumber,V as AbiEventSignatureEmptyTopicsError,X as AbiEventSignatureNotFoundError,Z as DecodeLogTopicsMismatch,_ as decodeAbiParameters,$ as AbiDecodingDataSizeTooSmallError,a0 as PositionOutOfBoundsError,a1 as DecodeLogDataMismatch,a2 as size$4,a3 as formatLog,a4 as getBlockNumber,a5 as getTransaction,a6 as stringify$2,a7 as observe,a8 as poll$1,a9 as getBlock,aa as formatBlock,ab as InvalidInputRpcError,ac as concat$2,ad as isAddress,ae as InvalidAddressError,af as BytesSizeMismatchError,ag as stringToHex,ah as bytesToHex$1,ai as sliceHex,aj as concatHex,ak as hexToBytes$1,al as isHex,am as hexToBigInt,an as call,ao as encodeDeployData,ap as universalSignatureValidatorAbi,aq as universalSignatureValidatorByteCode,ar as getAddress,as as recoverAddress,at as CallExecutionError,au as getBalance,av as getChainId$1,aw as getEnsAddress,ax as getEnsAvatar,ay as getEnsName,az as getEnsText,aA as estimateFeesPerGas,aB as getGasPrice,aC as estimateMaxPriorityFeePerGas,aD as getTransactionCount,aE as getTransactionReceipt,aF as multicall,aG as prepareTransactionRequest,aH as sendRawTransaction,aI as simulateContract$1,aJ as waitForTransactionReceipt$1,aK as watchBlockNumber,aL as createClient,aM as custom,aN as hexToString,aO as writeContract$1,aP as WagmiContext,aQ as Subscribable,aR as resolveEnabled,aS as shallowEqualObjects,aT as resolveStaleTime,aU as noop$3,aV as isServer,aW as isValidTimeout,aX as timeUntilStale,aY as focusManager,aZ as fetchState,a_ as replaceData,a$ as notifyManager,b0 as hashKey,b1 as getDefaultState,b2 as useQueryClient,j as jsxRuntimeExports,b3 as clsx,f as commonjsGlobal,g as getDefaultExportFromCjs,b4 as nodeCrypto,b5 as sha256$7,b6 as React__default,b7 as _t,b8 as __vitePreload,l as createLazyFileRoute,m as playbooks,t as toSlug,b9 as mainnet,ba as http}from"./index-CBwDx5gl.js";import{i as isAddressEqual}from"./isAddressEqual-D9iYaUN7.js";import{e as equalBytes$1,s as secp256k1}from"./secp256k1-B5jMENlr.js";var encode_1$f=encode$S,MSB$h=128,REST$h=127,MSBALL$g=~REST$h,INT$g=Math.pow(2,31);function encode$S(o,i,s){i=i||[],s=s||0;for(var a=s;o>=INT$g;)i[s++]=o&255|MSB$h,o/=128;for(;o&MSBALL$g;)i[s++]=o&255|MSB$h,o>>>=7;return i[s]=o|0,encode$S.bytes=s-a+1,i}var decode$1h=read$i,MSB$1$f=128,REST$1$f=127;function read$i(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$i.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$f)<=MSB$1$f);return read$i.bytes=d-a,s}var N1$f=Math.pow(2,7),N2$f=Math.pow(2,14),N3$f=Math.pow(2,21),N4$f=Math.pow(2,28),N5$f=Math.pow(2,35),N6$f=Math.pow(2,42),N7$f=Math.pow(2,49),N8$f=Math.pow(2,56),N9$f=Math.pow(2,63),length$f=function(o){return o(_brrp_varint$e.encode(o,i,s),i),encodingLength$e=o=>_brrp_varint$e.encodingLength(o),create$w=(o,i)=>{const s=i.byteLength,a=encodingLength$e(o),c=a+encodingLength$e(s),d=new Uint8Array(c+s);return encodeTo$e(o,d,0),encodeTo$e(s,d,a),d.set(i,c),new Digest$e(o,s,i,d)};let Digest$e=class{constructor(i,s,a,c){this.code=i,this.size=s,this.digest=a,this.bytes=c}};const from$u=({name:o,code:i,encode:s})=>new Hasher$7(o,i,s);let Hasher$7=class{constructor(i,s,a){this.name=i,this.code=s,this.encode=a}digest(i){if(i instanceof Uint8Array){const s=this.encode(i);return s instanceof Uint8Array?create$w(this.code,s):s.then(a=>create$w(this.code,a))}else throw Error("Unknown type, must be binary type")}};const sha$5=o=>async i=>new Uint8Array(await crypto.subtle.digest(o,i)),sha256$6=from$u({name:"sha2-256",code:18,encode:sha$5("SHA-256")});var shim={exports:{}},useSyncExternalStoreShim_production_min={};/** +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MarkdownEditor-BjREHNgK.js","assets/index-4Hagg-7l.js","assets/index-C5iV8B94.css"])))=>i.map(i=>d[i]); +var dn=Object.defineProperty;var qt=o=>{throw TypeError(o)};var hn=(o,i,s)=>i in o?dn(o,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):o[i]=s;var U=(o,i,s)=>hn(o,typeof i!="symbol"?i+"":i,s),At=(o,i,s)=>i.has(o)||qt("Cannot "+s);var F=(o,i,s)=>(At(o,i,"read from private field"),s?s.call(o):i.get(o)),Y=(o,i,s)=>i.has(o)?qt("Cannot add the same private member more than once"):i instanceof WeakSet?i.add(o):i.set(o,s),Q=(o,i,s,a)=>(At(o,i,"write to private field"),a?a.call(o,s):i.set(o,s),s),te=(o,i,s)=>(At(o,i,"access private method"),s);import{e as reactExports,o as getChainContractAddress,q as getAction$1,u as toHex,v as packetToBytes,w as readContract,B as BaseError$2,x as getAbiItem,y as AbiEventNotFoundError,z as formatAbiItem,D as toEventSelector,F as keccak256,H as toBytes$4,I as encodeAbiParameters,K as numberToHex,N as encodeFunctionData,P as estimateGas,Q as parseAccount,T as getContractError,U as hexToNumber,V as AbiEventSignatureEmptyTopicsError,X as AbiEventSignatureNotFoundError,Z as DecodeLogTopicsMismatch,_ as decodeAbiParameters,$ as AbiDecodingDataSizeTooSmallError,a0 as PositionOutOfBoundsError,a1 as DecodeLogDataMismatch,a2 as size$4,a3 as formatLog,a4 as getBlockNumber,a5 as getTransaction,a6 as stringify$2,a7 as observe,a8 as poll$1,a9 as getBlock,aa as formatBlock,ab as InvalidInputRpcError,ac as concat$2,ad as isAddress,ae as InvalidAddressError,af as BytesSizeMismatchError,ag as stringToHex,ah as bytesToHex$1,ai as sliceHex,aj as concatHex,ak as hexToBytes$1,al as isHex,am as hexToBigInt,an as call,ao as encodeDeployData,ap as universalSignatureValidatorAbi,aq as universalSignatureValidatorByteCode,ar as getAddress,as as recoverAddress,at as CallExecutionError,au as getBalance,av as getChainId$1,aw as getEnsAddress,ax as getEnsAvatar,ay as getEnsName,az as getEnsText,aA as estimateFeesPerGas,aB as getGasPrice,aC as estimateMaxPriorityFeePerGas,aD as getTransactionCount,aE as getTransactionReceipt,aF as multicall,aG as prepareTransactionRequest,aH as sendRawTransaction,aI as simulateContract$1,aJ as waitForTransactionReceipt$1,aK as watchBlockNumber,aL as createClient,aM as custom,aN as hexToString,aO as writeContract$1,aP as WagmiContext,aQ as Subscribable,aR as resolveEnabled,aS as shallowEqualObjects,aT as resolveStaleTime,aU as noop$3,aV as isServer,aW as isValidTimeout,aX as timeUntilStale,aY as focusManager,aZ as fetchState,a_ as replaceData,a$ as notifyManager,b0 as hashKey,b1 as getDefaultState,b2 as useQueryClient,j as jsxRuntimeExports,b3 as clsx,f as commonjsGlobal,g as getDefaultExportFromCjs,b4 as nodeCrypto,b5 as sha256$7,b6 as React__default,b7 as _t,b8 as __vitePreload,l as createLazyFileRoute,m as playbooks,t as toSlug,b9 as mainnet,ba as http}from"./index-4Hagg-7l.js";import{i as isAddressEqual}from"./isAddressEqual-DlPIwSPc.js";import{e as equalBytes$1,s as secp256k1}from"./secp256k1-CibHJEZu.js";var encode_1$f=encode$S,MSB$h=128,REST$h=127,MSBALL$g=~REST$h,INT$g=Math.pow(2,31);function encode$S(o,i,s){i=i||[],s=s||0;for(var a=s;o>=INT$g;)i[s++]=o&255|MSB$h,o/=128;for(;o&MSBALL$g;)i[s++]=o&255|MSB$h,o>>>=7;return i[s]=o|0,encode$S.bytes=s-a+1,i}var decode$1h=read$i,MSB$1$f=128,REST$1$f=127;function read$i(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$i.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$f)<=MSB$1$f);return read$i.bytes=d-a,s}var N1$f=Math.pow(2,7),N2$f=Math.pow(2,14),N3$f=Math.pow(2,21),N4$f=Math.pow(2,28),N5$f=Math.pow(2,35),N6$f=Math.pow(2,42),N7$f=Math.pow(2,49),N8$f=Math.pow(2,56),N9$f=Math.pow(2,63),length$f=function(o){return o(_brrp_varint$e.encode(o,i,s),i),encodingLength$e=o=>_brrp_varint$e.encodingLength(o),create$w=(o,i)=>{const s=i.byteLength,a=encodingLength$e(o),c=a+encodingLength$e(s),d=new Uint8Array(c+s);return encodeTo$e(o,d,0),encodeTo$e(s,d,a),d.set(i,c),new Digest$e(o,s,i,d)};let Digest$e=class{constructor(i,s,a,c){this.code=i,this.size=s,this.digest=a,this.bytes=c}};const from$u=({name:o,code:i,encode:s})=>new Hasher$7(o,i,s);let Hasher$7=class{constructor(i,s,a){this.name=i,this.code=s,this.encode=a}digest(i){if(i instanceof Uint8Array){const s=this.encode(i);return s instanceof Uint8Array?create$w(this.code,s):s.then(a=>create$w(this.code,a))}else throw Error("Unknown type, must be binary type")}};const sha$5=o=>async i=>new Uint8Array(await crypto.subtle.digest(o,i)),sha256$6=from$u({name:"sha2-256",code:18,encode:sha$5("SHA-256")});var shim={exports:{}},useSyncExternalStoreShim_production_min={};/** * @license React * use-sync-external-store-shim.production.min.js * @@ -2141,7 +2141,7 @@ zebra zero zone zoo`.split(` -`),Provider$1=match$1({method:"web"}),add$8=capability({can:"provider/add",with:AccountDID$1,nb:struct({provider:Provider$1,consumer:SpaceDID$1}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.provider,i.nb.provider,"provider"))||and$2(equal(o.nb.consumer,i.nb.consumer,"consumer"))||ok({})}),Provider$2=Object.freeze(Object.defineProperty({__proto__:null,AccountDID:AccountDID$1,Provider:Provider$1,add:add$8},Symbol.toStringTag,{value:"Module"})),{Provider:ProviderDID$3,AccountDID}=Provider$2,add$7=async(o,{account:i,consumer:s,provider:a=o.connection.id.did(),proofs:c})=>{if(!ProviderDID$3.is(a))throw new Error(`Unable to determine provider from agent.connection.id did ${a}. expected a did:web:`);const{out:d}=await o.invokeAndExecute(add$8,{with:i,nb:{provider:a,consumer:s},proofs:c});return d},generate$1=async({name:o,agent:i})=>{const{signer:s}=await generate$2();return new OwnedSpace({signer:s,name:o,agent:i})},fromMnemonic=async(o,{name:i,agent:s})=>{const a=mnemonicToEntropy(o,wordlist),c=await derive(a);return new OwnedSpace({signer:c,name:i,agent:s})},toMnemonic=({signer:o})=>{const i=o.secret;return entropyToMnemonic(i,wordlist)},createRecovery=(o,i)=>createAuthorization(o,{agent:o.signer.withDID(i),access:accountAccess$1,expiration:1/0}),SESSION_LIFETIME=60*60*24*365,createAuthorization=async({signer:o,name:i},{agent:s,access:a=spaceAccess$1,expiration:c=now()+SESSION_LIFETIME})=>await delegate$3({issuer:o,audience:s,capabilities:toCapabilities({[o.did()]:a}),...c?{expiration:c}:{},facts:[{space:{name:i}}]}),toCapabilities=o=>{const i=[];for(const[s,a]of Object.entries(o)){const c=Object.entries(a);for(const[d,f]of c)f&&i.push({can:d,with:s})}return i};class OwnedSpace{constructor(i){this.model=i}get signer(){return this.model.signer}get name(){return this.model.name}did(){return this.signer.did()}withName(i){return new OwnedSpace({signer:this.signer,name:i})}async save({agent:i=this.model.agent}={}){if(!i)return fail("Please provide an agent to save the space into");const s=await createAuthorization(this,{agent:i});return await i.importSpaceFromDelegation(s),await i.setCurrentSpace(this.did()),{ok:{}}}provision({proofs:i},{agent:s=this.model.agent}={}){return s?provision(this,{proofs:i,agent:s}):fail("Please provide an agent to save the space into")}async createRecovery(i){return createRecovery(this,i)}createAuthorization(i,s){return createAuthorization(this,{...s,agent:i})}toMnemonic(){return toMnemonic(this)}}const SpaceDID=match$1({method:"key"}),fromDelegation=o=>{var a;const i=SpaceDID.read(o.capabilities[0].with);if(i.error)throw Object.assign(new Error(`Invalid delegation, expected capabilities[0].with to be DID, ${i.error}`),{cause:i.error});const s=((a=o.facts[0])==null?void 0:a.space)??{};return new SharedSpace({id:i.ok,delegation:o,meta:s})},provision=async(o,{proofs:i,agent:s})=>{const[a]=i[0].capabilities,{ok:c,error:d}=AccountDID.read(a.with);return d?error$1(d):await add$7(s,{consumer:o.did(),account:c,proofs:i})};class SharedSpace{constructor(i){this.model=i}get delegation(){return this.model.delegation}get meta(){return this.model.meta}get name(){return this.meta.name??""}did(){return this.model.id}withName(i){return new SharedSpace({...this.model,meta:{...this.meta,name:i}})}}function isExpired(o){return o.expiration===void 0||o.expiration<=Math.floor(Date.now()/1e3)}function isTooEarly(o){return o.notBefore?o.notBefore>Math.floor(Date.now()/1e3):!1}function canDelegateCapability(o,i){const s=allows(o);for(const[a,c]of Object.entries(s))if(matchResource(a,i.with)){const d=Object.keys(c);for(const f of d)if(canDelegateAbility(f,i.can))return!0}return!1}const matchResource=(o,i)=>i==="ucan:*"?!0:typeof i=="string"?o===i:i.test(o),_globalReference=globalThis||window||self,webcrypto=_globalReference.crypto,tagWith=(o,i)=>{const s=encodingLength$7(o),a=new Uint8Array(i.byteLength+s);return encodeTo$7(o,a,0),a.set(i,s),a},untagWith=(o,i,s=0)=>{const a=s!==0?i.subarray(s):i,[c,d]=decode$C(a);if(c!==o)throw new Error(`Expected multiformat with 0x${o.toString(16)} tag instead got 0x${c.toString(16)}`);return new Uint8Array(a.buffer,a.byteOffset+d)},TAG_SIZE$1=1,INT_TAG=2,BITSTRING_TAG=3,OCTET_STRING_TAG=4,SEQUENCE_TAG=48,UNUSED_BIT_PAD=0,encodeDERLength=o=>{if(o<=127)return new Uint8Array([o]);const i=[];for(;o!==0;)i.push(o&255),o=o>>>8;return i.reverse(),new Uint8Array([128|i.length&255,...i])},readDERLength=(o,i=0)=>{if(!(o[i]&128))return{number:o[i],consumed:1};const s=o[i]&127;if(o.length{const a=into(o,i,s);return a.position+a.length},into=(o,i,s)=>{const a=o[s];if(a!==i)throw new Error(`ASN parsing error: Expected tag 0x${i.toString(16)} at position ${s}, but got 0x${a.toString(16)}.`);const c=readDERLength(o,s+TAG_SIZE$1);return{position:s+TAG_SIZE$1+c.consumed,length:c.number}},encodeBitString=o=>{const i=encodeDERLength(o.byteLength+1),s=new Uint8Array(TAG_SIZE$1+i.byteLength+1+o.byteLength);let a=0;return s[a]=BITSTRING_TAG,a+=TAG_SIZE$1,s.set(i,a),a+=i.byteLength,s[a]=UNUSED_BIT_PAD,a+=1,s.set(o,a),s},encodeOctetString=o=>{const i=encodeDERLength(o.byteLength),s=new Uint8Array(TAG_SIZE$1+i.byteLength+o.byteLength);let a=0;return s[a]=OCTET_STRING_TAG,a+=TAG_SIZE$1,s.set(i,a),a+=i.byteLength,s.set(o,a),s},encodeSequence=o=>{let i=0;for(const d of o)i+=d.byteLength;const s=encodeDERLength(i),a=new Uint8Array(TAG_SIZE$1+s.byteLength+i);let c=0;a[c]=SEQUENCE_TAG,c+=TAG_SIZE$1,a.set(s,c),c+=s.byteLength;for(const d of o)a.set(d,c),c+=d.byteLength;return a},readSequence=(o,i=0)=>{const{position:s,length:a}=into(o,SEQUENCE_TAG,i);return new Uint8Array(o.buffer,o.byteOffset+s,a)},encodeInt=o=>{const i=o.byteLength===0||o[0]&128?1:0,s=encodeDERLength(o.byteLength+i),a=new Uint8Array(TAG_SIZE$1+s.byteLength+o.byteLength+i);let c=0;return a[c]=INT_TAG,c+=TAG_SIZE$1,a.set(s,c),c+=s.byteLength,i>0&&(a[c]=UNUSED_BIT_PAD,c+=i),a.set(o,c),a},enterSequence=(o,i=0)=>into(o,SEQUENCE_TAG,i).position,skipSequence=(o,i=0)=>skip(o,SEQUENCE_TAG,i),skipInt=(o,i=0)=>skip(o,INT_TAG,i),readBitString=(o,i=0)=>{const{position:s,length:a}=into(o,BITSTRING_TAG,i),c=o[s];if(c!==UNUSED_BIT_PAD)throw new Error(`Can not read bitstring, expected length to be multiple of 8, but got ${c} unused bits in last byte.`);return new Uint8Array(o.buffer,o.byteOffset+s+1,a-1)},readInt$1=(o,i=0)=>{const{position:s,length:a}=into(o,INT_TAG,i);let c=0;for(;o[s+c]===0;)c++;return new Uint8Array(o.buffer,o.byteOffset+s+c,a-c)},readOctetString=(o,i=0)=>{const{position:s,length:a}=into(o,OCTET_STRING_TAG,i);return new Uint8Array(o.buffer,o.byteOffset+s,a)},readSequenceWith=(o,i,s=0)=>{const a=[],c=readSequence(i,s);let d=0;for(const f of o){const g=f(c,d);a.push(g),d=g.byteOffset+g.byteLength-c.byteOffset}return a},SPKI_PARAMS_ENCODED=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),encode$n=o=>encodeSequence([SPKI_PARAMS_ENCODED,encodeBitString(o)]),decode$y=o=>{const i=enterSequence(o,0),s=skipSequence(o,i);return readBitString(o,s)},PKSC8_HEADER=new Uint8Array([2,1,0,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),decode$x=o=>{let i=0;return i=enterSequence(o,i),i=skipInt(o,i),i=skipSequence(o,i),readOctetString(o,i)},encode$m=o=>encodeSequence([PKSC8_HEADER,encodeOctetString(o)]),encode$l=({n:o,e:i})=>encodeSequence([encodeInt(o),encodeInt(i)]),decode$w=(o,i=0)=>{const[s,a,c,d,f,g,y,b,$]=readSequenceWith([readInt$1,readInt$1,readInt$1,readInt$1,readInt$1,readInt$1,readInt$1,readInt$1,readInt$1],o,i);return{v:s,n:a,e:c,d,p:f,q:g,dp:y,dq:b,qi:$}},name$6="RSA",code$8=4869,verifierCode=4613,signatureCode=RS256,signatureAlgorithm="RS256",ALG="RSASSA-PKCS1-v1_5",HASH_ALG="SHA-256",KEY_SIZE=2048,SALT_LENGTH=128,IMPORT_PARAMS={name:ALG,hash:{name:HASH_ALG}},generate=async({size:o=KEY_SIZE,extractable:i=!1}={})=>{const{publicKey:s,privateKey:a}=await webcrypto.subtle.generateKey({name:ALG,modulusLength:o,publicExponent:new Uint8Array([1,0,1]),hash:{name:HASH_ALG}},i,["sign","verify"]),c=await webcrypto.subtle.exportKey("spki",s),d=tagWith(verifierCode,decode$y(new Uint8Array(c))),f=new RSAVerifier({bytes:d,publicKey:s});if(i){const g=await webcrypto.subtle.exportKey("pkcs8",a),y=tagWith(code$8,decode$x(new Uint8Array(g)));return new ExtractableRSASigner({privateKey:a,bytes:y,verifier:f})}else return new UnextractableRSASigner({privateKey:a,verifier:f})},from$g=({id:o,keys:i})=>{if(o.startsWith("did:key:")){const s=o,a=i[s];return a instanceof Uint8Array?decode$v(a):new UnextractableRSASigner({privateKey:a,verifier:RSAVerifier.parse(s)})}else throw new TypeError(`RSA can not import from ${o} archive, try generic Signer instead`)},or$9=o=>or$b({from:from$g},o),decode$v=o=>{const i=decode$w(untagWith(code$8,o)),s=tagWith(verifierCode,encode$l(i));return new ExtractableRSASigner({bytes:o,privateKey:webcrypto.subtle.importKey("pkcs8",encode$m(untagWith(code$8,o)),IMPORT_PARAMS,!0,["sign"]),verifier:RSAVerifier.decode(s)})};class RSAVerifier{constructor({publicKey:i,bytes:s}){this.publicKey=i,this.bytes=s}withDID(i){return withDID$1(this,i)}toDIDKey(){return this.did()}static decode(i){return new this({bytes:i,publicKey:webcrypto.subtle.importKey("spki",encode$n(untagWith(verifierCode,i)),IMPORT_PARAMS,!0,["verify"])})}static parse(i){return RSAVerifier.decode(parse$2(i))}static or(i){return or$c(this,i)}get code(){return verifierCode}get signatureCode(){return signatureCode}get signatureAlgorithm(){return signatureAlgorithm}did(){return`did:key:${base58btc$5.encode(this.bytes)}`}async verify(i,s){return s.code!==signatureCode?!1:webcrypto.subtle.verify({name:ALG,hash:{name:HASH_ALG}},await this.publicKey,s.raw,i)}}class RSASigner{constructor({privateKey:i,verifier:s}){this.verifier=s,this.privateKey=i}get signer(){return this}get code(){return code$8}get signatureCode(){return signatureCode}get signatureAlgorithm(){return signatureAlgorithm}did(){return this.verifier.did()}toDIDKey(){return this.verifier.toDIDKey()}verify(i,s){return this.verifier.verify(i,s)}async sign(i){const s=await webcrypto.subtle.sign({name:ALG,saltLength:SALT_LENGTH},await this.privateKey,i);return create$r(signatureCode,new Uint8Array(s))}}class ExtractableRSASigner extends RSASigner{constructor(i){super(i),this.bytes=i.bytes}withDID(i){return withDID(this,i)}toArchive(){const i=this.did();return{id:i,keys:{[i]:this.bytes}}}}class UnextractableRSASigner extends RSASigner{constructor(i){super(i),this.privateKey=i.privateKey}withDID(i){return withDID(this,i)}toArchive(){const i=this.did();return{id:i,keys:{[i]:this.privateKey}}}}const RSA=Object.freeze(Object.defineProperty({__proto__:null,Verifier:RSAVerifier,code:code$8,decode:decode$v,from:from$g,generate,name:name$6,or:or$9,signatureAlgorithm,signatureCode},Symbol.toStringTag,{value:"Module"})),Signer=or$a(RSA),ProviderDID$2=match$1({method:"web"}),has$1=capability({can:"consumer/has",with:ProviderDID$2,nb:struct({consumer:SpaceDID$1}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.consumer,i.nb.consumer,"consumer"))||ok({})}),get$f=capability({can:"consumer/get",with:ProviderDID$2,nb:struct({consumer:SpaceDID$1}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.consumer,i.nb.consumer,"consumer"))||ok({})}),ProviderDID$1=match$1({method:"web"}),get$e=capability({can:"customer/get",with:ProviderDID$1,nb:struct({customer:AccountDID$1}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.customer,i.nb.customer,"customer"))||ok({})});capability({can:"console/*",with:match$1(),derives:equalWith});capability({can:"console/log",with:match$1(),nb:struct({value:unknown()}),derives:equalWith});capability({can:"console/error",with:match$1(),nb:struct({error:unknown()}),derives:equalWith});const Provider=DID,add$6=capability({can:"rate-limit/add",with:Provider,nb:struct({subject:string(),rate:number()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.subject,i.nb.subject,"subject"))||and$2(equal(o.nb.rate,i.nb.rate,"rate"))||ok({})}),remove$6=capability({can:"rate-limit/remove",with:Provider,nb:struct({id:string()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.id,i.nb.id,"id"))||ok({})}),list$7=capability({can:"rate-limit/list",with:Provider,nb:struct({subject:string()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.subject,i.nb.subject,"subject"))||ok({})}),admin=capability({can:"admin/*",with:ProviderDID$4,derives:equalWith}),upload$1={inspect:capability({can:"admin/upload/inspect",with:ProviderDID$4,nb:struct({root:Link}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.root,i.nb.root,"root"))||ok({})})},store={inspect:capability({can:"admin/store/inspect",with:ProviderDID$4,nb:struct({link:Link}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.link,i.nb.link,"link"))||ok({})})},ProviderDID=match$1({method:"web"}),get$d=capability({can:"subscription/get",with:ProviderDID,nb:struct({subscription:string()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.subscription,i.nb.subscription,"consumer"))||ok({})}),list$6=capability({can:"subscription/list",with:AccountDID$1,derives:equalWith}),FR32_SHA2_256_TRUNC254_PADDED_BINARY_TREE=4113,RAW_CODE=85,PieceLink=match$2({code:RAW_CODE,version:1,multihash:{code:FR32_SHA2_256_TRUNC254_PADDED_BINARY_TREE}}),filecoinOffer$1=capability({can:"filecoin/offer",with:match$1(),nb:struct({content:match$2(),piece:PieceLink}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.content,i.nb.content,"nb.content"))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||ok({})}),filecoinSubmit=capability({can:"filecoin/submit",with:match$1(),nb:struct({content:match$2(),piece:PieceLink}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.content,i.nb.content,"nb.content"))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||ok({})}),filecoinAccept=capability({can:"filecoin/accept",with:match$1(),nb:struct({content:match$2(),piece:PieceLink}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.content,i.nb.content,"nb.content"))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||ok({})}),filecoinInfo$1=capability({can:"filecoin/info",with:match$1(),nb:struct({piece:PieceLink}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||ok({})}),pieceOffer=capability({can:"piece/offer",with:match$1(),nb:struct({piece:PieceLink,group:match()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||and$2(equal(o.nb.group,i.nb.group,"nb.group"))||ok({})}),pieceAccept=capability({can:"piece/accept",with:match$1(),nb:struct({piece:PieceLink,group:match()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||and$2(equal(o.nb.group,i.nb.group,"nb.group"))||ok({})}),aggregateOffer=capability({can:"aggregate/offer",with:match$1(),nb:struct({aggregate:PieceLink,pieces:match$2({version:1})}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.aggregate,i.nb.aggregate,"nb.aggregate"))||and$2(checkLink(o.nb.pieces,i.nb.pieces,"nb.pieces"))||ok({})}),aggregateAccept=capability({can:"aggregate/accept",with:match$1(),nb:struct({aggregate:PieceLink,pieces:match$2()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.aggregate,i.nb.aggregate,"nb.aggregate"))||and$2(checkLink(o.nb.pieces,i.nb.pieces,"nb.pieces"))||ok({})}),dealInfo=capability({can:"deal/info",with:match$1(),nb:struct({piece:PieceLink}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||ok({})}),index=capability({can:"space/index/*",with:SpaceDID$1,derives:equalWith}),add$5=capability({can:"space/index/add",with:SpaceDID$1,nb:struct({index:match$2({code:code$c,version:1})}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.index,i.nb.index,"index"))||ok({})}),get$c=capability({can:"plan/get",with:AccountDID$1,derives:(o,i)=>and$2(equalWith(o,i))||ok({})}),set$5=capability({can:"plan/set",with:AccountDID$1,nb:struct({product:DID}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.product,i.nb.product,"product"))||ok({})}),createAdminSession$1=capability({can:"plan/create-admin-session",with:AccountDID$1,nb:struct({returnURL:string()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.returnURL,i.nb.returnURL,"returnURL"))||ok({})}),usage=capability({can:"usage/*",with:SpaceDID$1,derives:equalWith}),report$1=capability({can:"usage/report",with:SpaceDID$1,nb:struct({period:struct({from:integer().greaterThan(-1),to:integer().greaterThan(-1)})}),derives:(o,i)=>{var s,a,c,d;return and$2(equalWith(o,i))||and$2(equal((s=o.nb.period)==null?void 0:s.from,(a=i.nb.period)==null?void 0:a.from,"period.from"))||and$2(equal((c=o.nb.period)==null?void 0:c.to,(d=i.nb.period)==null?void 0:d.to,"period.to"))||ok({})}}),blob$1=capability({can:"space/blob/*",with:SpaceDID$1,derives:equalWith}),content=struct({digest:bytes$1(),size:integer()}),add$4=capability({can:"space/blob/add",with:SpaceDID$1,nb:struct({blob:content}),derives:equalBlob}),remove$5=capability({can:"space/blob/remove",with:SpaceDID$1,nb:struct({digest:bytes$1()}),derives:(o,i)=>o.with!==i.with?fail(`Expected 'with: "${i.with}"' instead got '${o.with}'`):i.nb.digest&&!equals$d(i.nb.digest,o.nb.digest)?fail(`Link ${o.nb.digest?`${o.nb.digest}`:""} violates imposed ${i.nb.digest} constraint.`):ok({})}),list$5=capability({can:"space/blob/list",with:SpaceDID$1,nb:struct({cursor:string().optional(),size:integer().optional()}),derives:(o,i)=>o.with!==i.with?fail(`Expected 'with: "${i.with}"' instead got '${o.with}'`):ok({})}),get$b=capability({can:"space/blob/get/0/1",with:SpaceDID$1,nb:struct({digest:bytes$1()}),derives:(o,i)=>o.with!==i.with?fail(`Expected 'with: "${i.with}"' instead got '${o.with}'`):i.nb.digest&&!equals$d(i.nb.digest,o.nb.digest)?fail(`Link ${o.nb.digest?`${o.nb.digest}`:""} violates imposed ${i.nb.digest} constraint.`):ok({})}),blob=capability({can:"web3.storage/blob/*",with:SpaceDID$1,derives:equalWith}),allocate=capability({can:"web3.storage/blob/allocate",with:match$1(),nb:struct({blob:content,cause:Link,space:SpaceDID$1}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equalBlob(o,i))||and$2(checkLink(o.nb.cause,i.nb.cause,"cause"))||and$2(equal(o.nb.space,i.nb.space,"space"))||ok({})}),accept=capability({can:"web3.storage/blob/accept",with:match$1(),nb:struct({blob:content,ttl:integer().optional(),space:SpaceDID$1,_put:Await}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equalBlob(o,i))||and$2(equal(o.nb.ttl,i.nb.ttl,"ttl"))||and$2(equal(o.nb.space,i.nb.space,"space"))||ok({})}),put=capability({can:"http/put",with:SpaceDID$1,nb:struct({body:content,url:string().or(Await),headers:dictionary({value:string()}).or(Await)}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equalBody(o,i))||and$2(equal(o.nb.url,i.nb,"url"))||and$2(equal(o.nb.headers,i.nb,"headers"))||ok({})}),abilitiesAsStrings=[top.can,add$8.can,space.can,info.can,upload$2.can,add$9.can,get$g.can,remove$7.can,list$8.can,store$1.can,add$a.can,get$h.can,remove$8.can,list$9.can,access$1.can,authorize.can,attest.can,conclude$1.can,get$e.can,has$1.can,get$f.can,get$d.can,list$6.can,add$6.can,remove$6.can,list$7.can,filecoinOffer$1.can,filecoinSubmit.can,filecoinAccept.can,filecoinInfo$1.can,pieceOffer.can,pieceAccept.can,aggregateOffer.can,aggregateAccept.can,dealInfo.can,admin.can,upload$1.inspect.can,store.inspect.can,get$c.can,set$5.can,createAdminSession$1.can,usage.can,report$1.can,blob$1.can,add$4.can,remove$5.can,list$5.can,blob.can,allocate.can,accept.can,put.can,index.can,add$5.can];function uint8ArrayToArrayBuffer(o){return o.byteOffset===0&&o.byteLength===o.buffer.byteLength?o.buffer:o.buffer.slice(o.byteOffset,o.byteLength+o.byteOffset)}var Fe;const St=class St{constructor(i,s={}){Y(this,Fe);this.meta=i.meta,this.principal=i.principal,this.spaces=i.spaces,this.delegations=i.delegations,this.currentSpace=i.currentSpace,Q(this,Fe,a=>s.store?s.store.save(a):void 0)}static async create(i={},s={}){const a=new St({meta:{name:"agent",type:"device",...i.meta},principal:i.principal??await generate$2(),spaces:i.spaces??new Map,delegations:i.delegations??new Map,currentSpace:i.currentSpace},s);return s.store&&await s.store.save(a.export()),a}static fromExport(i,s){const a=new Map;for(const[c,d]of i.delegations)a.set(c,{delegation:importDAG(d.delegation.map(f=>({cid:CID$5.parse(f.cid).toV1(),bytes:f.bytes instanceof Uint8Array?f.bytes:new Uint8Array(f.bytes)}))),meta:d.meta});return new St({meta:i.meta,principal:Signer.from(i.principal),currentSpace:i.currentSpace,spaces:i.spaces,delegations:a},s)}export(){const i={meta:this.meta,principal:this.principal.toArchive(),currentSpace:this.currentSpace,spaces:this.spaces,delegations:new Map};for(const[s,a]of this.delegations)i.delegations.set(s,{meta:a.meta,delegation:[...a.delegation.export()].map(c=>({cid:c.cid.toString(),bytes:uint8ArrayToArrayBuffer(c.bytes)}))});return i}async addSpace(i,s,a){this.spaces.set(i,s),await(a?this.addDelegation(a):F(this,Fe).call(this,this.export()))}async setCurrentSpace(i){this.currentSpace=i,await F(this,Fe).call(this,this.export())}async addDelegation(i,s){this.delegations.set(i.cid.toString(),{delegation:i,meta:s??{}}),await F(this,Fe).call(this,this.export())}async removeDelegation(i){this.delegations.delete(i.toString()),await F(this,Fe).call(this,this.export())}};Fe=new WeakMap;let AgentData=St;const isSessionCapability=o=>o.can===attest.can,isSessionProof=o=>o.capabilities.some(i=>isSessionCapability(i));function getSessionProofs(o){const i={};for(const{delegation:s}of o.delegations.values())if(isSessionProof(s)){const a=s.capabilities[0];if(a&&!isExpired(s)){const c=a.nb.proof;if(c){const d=c.toString(),f=s.issuer.did();i[d]=i[d]??{},i[d][f]=i[d][f]??[],i[d][f].push(s)}}}return i}match$1({method:"web"});const HOST="https://up.web3.storage",PRINCIPAL=parse$2("did:web:web3.storage"),agentToData=new WeakMap;function connection$2(o={}){return connect({id:o.principal??PRINCIPAL,codec:outbound,channel:o.channel??open$2({url:o.url??new URL(HOST),method:"POST",fetch:o.fetch??globalThis.fetch.bind(globalThis)})})}var se,gt,Mt;const Tt=class Tt{constructor(i,s={}){Y(this,gt);Y(this,se);var c;const a=(c=s.connection)==null?void 0:c.channel;this.url=s.url??(a==null?void 0:a.url)??new URL(HOST),this.connection=s.connection??connection$2({principal:s.servicePrincipal,url:this.url}),Q(this,se,i),agentToData.set(this,F(this,se))}static async create(i,s={}){const a=await AgentData.create(i,s);return new Tt(a,s)}static from(i,s={}){const a=AgentData.fromExport(i,s);return new Tt(a,s)}get issuer(){return F(this,se).principal}get meta(){return F(this,se).meta}get spaces(){return F(this,se).spaces}did(){return F(this,se).principal.did()}async addProof(i){return await this.addProofs([i])}async addProofs(i){for(const s of i)await F(this,se).addDelegation(s,{audience:this.meta});return await this.removeExpiredDelegations(),{}}async removeExpiredDelegations(){for(const[,i]of F(this,se).delegations)isExpired(i.delegation)&&await F(this,se).removeDelegation(i.delegation.cid)}async revoke(i,s={}){const a=s.proofs??[],c=[...this.delegations(),...a].find(f=>f.cid.equals(i));return c?(await this.invokeAndExecute(revoke,{with:this.issuer.did(),nb:{ucan:c.cid},proofs:[c,...a]})).out:{error:new Error(`could not find delegation ${i.toString()} - please include the delegation in options.proofs`)}}proofs(i,s){const a=[];for(const{delegation:d}of te(this,gt,Mt).call(this,i))d.audience.did()===this.issuer.did()&&a.push(d);const c=getSessionProofs(F(this,se));for(const d of a){const f=c[d.asCID.toString()]??{},g=s!=null&&s.sessionProofIssuer?f[s.sessionProofIssuer]??[]:Object.values(f).flat();g.length&&a.push(...g)}return a}delegations(i){const s=[];for(const{delegation:a}of this.delegationsWithMeta(i))s.push(a);return s}delegationsWithMeta(i){const s=[];for(const a of te(this,gt,Mt).call(this,i)){const{delegation:c}=a;!c.capabilities.some(f=>f.can===attest.can)&&c.audience.did()!==this.issuer.did()&&s.push(a)}return s}async createSpace(i){return await generate$1({name:i,agent:this})}async recoverSpace(i,{name:s}){return await fromMnemonic(i,{name:s,agent:this})}async importSpaceFromDelegation(i,{name:s=""}={}){const a=s===""?fromDelegation(i):fromDelegation(i).withName(s);return F(this,se).spaces.set(a.did(),{...a.meta,name:a.name}),await this.addProof(a.delegation),this.currentSpace()||await this.setCurrentSpace(a.did()),a}async setCurrentSpace(i){if(!F(this,se).spaces.has(i))throw new Error(`Agent has no proofs for ${i}.`);return await F(this,se).setCurrentSpace(i),i}currentSpace(){return F(this,se).currentSpace}currentSpaceWithMeta(){if(!F(this,se).currentSpace)return;const i=this.proofs([{can:"space/info",with:F(this,se).currentSpace}]),s=new Set;for(const a of i)for(const c of a.capabilities)s.add(c.can);return{did:F(this,se).currentSpace,proofs:i,capabilities:[...s],meta:F(this,se).spaces.get(F(this,se).currentSpace)}}async delegate(i){const s=this.currentSpaceWithMeta();if(!s)throw new Error("no space selected.");const a=i.abilities.map(d=>({with:s.did,can:d}));for(const d of a)if(!this.proofs([d]).length)throw new Error(`cannot delegate capability ${d.can} with ${d.with}`);const c=await delegate$3({issuer:this.issuer,capabilities:a,proofs:this.proofs(a),facts:[{space:s.meta??{}}],...i});return await F(this,se).addDelegation(c,{audience:i.audienceMeta}),await this.removeExpiredDelegations(),c}async invokeAndExecute(i,s){return(await this.invoke(i,s)).execute(this.connection)}execute(...i){return this.connection.execute(...i)}async invoke(i,s){const a=s.audience||this.connection.id,c=s.with||this.currentSpace();if(!c)throw new Error("No space or resource selected, you need pass a resource.");const d=[...s.proofs||[],...this.proofs([{with:c,can:i.can}],{sessionProofIssuer:a.did()})];if(d.length===0&&s.with!==this.did())throw new Error(`no proofs available for resource ${c} and ability ${i.can}`);return invoke({...s,audience:a,capability:i.create({with:c,nb:s.nb}),issuer:this.issuer,proofs:[...d],nonce:s.nonce})}async getSpaceInfo(i,s){const a=i||this.currentSpace();if(!a)throw new Error("No space selected, you need pass a resource.");const c=await this.invokeAndExecute(info,{...s,with:a});if(c.out.error)throw c.out.error;return c.out.ok}};se=new WeakMap,gt=new WeakSet,Mt=function(i){const s=new Set(i),a=[];for(const[,c]of F(this,se).delegations)if(!isExpired(c.delegation)&&!isTooEarly(c.delegation))if(Array.isArray(i)&&i.length>0)for(const d of s)canDelegateCapability(c.delegation,d)&&a.push(c);else a.push(c);return a};let Agent=Tt;async function addSpacesFromDelegations(o,i){const s=agentToData.get(o);if(!s)throw Object.assign(new Error("cannot determine AgentData for Agent"),{agent:o});const a=new Map,c=i.filter(f=>f.audience.did()===o.did()),d=c.filter(f=>f.capabilities[0].can==="*"&&f.capabilities[0].with==="ucan:*");for(const f of d)for(const g of f.proofs){if(!isDelegation(g)||!g.capabilities[0].with.startsWith("did:key"))continue;const y=fromDelegation(g);a.set(y.did(),y.meta)}for(const f of c){const g=allows(f);for(const[y,b]of Object.entries(g))y.startsWith("did:key")&&Object.keys(b).length>0&&(a.has(y)||a.set(y,{}))}for(const[f,g]of a)await s.addSpace(f,g)}const importAuthorization=async(o,{proofs:i})=>{try{return await o.addProofs(i),await addSpacesFromDelegations(o,i),{ok:{}}}catch(s){return{error:s}}};function pDefer(){const o={};return o.promise=new Promise((i,s)=>{o.resolve=i,o.reject=s}),o}const STORE_NAME="AccessStore",DATA_ID=1;var yt,mt,je,Be,bt,rt,kt;class IndexedDBDriver{constructor(i,s={}){Y(this,rt);Y(this,yt);Y(this,mt);Y(this,je);Y(this,Be);Y(this,bt);Q(this,yt,i),Q(this,mt,s.dbVersion),Q(this,je,s.dbStoreName??STORE_NAME),Q(this,bt,s.autoOpen??!0)}async open(){if(F(this,Be))return;const{resolve:s,reject:a,promise:c}=pDefer(),d=indexedDB.open(F(this,yt),F(this,mt));return d.addEventListener("upgradeneeded",()=>{d.result.createObjectStore(F(this,je),{keyPath:"id"})}),d.addEventListener("success",()=>{Q(this,Be,d.result),s()}),d.addEventListener("error",()=>a(d.error)),c}async close(){const i=F(this,Be);if(!i)throw new Error("Store is not open");i.close(),Q(this,Be,void 0)}async save(i){const s=await te(this,rt,kt).call(this);return await withObjectStore(s,"readwrite",F(this,je),async c=>{const{resolve:d,reject:f,promise:g}=pDefer(),y=c.put({id:DATA_ID,...i});return y.addEventListener("success",()=>d()),y.addEventListener("error",()=>f(new Error("failed to query DB",{cause:y.error}))),g})()}async load(){const i=await te(this,rt,kt).call(this);return await withObjectStore(i,"readonly",F(this,je),async a=>{const{resolve:c,reject:d,promise:f}=pDefer(),g=a.get(DATA_ID);return g.addEventListener("success",()=>c(g.result)),g.addEventListener("error",()=>d(new Error("failed to query DB",{cause:g.error}))),f})()}async reset(){const i=await te(this,rt,kt).call(this);await withObjectStore(i,"readwrite",F(this,je),a=>{const{resolve:c,reject:d,promise:f}=pDefer(),g=a.clear();return g.addEventListener("success",()=>{c()}),g.addEventListener("error",()=>d(new Error("failed to query DB",{cause:g.error}))),f})()}}yt=new WeakMap,mt=new WeakMap,je=new WeakMap,Be=new WeakMap,bt=new WeakMap,rt=new WeakSet,kt=async function(){if(!F(this,Be)){if(!F(this,bt))throw new Error("Store is not open");await this.open()}return F(this,Be)};function withObjectStore(o,i,s,a){return async()=>{const c=o.transaction(s,i),{resolve:d,reject:f,promise:g}=pDefer();let y;c.addEventListener("complete",()=>d(y)),c.addEventListener("abort",()=>f(c.error||new Error("transaction aborted"))),c.addEventListener("error",()=>f(new Error("transaction error",{cause:c.error})));try{y=await a(c.objectStore(s)),c.commit()}catch(b){f(b),c.abort()}return g}}class StoreIndexedDB extends IndexedDBDriver{}const BITS_PER_BYTE=8,FRS_PER_QUAD=4;BigInt(FRS_PER_QUAD);const IN_BITS_FR=254,OUT_BITS_FR=256,IN_BYTES_PER_QUAD=FRS_PER_QUAD*IN_BITS_FR/BITS_PER_BYTE,OUT_BYTES_PER_QUAD=FRS_PER_QUAD*OUT_BITS_FR/BITS_PER_BYTE,PADDED_BYTES_PER_QUAD=BigInt(IN_BYTES_PER_QUAD);BigInt(OUT_BYTES_PER_QUAD);const FR_RATIO=IN_BITS_FR/OUT_BITS_FR,NODE_SIZE=OUT_BYTES_PER_QUAD/FRS_PER_QUAD,EXPANDED_BYTES_PER_NODE=BigInt(NODE_SIZE),MIN_PAYLOAD_SIZE=2*NODE_SIZE+1,from$f=o=>{if(o instanceof Uint8Array){if(o.length>NODE_SIZE)return o.subarray(0,NODE_SIZE);if(o.length==NODE_SIZE)return o}const i=new Uint8Array(NODE_SIZE);return i.set([...o]),i},empty$4=()=>EMPTY$4,EMPTY$4=from$f(new Uint8Array(NODE_SIZE).fill(0));Object.freeze(EMPTY$4.buffer);function coerce$6(o){if(o instanceof Uint8Array&&o.constructor.name==="Uint8Array")return o;if(o instanceof ArrayBuffer)return new Uint8Array(o);if(ArrayBuffer.isView(o))return new Uint8Array(o.buffer,o.byteOffset,o.byteLength);throw new Error("Unknown type, must be binary type")}const name$5="sha2-256",code$7=18,size$2=32,prefix=new Uint8Array([18,32]);let Digest$7=class{constructor(i){this.code=code$7,this.name=name$5,this.bytes=i,this.size=size$2,this.digest=i.subarray(2)}};const digest$2=o=>{const i=new Uint8Array(prefix.length+size$2);return i.set(prefix,0),i.set(sha256$7(o),prefix.length),new Digest$7(i)},code$6=code$7,SHA256=Object.freeze(Object.defineProperty({__proto__:null,code:code$6,digest:digest$2,name:name$5,size:size$2},Symbol.toStringTag,{value:"Module"}));function base$6(o,i){if(o.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src$6=base$6,_brrp__multiformats_scope_baseX$6=src$6;let Encoder$6=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseEncode");this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}},Decoder$6=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseDecode");U(this,"prefixCodePoint");this.name=i,this.prefix=s;const c=s.codePointAt(0);if(c===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=c,this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or$8(this,i)}},ComposedDecoder$6=class{constructor(i){U(this,"decoders");this.decoders=i}or(i){return or$8(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a!=null)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$8(o,i){return new ComposedDecoder$6({...o.decoders??{[o.prefix]:o},...i.decoders??{[i.prefix]:i}})}let Codec$6=class{constructor(i,s,a,c){U(this,"name");U(this,"prefix");U(this,"baseEncode");U(this,"baseDecode");U(this,"encoder");U(this,"decoder");this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder$6(i,s,a),this.decoder=new Decoder$6(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}};function from$e({name:o,prefix:i,encode:s,decode:a}){return new Codec$6(o,i,s,a)}function baseX$6({name:o,prefix:i,alphabet:s}){const{encode:a,decode:c}=_brrp__multiformats_scope_baseX$6(s,o);return from$e({prefix:i,name:o,encode:a,decode:d=>coerce$6(c(d))})}function decode$u(o,i,s,a){const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f}function encode$k(o,i,s){const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f!==0&&(d+=i[c&g<=INT$7;)i[s++]=o&255|MSB$7,o/=128;for(;o&MSBALL$7;)i[s++]=o&255|MSB$7,o>>>=7;return i[s]=o|0,encode$j.bytes=s-a+1,i}var decode$t=read$7,MSB$1$7=128,REST$1$7=127;function read$7(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$7.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$7)<=MSB$1$7);return read$7.bytes=d-a,s}var N1$6=Math.pow(2,7),N2$6=Math.pow(2,14),N3$6=Math.pow(2,21),N4$6=Math.pow(2,28),N5$6=Math.pow(2,35),N6$6=Math.pow(2,42),N7$6=Math.pow(2,49),N8$6=Math.pow(2,56),N9$6=Math.pow(2,63),length$6=function(o){return o{const a=new Uint8Array(o.length+i.length);return a.set(o,0),a.set(i,o.length),truncatedHash(a,s)};function truncate(o){return o[NODE_SIZE-1]&=63,o}const MAX_LEVEL=64;class ZeroComm{constructor(){this.bytes=new Uint8Array(MAX_LEVEL*NODE_SIZE),this.bytes.set(empty$4(),0),this.node=empty$4(),this.length=NODE_SIZE}slice(i,s){for(;this.length{if(o<0||o>=MAX_LEVEL)throw new Error(`Only levels between 0 and ${MAX_LEVEL-1} inclusive are available`);return ZERO_COMM.slice(NODE_SIZE*o,NODE_SIZE*(o+1))},split$1=o=>{const i=o.length/NODE_SIZE,s=new Array(i);for(let a=0;atoZeroPaddedSize(o)/FR_RATIO,pad=(o,i=new Uint8Array(toPieceSize(o.length)))=>{const a=toZeroPaddedSize(o.byteLength)/IN_BYTES_PER_QUAD;for(let c=0;c>6;i[f+63]&=63;for(let g=64;g<96;g++)i[f+g]=o[d+g]<<4|o[d+g-1]>>4;i[f+95]&=63;for(let g=96;g<127;g++)i[f+g]=o[d+g]<<6|o[d+g-1]>>2;i[f+127]=o[d+126]>>2}return i},log2Floor=o=>{let i=0n;for(;o>>=1n;)i++;return Number(i)},log2Ceil=o=>o<=1n?0:log2Floor(BigInt(o)-1n)+1,toPadding=o=>toPadded(o)-o,toPadded=o=>toQauds(o)*PADDED_BYTES_PER_QUAD,toQauds=o=>{const i=(o+PADDED_BYTES_PER_QUAD-1n)/PADDED_BYTES_PER_QUAD;return 2n**BigInt(log2Ceil(i))},fromHeight=o=>fromWidth(2n**BigInt(o)),fromWidth=o=>o*EXPANDED_BYTES_PER_NODE,name$4="fr32-sha2-256-trunc254-padded-binary-tree",code$5=4113,MAX_PADDING_SIZE=9,HEIGHT_SIZE=1,ROOT_SIZE=size$2,MAX_DIGEST_SIZE=MAX_PADDING_SIZE+HEIGHT_SIZE+size$2,TAG_SIZE=encodingLength$6(code$5),MAX_SIZE=TAG_SIZE+encodingLength$6(MAX_DIGEST_SIZE)+MAX_DIGEST_SIZE,MAX_HEIGHT$1=255,MAX_PAYLOAD_SIZE$1=fromHeight(MAX_HEIGHT$1)*BigInt(IN_BITS_FR)/BigInt(OUT_BITS_FR),fromPiece=({padding:o,height:i,root:s})=>{const a=encodingLength$6(Number(o)),c=a+HEIGHT_SIZE+ROOT_SIZE,d=encodingLength$6(c),f=TAG_SIZE+d+c;let g=0;const y=new Uint8Array(f);return encodeTo$6(code$5,y,g),g+=TAG_SIZE,encodeTo$6(c,y,g),g+=d,encodeTo$6(Number(o),y,g),g+=a,y[g]=i,g+=HEIGHT_SIZE,y.set(s,g),new Digest$6(y)},fromBytes$3=o=>new Digest$6(o),toBytes$2=({digest:o})=>{const s=encodingLength$6(o.length)+TAG_SIZE;if(o.byteOffset>=s){const c=new Uint8Array(o.buffer,o.byteOffset-s,o.byteOffset+o.length),[d,f]=decode$s(c);if(d===code$5&&decode$s(c,f)[0]===o.length)return c}const a=new Uint8Array(o.length+s);return encodeTo$6(code$5,a),encodeTo$6(o.length,a,TAG_SIZE),a.set(o,s),a},height=({digest:o})=>{const[,i]=decode$s(o);return o[i]},padding=({digest:o})=>{const[i]=decode$s(o);return BigInt(i)},root=({digest:o})=>{const[,i]=decode$s(o);return o.subarray(i+HEIGHT_SIZE,i+HEIGHT_SIZE+size$2)};let Digest$6=class{constructor(i){this.bytes=i;const[s]=decode$s(i);if(s!==code$5)throw new RangeError(`Expected multihash with code ${code$5}`);let a=TAG_SIZE;const[c,d]=decode$s(i,a);a+=d;const f=i.subarray(a);if(f.length!==c)throw new RangeError(`Invalid multihash size expected ${a+c} bytes, got ${i.length} bytes`);this.digest=f}get name(){return name$4}get code(){return code$5}get size(){return this.digest.length}get padding(){return padding(this)}get height(){return height(this)}get root(){return root(this)}};const digest$1=Object.freeze(Object.defineProperty({__proto__:null,HEIGHT_SIZE,MAX_DIGEST_SIZE,MAX_HEIGHT:MAX_HEIGHT$1,MAX_PAYLOAD_SIZE:MAX_PAYLOAD_SIZE$1,MAX_SIZE,ROOT_SIZE,TAG_SIZE,code:code$5,fromBytes:fromBytes$3,fromPiece,height,name:name$4,padding,root,toBytes:toBytes$2},Symbol.toStringTag,{value:"Module"})),name$3="fr32-sha2-256-trunc254-padded-binary-tree",code$4=4113,MAX_HEIGHT=255,MAX_PAYLOAD_SIZE=fromHeight(MAX_HEIGHT)*BigInt(IN_BITS_FR)/BigInt(OUT_BITS_FR),digest=o=>{const i=new Hasher$4;return i.write(o),i.digest()},create$i=()=>new Hasher$4;let Hasher$4=class{constructor(){this.bytesWritten=0n,this.buffer=new Uint8Array(IN_BYTES_PER_QUAD),this.offset=0,this.layers=[[]]}count(){return this.bytesWritten}digest(){const i=new Uint8Array(MAX_SIZE),s=this.digestInto(i,0,!0);return fromBytes$3(i.subarray(0,s))}digestInto(i,s=0,a=!0){const{buffer:c,layers:d,offset:f,bytesWritten:g}=this;let[y,...b]=d;(f>0||g===0n)&&(y=[...y,...split$1(pad(c.fill(0,f)))]);const $=build([y,...b]),x=$.length-1,[T]=$[x],A=Number(toPadding(this.bytesWritten)),E=encodingLength$6(A);let S=s;if(a){encodeTo$6(code$4,i,S),S+=TAG_SIZE;const _=E+HEIGHT_SIZE+ROOT_SIZE,C=encodingLength$6(_);encodeTo$6(_,i,S),S+=C}return encodeTo$6(A,i,S),S+=E,i[S]=x,S+=1,i.set(T,S),S+=T.length,S-s}write(i){const{buffer:s,offset:a,layers:c}=this,d=c[0],{length:f}=i;if(f===0)return this;if(this.bytesWritten+BigInt(f)>MAX_PAYLOAD_SIZE)throw new RangeError(`Writing ${f} bytes exceeds max payload size of ${MAX_PAYLOAD_SIZE}`);if(a+fflush$1(o,!1),build=o=>flush$1([...o],!0),flush$1=(o,i)=>{let s=0;for(;s0&&a&&c.push(fromLevel(s)),s+=1,a=a?i?[...a]:a:[];let d=0;for(;d+1{const s=[];for(const c of o.receipts.values()){const d=c.out;d.ok?s.push(d.ok):s.push({...d.error,error:!0})}const a=encode$A(s);return{headers:HEADERS,body:a}},response=Object.freeze(Object.defineProperty({__proto__:null,contentType:contentType$2,encode:encode$i},Symbol.toStringTag,{value:"Module"})),contentType$1="application/car",decode$r=async({body:o})=>{const{roots:i,blocks:s}=decode$M(o),a=[];for(const{cid:d}of i){const f=view$2({root:d,blocks:s});a.push(f)}return await build$1({invocations:a})},request$1=Object.freeze(Object.defineProperty({__proto__:null,contentType:contentType$1,decode:decode$r},Symbol.toStringTag,{value:"Module"})),{contentType}=request$1;inbound({decoders:{[contentType]:request$1,[contentType$3]:request$3},encoders:{"*/*;q=0.1":response,[contentType$3]:response$1}});const services={STOREFRONT:{url:new URL("https://up.web3.storage"),principal:parse$2("did:web:web3.storage")},AGGREGATOR:{url:new URL("https://aggregator.web3.storage"),principal:parse$2("did:web:web3.storage")},DEALER:{url:new URL("https://dealer.web3.storage"),principal:parse$2("did:web:web3.storage")},DEAL_TRACKER:{url:new URL("https://tracker.web3.storage"),principal:parse$2("did:web:web3.storage")}},connection$1=connect({id:services.STOREFRONT.principal,codec:outbound,channel:open$2({url:services.STOREFRONT.url,method:"POST"})});async function filecoinOffer({issuer:o,with:i,proofs:s,audience:a},c,d,f={}){const g=f.connection??connection$1;return await filecoinOffer$1.invoke({issuer:o,audience:a??services.STOREFRONT.principal,with:i,nb:{content:c,piece:d},proofs:s,expiration:1/0}).execute(g)}async function filecoinInfo({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection$1;return await filecoinInfo$1.invoke({issuer:o,audience:a??services.STOREFRONT.principal,with:i,nb:{piece:c},proofs:s}).execute(f)}connect({id:services.AGGREGATOR.principal,codec:outbound,channel:open$2({url:services.AGGREGATOR.url,method:"POST"})});connect({id:services.DEALER.principal,codec:outbound,channel:open$2({url:services.DEALER.url,method:"POST"})});connect({id:services.DEAL_TRACKER.principal,codec:outbound,channel:open$2({url:services.DEAL_TRACKER.url,method:"POST"})});function base$5(o,i){if(o.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src$5=base$5,_brrp__multiformats_scope_baseX$5=src$5;const equals$a=(o,i)=>{if(o===i)return!0;if(o.byteLength!==i.byteLength)return!1;for(let s=0;s{if(o instanceof Uint8Array&&o.constructor.name==="Uint8Array")return o;if(o instanceof ArrayBuffer)return new Uint8Array(o);if(ArrayBuffer.isView(o))return new Uint8Array(o.buffer,o.byteOffset,o.byteLength);throw new Error("Unknown type, must be binary type")};let Encoder$5=class{constructor(i,s,a){this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}},Decoder$5=class{constructor(i,s,a){if(this.name=i,this.prefix=s,s.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s.codePointAt(0),this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or$7(this,i)}},ComposedDecoder$5=class{constructor(i){this.decoders=i}or(i){return or$7(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const or$7=(o,i)=>new ComposedDecoder$5({...o.decoders||{[o.prefix]:o},...i.decoders||{[i.prefix]:i}});let Codec$5=class{constructor(i,s,a,c){this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder$5(i,s,a),this.decoder=new Decoder$5(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}};const from$d=({name:o,prefix:i,encode:s,decode:a})=>new Codec$5(o,i,s,a),baseX$5=({prefix:o,name:i,alphabet:s})=>{const{encode:a,decode:c}=_brrp__multiformats_scope_baseX$5(s,i);return from$d({prefix:o,name:i,encode:a,decode:d=>coerce$5(c(d))})},decode$q=(o,i,s,a)=>{const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f},encode$h=(o,i,s)=>{const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f&&(d+=i[c&g<from$d({prefix:i,name:o,encode(c){return encode$h(c,a,s)},decode(c){return decode$q(c,a,s,o)}}),base32$4=rfc4648$5({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5});rfc4648$5({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5});rfc4648$5({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5});rfc4648$5({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5});rfc4648$5({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5});rfc4648$5({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5});rfc4648$5({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5});rfc4648$5({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5});rfc4648$5({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});const base58btc$4=baseX$5({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});baseX$5({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var encode_1$5=encode$g,MSB$6=128,REST$6=127,MSBALL$6=~REST$6,INT$6=Math.pow(2,31);function encode$g(o,i,s){i=i||[],s=s||0;for(var a=s;o>=INT$6;)i[s++]=o&255|MSB$6,o/=128;for(;o&MSBALL$6;)i[s++]=o&255|MSB$6,o>>>=7;return i[s]=o|0,encode$g.bytes=s-a+1,i}var decode$p=read$6,MSB$1$6=128,REST$1$6=127;function read$6(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$6.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$6)<=MSB$1$6);return read$6.bytes=d-a,s}var N1$5=Math.pow(2,7),N2$5=Math.pow(2,14),N3$5=Math.pow(2,21),N4$5=Math.pow(2,28),N5$5=Math.pow(2,35),N6$5=Math.pow(2,42),N7$5=Math.pow(2,49),N8$5=Math.pow(2,56),N9$5=Math.pow(2,63),length$5=function(o){return o[_brrp_varint$5.decode(o,i),_brrp_varint$5.decode.bytes],encodeTo$5=(o,i,s=0)=>(_brrp_varint$5.encode(o,i,s),i),encodingLength$5=o=>_brrp_varint$5.encodingLength(o),create$h=(o,i)=>{const s=i.byteLength,a=encodingLength$5(o),c=a+encodingLength$5(s),d=new Uint8Array(c+s);return encodeTo$5(o,d,0),encodeTo$5(s,d,a),d.set(i,c),new Digest$5(o,s,i,d)},decode$n=o=>{const i=coerce$5(o),[s,a]=decode$o(i),[c,d]=decode$o(i.subarray(a)),f=i.subarray(a+d);if(f.byteLength!==c)throw new Error("Incorrect length");return new Digest$5(s,c,f,i)},equals$9=(o,i)=>{if(o===i)return!0;{const s=i;return o.code===s.code&&o.size===s.size&&s.bytes instanceof Uint8Array&&equals$a(o.bytes,s.bytes)}};let Digest$5=class{constructor(i,s,a,c){this.code=i,this.size=s,this.digest=a,this.bytes=c}};const format$4=(o,i)=>{const{bytes:s,version:a}=o;switch(a){case 0:return toStringV0$4(s,baseCache$4(o),i||base58btc$4.encoder);default:return toStringV1$4(s,baseCache$4(o),i||base32$4.encoder)}},cache$5=new WeakMap,baseCache$4=o=>{const i=cache$5.get(o);if(i==null){const s=new Map;return cache$5.set(o,s),s}return i};let CID$4=class ye{constructor(i,s,a,c){this.code=s,this.version=i,this.multihash=a,this.bytes=c,this["/"]=c}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:{const{code:i,multihash:s}=this;if(i!==DAG_PB_CODE$5)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(s.code!==SHA_256_CODE$4)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ye.createV0(s)}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:{const{code:i,digest:s}=this.multihash,a=create$h(i,s);return ye.createV1(this.code,a)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(i){return ye.equals(this,i)}static equals(i,s){const a=s;return a&&i.code===a.code&&i.version===a.version&&equals$9(i.multihash,a.multihash)}toString(i){return format$4(this,i)}toJSON(){return{"/":format$4(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(i){if(i==null)return null;const s=i;if(s instanceof ye)return s;if(s["/"]!=null&&s["/"]===s.bytes||s.asCID===s){const{version:a,code:c,multihash:d,bytes:f}=s;return new ye(a,c,d,f||encodeCID$4(a,c,d.bytes))}else if(s[cidSymbol$4]===!0){const{version:a,multihash:c,code:d}=s,f=decode$n(c);return ye.create(a,d,f)}else return null}static create(i,s,a){if(typeof s!="number")throw new Error("String codecs are no longer supported");if(!(a.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(i){case 0:{if(s!==DAG_PB_CODE$5)throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE$5}) block encoding`);return new ye(i,s,a,a.bytes)}case 1:{const c=encodeCID$4(i,s,a.bytes);return new ye(i,s,a,c)}default:throw new Error("Invalid version")}}static createV0(i){return ye.create(0,DAG_PB_CODE$5,i)}static createV1(i,s){return ye.create(1,i,s)}static decode(i){const[s,a]=ye.decodeFirst(i);if(a.length)throw new Error("Incorrect length");return s}static decodeFirst(i){const s=ye.inspectBytes(i),a=s.size-s.multihashSize,c=coerce$5(i.subarray(a,a+s.multihashSize));if(c.byteLength!==s.multihashSize)throw new Error("Incorrect length");const d=c.subarray(s.multihashSize-s.digestSize),f=new Digest$5(s.multihashCode,s.digestSize,d,c);return[s.version===0?ye.createV0(f):ye.createV1(s.codec,f),i.subarray(s.size)]}static inspectBytes(i){let s=0;const a=()=>{const[x,T]=decode$o(i.subarray(s));return s+=T,x};let c=a(),d=DAG_PB_CODE$5;if(c===18?(c=0,s=0):d=a(),c!==0&&c!==1)throw new RangeError(`Invalid CID version ${c}`);const f=s,g=a(),y=a(),b=s+y,$=b-f;return{version:c,codec:d,multihashCode:g,digestSize:y,multihashSize:$,size:b}}static parse(i,s){const[a,c]=parseCIDtoBytes$4(i,s),d=ye.decode(c);if(d.version===0&&i[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache$4(d).set(a,i),d}};const parseCIDtoBytes$4=(o,i)=>{switch(o[0]){case"Q":{const s=i||base58btc$4;return[base58btc$4.prefix,s.decode(`${base58btc$4.prefix}${o}`)]}case base58btc$4.prefix:{const s=i||base58btc$4;return[base58btc$4.prefix,s.decode(o)]}case base32$4.prefix:{const s=i||base32$4;return[base32$4.prefix,s.decode(o)]}default:{if(i==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[o[0],i.decode(o)]}}},toStringV0$4=(o,i,s)=>{const{prefix:a}=s;if(a!==base58btc$4.prefix)throw Error(`Cannot string encode V0 in ${s.name} encoding`);const c=i.get(a);if(c==null){const d=s.encode(o).slice(1);return i.set(a,d),d}else return c},toStringV1$4=(o,i,s)=>{const{prefix:a}=s,c=i.get(a);if(c==null){const d=s.encode(o);return i.set(a,d),d}else return c},DAG_PB_CODE$5=112,SHA_256_CODE$4=18,encodeCID$4=(o,i,s)=>{const a=encodingLength$5(o),c=a+encodingLength$5(i),d=new Uint8Array(c+s.byteLength);return encodeTo$5(o,d,0),encodeTo$5(i,d,a),d.set(s,c),d},cidSymbol$4=Symbol.for("@ipld/js-cid/CID"),create$g=(o,i)=>CID$4.create(1,o,i),name$2="raw",code$3=85,encode$f=o=>coerce$5(o),decode$m=o=>coerce$5(o),raw=Object.freeze(Object.defineProperty({__proto__:null,code:code$3,decode:decode$m,encode:encode$f,name:name$2},Symbol.toStringTag,{value:"Module"})),from$c=({name:o,code:i,encode:s})=>new Hasher$3(o,i,s);let Hasher$3=class{constructor(i,s,a){this.name=i,this.code=s,this.encode=a}digest(i){if(i instanceof Uint8Array){const s=this.encode(i);return s instanceof Uint8Array?create$h(this.code,s):s.then(a=>create$h(this.code,a))}else throw Error("Unknown type, must be binary type")}};const sha$2=o=>async i=>new Uint8Array(await crypto.subtle.digest(o,i)),sha256$2=from$c({name:"sha2-256",code:18,encode:sha$2("SHA-256")});var retry$2={};function RetryOperation(o,i){typeof i=="boolean"&&(i={forever:i}),this._originalTimeouts=JSON.parse(JSON.stringify(o)),this._timeouts=o,this._options=i||{},this._maxRetryTime=i&&i.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))}var retry_operation=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(o){if(this._timeout&&clearTimeout(this._timeout),!o)return!1;var i=new Date().getTime();if(o&&i-this._operationStart>=this._maxRetryTime)return this._errors.push(o),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(o);var s=this._timeouts.shift();if(s===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),s=this._cachedTimeouts.slice(-1);else return!1;var a=this;return this._timer=setTimeout(function(){a._attempts++,a._operationTimeoutCb&&(a._timeout=setTimeout(function(){a._operationTimeoutCb(a._attempts)},a._operationTimeout),a._options.unref&&a._timeout.unref()),a._fn(a._attempts)},s),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(o,i){this._fn=o,i&&(i.timeout&&(this._operationTimeout=i.timeout),i.cb&&(this._operationTimeoutCb=i.cb));var s=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){s._operationTimeoutCb()},s._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(o){console.log("Using RetryOperation.try() is deprecated"),this.attempt(o)};RetryOperation.prototype.start=function(o){console.log("Using RetryOperation.start() is deprecated"),this.attempt(o)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var o={},i=null,s=0,a=0;a=s&&(i=c,s=f)}return i};(function(o){var i=retry_operation;o.operation=function(s){var a=o.timeouts(s);return new i(a,{forever:s&&(s.forever||s.retries===1/0),unref:s&&s.unref,maxRetryTime:s&&s.maxRetryTime})},o.timeouts=function(s){if(s instanceof Array)return[].concat(s);var a={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var c in s)a[c]=s[c];if(a.minTimeout>a.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var d=[],f=0;f{const a=s.retries-(i-1);return o.attemptNumber=i,o.retriesLeft=a,o},isNetworkError=o=>networkErrorMsgs.has(o),getDOMException=o=>globalThis.DOMException===void 0?new Error(o):new DOMException(o);async function pRetry(o,i){return new Promise((s,a)=>{i={onFailedAttempt(){},retries:10,...i};const c=retry$1.operation(i);c.attempt(async d=>{try{s(await o(d))}catch(f){if(!(f instanceof Error)){a(new TypeError(`Non-error was thrown: "${f}". You should only throw errors.`));return}if(f instanceof AbortError)c.stop(),a(f.originalError);else if(f instanceof TypeError&&!isNetworkError(f.message))c.stop(),a(f);else{decorateErrorWithCounts(f,d,i);try{await i.onFailedAttempt(f)}catch(g){a(g);return}c.retry(f)||a(c.mainError())}}}),i.signal&&!i.signal.aborted&&i.signal.addEventListener("abort",()=>{c.stop();const d=i.signal.reason===void 0?getDOMException("The operation was aborted."):i.signal.reason;a(d instanceof Error?d:getDOMException(d))},{once:!0})})}const serviceURL=new URL("https://up.web3.storage"),servicePrincipal=parse$2("did:web:web3.storage"),receiptsEndpoint="https://up.web3.storage/receipt/",connection=connect({id:servicePrincipal,codec:outbound,channel:open$2({url:serviceURL,method:"POST"})}),REQUEST_RETRIES=3;function createUploadProgressHandler$1(o,i){function s({total:a,loaded:c,lengthComputable:d}){return i({total:a,loaded:c,lengthComputable:d,url:o})}return s}async function add$3({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=c instanceof Uint8Array?c:new Uint8Array(await c.arrayBuffer()),g=await link$2(f),y=d.connection??connection,b=await pRetry(async()=>await add$a.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:{link:g,size:f.length},proofs:s,nonce:d.nonce}).execute(y),{onFailedAttempt:console.warn,retries:d.retries??REQUEST_RETRIES});if(!b.out.ok)throw new Error(`failed ${add$a.can} invocation`,{cause:b.out.error});if(b.out.ok.status==="done")return g;const $=b.out.ok,x=d.fetchWithUploadProgress||d.fetch||globalThis.fetch.bind(globalThis);let T=!1;const A=await pRetry(async()=>{var E;try{const S=await x($.url,{method:"PUT",body:c,headers:$.headers,signal:d.signal,onUploadProgress:_=>{T=!0,d.onUploadProgress&&createUploadProgressHandler$1($.url,d.onUploadProgress)(_)},duplex:"half"});if(S.status>=400&&S.status<500)throw new AbortError(`upload failed: ${S.status}`);return S}catch(S){throw((E=d.signal)==null?void 0:E.aborted)===!0?new AbortError("upload aborted"):S}},{retries:d.retries??REQUEST_RETRIES});if(!T&&d.onUploadProgress){const E=new Blob([c]);d.onUploadProgress({total:E.size,loaded:E.size,lengthComputable:!1})}if(!A.ok)throw new Error(`upload failed: ${A.status}`);return g}async function get$a({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await pRetry(async()=>await get$h.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:{link:c},proofs:s,nonce:d.nonce}).execute(f),{onFailedAttempt:console.warn,retries:d.retries??REQUEST_RETRIES});if(!g.out.ok)throw new Error(`failed ${get$h.can} invocation`,{cause:g.out.error});return g.out.ok}async function list$4({issuer:o,with:i,proofs:s,audience:a},c={}){const d=c.connection??connection,f=await list$9.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),proofs:s,nb:{cursor:c.cursor,size:c.size,pre:c.pre},nonce:c.nonce}).execute(d);if(!f.out.ok)throw new Error(`failed ${list$9.can} invocation`,{cause:f.out.error});return f.out.ok}async function remove$4({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await remove$8.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:{link:c},proofs:s,nonce:d.nonce}).execute(f);if(!g.out.ok)throw new Error(`failed ${remove$8.can} invocation`,{cause:g.out.error});return g.out}class ReceiptNotFound extends Error{constructor(i){super(),this.taskCid=i}get reason(){return`receipt not found for task ${this.taskCid} in the indexed workflow`}get name(){return"ReceiptNotFound"}}class ReceiptMissing extends Error{constructor(i){super(),this.taskCid=i}get reason(){return`receipt missing for task ${this.taskCid}`}get name(){return"ReceiptMissing"}}async function poll(o,i={}){return await pRetry(async()=>{const s=await get$9(o,i);if(s.error)throw s.error.name==="ReceiptNotFound"?s.error:new AbortError(new Error("failed to fetch blob/accept receipt",{cause:s.error}));return s.ok},{onFailedAttempt:console.warn,retries:i.retries??REQUEST_RETRIES})}async function get$9(o,i={}){const s=new URL(o.toString(),i.receiptsEndpoint??receiptsEndpoint),c=await(i.fetch??globalThis.fetch.bind(globalThis))(s);if(c.status===404)return{error:new ReceiptNotFound(o)};const d=new Uint8Array(await c.arrayBuffer()),g=(await decode$K({body:d,headers:{}})).receipts.get(o.toString());return g?{ok:g}:{error:new ReceiptMissing(o)}}function createUploadProgressHandler(o,i){return({total:a,loaded:c,lengthComputable:d})=>i({total:a,loaded:c,lengthComputable:d,url:o})}function getConcludeReceipt(o){const i=new Map;for(const s of o.iterateIPLDBlocks())i.set(`${s.cid}`,s);return view$1({root:o.capabilities[0].nb.receipt,blocks:i})}function parseBlobAddReceiptNext(o){const i=o.fx.fork,s=i.find($=>$.capabilities[0].can===allocate.can),a=i.filter($=>$.capabilities[0].can===conclude$1.can),c=i.find($=>$.capabilities[0].can===put.can),d=i.find($=>$.capabilities[0].can===accept.can);if(!s||!a.length||!c||!d)throw new Error("mandatory effects not received");const f=a.map($=>getConcludeReceipt($)),g=f.find($=>$.ran.link().equals(s.cid)),y=f.find($=>$.ran.link().equals(c.cid)),b=f.find($=>$.ran.link().equals(d.cid));if(!g)throw new Error("mandatory effects not received");return{allocate:{task:s,receipt:g},put:{task:c,receipt:y},accept:{task:d,receipt:b}}}function createConcludeInvocation(o,i,s){const a=[],c=[];for(const f of s.iterateIPLDBlocks())a.push(f),c.push(f.cid);const d=conclude$1.invoke({issuer:o,audience:i,with:o.toDIDKey(),nb:{receipt:s.link()},expiration:1/0,facts:[{...c}]});for(const f of a)d.attach(f);return d}async function add$2({issuer:o,with:i,proofs:s,audience:a},c,d,f={}){var B;const g=d instanceof Uint8Array?d:new Uint8Array(await d.arrayBuffer()),y=g.length,b=f.connection??connection,$=await pRetry(async()=>await add$4.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input$8(c,y),proofs:s,nonce:f.nonce}).execute(b),{onFailedAttempt:console.warn,retries:f.retries??REQUEST_RETRIES});if(!$.out.ok)throw new Error(`failed ${add$4.can} invocation`,{cause:$.out.error});const x=parseBlobAddReceiptNext($),{receipt:T}=x.allocate;if(!T.out.ok)throw new Error(`failed ${add$4.can} invocation`,{cause:T.out.error});const{address:A}=T.out.ok;if(A){const D=f.fetchWithUploadProgress||f.fetch||globalThis.fetch.bind(globalThis);let I=!1;const{status:O}=await pRetry(async()=>{var N;try{const L=await D(A.url,{method:"PUT",mode:"cors",body:g,headers:A.headers,signal:f.signal,onUploadProgress:R=>{I=!0,f.onUploadProgress&&createUploadProgressHandler(A.url,f.onUploadProgress)(R)},duplex:"half"});if(L.status>=400&&L.status<500)throw new AbortError(`upload failed: ${L.status}`);return L}catch(L){throw((N=f.signal)==null?void 0:N.aborted)===!0?new AbortError("upload aborted"):L}},{retries:f.retries??REQUEST_RETRIES});if(O!==200)throw new Error(`upload failed: ${O}`);if(!I&&f.onUploadProgress){const N=new Blob([g]);f.onUploadProgress({total:N.size,loaded:N.size,lengthComputable:!1})}}let{receipt:E}=x.put;if(!(E!=null&&E.out.ok)){const D=from$h(x.put.task.facts[0].keys);if(E=await issue$1({issuer:D,ran:x.put.task.cid,result:{ok:{}}}),!(await createConcludeInvocation(o,a??servicePrincipal,E).execute(b)).out.ok)throw new Error(`failed ${add$4.can} invocation`,{cause:$.out.error})}let{receipt:S}=x.accept;S!=null&&S.out.ok||(S=await poll(x.accept.task.link(),f));const _=new Map([...S.iterateIPLDBlocks()].map(D=>[`${D.cid}`,D]));return{site:view$3({root:(B=S.out.ok)==null?void 0:B.site,blocks:_})}}const ability$2=add$4.can,input$8=(o,i)=>({blob:{digest:o.bytes,size:i}});async function get$8({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await get$b.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input$7(c),proofs:s,nonce:d.nonce}).execute(f);if(!g.out.ok)throw new Error(`failed ${get$b.can} invocation`,{cause:g.out.error});return g.out}get$b.can;const input$7=o=>({digest:o.bytes});async function list$3({issuer:o,with:i,proofs:s,audience:a},c={}){const d=c.connection??connection,f=await list$5.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),proofs:s,nb:input$6(c.cursor,c.size),nonce:c.nonce}).execute(d);if(!f.out.ok)throw new Error(`failed ${list$5.can} invocation`,{cause:f.out.error});return f.out.ok}list$5.can;const input$6=(o,i)=>({cursor:o,size:i});async function remove$3({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await remove$5.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input$5(c),proofs:s,nonce:d.nonce}).execute(f);if(!g.out.ok)throw new Error(`failed ${remove$5.can} invocation`,{cause:g.out.error});return g.out}remove$5.can;const input$5=o=>({digest:o.bytes});async function add$1({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await pRetry(async()=>await add$5.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input$4(c),proofs:s}).execute(f),{onFailedAttempt:console.warn,retries:d.retries??REQUEST_RETRIES});if(!g.out.ok)throw new Error(`failed ${add$5.can} invocation`,{cause:g.out.error});return g.out.ok}const ability$1=add$5.can,input$4=o=>({index:o});async function add({issuer:o,with:i,proofs:s,audience:a},c,d,f={}){const g=f.connection??connection,y=await pRetry(async()=>await add$9.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input$3(c,d),proofs:s,nonce:f.nonce}).execute(g),{onFailedAttempt:console.warn,retries:f.retries??REQUEST_RETRIES});if(!y.out.ok)throw new Error(`failed ${add$9.can} invocation`,{cause:y.out.error});return y.out.ok}const ability=add$9.can,input$3=(o,i)=>({root:o,shards:i});async function get$7({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await pRetry(async()=>await get$g.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input$2(c),proofs:s,nonce:d.nonce}).execute(f),{onFailedAttempt:console.warn,retries:d.retries??REQUEST_RETRIES});if(!g.out.ok)throw new Error(`failed ${get$g.can} invocation`,{cause:g.out.error});return g.out.ok}get$g.can;const input$2=o=>({root:o});async function list$2({issuer:o,with:i,proofs:s,audience:a},c={}){const d=c.connection??connection,f=await list$8.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),proofs:s,nb:input$1(c.cursor,c.size,c.pre),nonce:c.nonce}).execute(d);if(!f.out.ok)throw new Error(`failed ${list$8.can} invocation`,{cause:f.out.error});return f.out.ok}list$8.can;const input$1=(o,i,s)=>({cursor:o,size:i,pre:s});async function remove$2({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await remove$7.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input(c),proofs:s,nonce:d.nonce}).execute(f);if(!g.out.ok)throw new Error(`failed ${remove$7.can} invocation`,{cause:g.out.error});return g.out.ok}remove$7.can;const input=o=>({root:o});function equals$8(o,i){if(o===i)return!0;if(o.byteLength!==i.byteLength)return!1;for(let s=0;s=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src$4=base$4,_brrp__multiformats_scope_baseX$4=src$4;let Encoder$4=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseEncode");this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}},Decoder$4=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseDecode");U(this,"prefixCodePoint");this.name=i,this.prefix=s;const c=s.codePointAt(0);if(c===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=c,this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or$6(this,i)}},ComposedDecoder$4=class{constructor(i){U(this,"decoders");this.decoders=i}or(i){return or$6(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a!=null)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$6(o,i){return new ComposedDecoder$4({...o.decoders??{[o.prefix]:o},...i.decoders??{[i.prefix]:i}})}let Codec$4=class{constructor(i,s,a,c){U(this,"name");U(this,"prefix");U(this,"baseEncode");U(this,"baseDecode");U(this,"encoder");U(this,"decoder");this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder$4(i,s,a),this.decoder=new Decoder$4(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}};function from$b({name:o,prefix:i,encode:s,decode:a}){return new Codec$4(o,i,s,a)}function baseX$4({name:o,prefix:i,alphabet:s}){const{encode:a,decode:c}=_brrp__multiformats_scope_baseX$4(s,o);return from$b({prefix:i,name:o,encode:a,decode:d=>coerce$4(c(d))})}function decode$l(o,i,s,a){const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f}function encode$e(o,i,s){const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f!==0&&(d+=i[c&g<=INT$5;)i[s++]=o&255|MSB$5,o/=128;for(;o&MSBALL$5;)i[s++]=o&255|MSB$5,o>>>=7;return i[s]=o|0,encode$d.bytes=s-a+1,i}var decode$k=read$5,MSB$1$5=128,REST$1$5=127;function read$5(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$5.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$5)<=MSB$1$5);return read$5.bytes=d-a,s}var N1$4=Math.pow(2,7),N2$4=Math.pow(2,14),N3$4=Math.pow(2,21),N4$4=Math.pow(2,28),N5$4=Math.pow(2,35),N6$4=Math.pow(2,42),N7$4=Math.pow(2,49),N8$4=Math.pow(2,56),N9$4=Math.pow(2,63),length$4=function(o){return o{const[x,T]=decode$j(i.subarray(s));return s+=T,x};let c=a(),d=DAG_PB_CODE$4;if(c===18?(c=0,s=0):d=a(),c!==0&&c!==1)throw new RangeError(`Invalid CID version ${c}`);const f=s,g=a(),y=a(),b=s+y,$=b-f;return{version:c,codec:d,multihashCode:g,digestSize:y,multihashSize:$,size:b}}static parse(i,s){const[a,c]=parseCIDtoBytes$3(i,s),d=me.decode(c);if(d.version===0&&i[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache$3(d).set(a,i),d}};function parseCIDtoBytes$3(o,i){switch(o[0]){case"Q":{const s=i??base58btc$3;return[base58btc$3.prefix,s.decode(`${base58btc$3.prefix}${o}`)]}case base58btc$3.prefix:{const s=i??base58btc$3;return[base58btc$3.prefix,s.decode(o)]}case base32$3.prefix:{const s=i??base32$3;return[base32$3.prefix,s.decode(o)]}case base36$2.prefix:{const s=i??base36$2;return[base36$2.prefix,s.decode(o)]}default:{if(i==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[o[0],i.decode(o)]}}}function toStringV0$3(o,i,s){const{prefix:a}=s;if(a!==base58btc$3.prefix)throw Error(`Cannot string encode V0 in ${s.name} encoding`);const c=i.get(a);if(c==null){const d=s.encode(o).slice(1);return i.set(a,d),d}else return c}function toStringV1$3(o,i,s){const{prefix:a}=s,c=i.get(a);if(c==null){const d=s.encode(o);return i.set(a,d),d}else return c}const DAG_PB_CODE$4=112,SHA_256_CODE$3=18;function encodeCID$3(o,i,s){const a=encodingLength$4(o),c=a+encodingLength$4(i),d=new Uint8Array(c+s.byteLength);return encodeTo$4(o,d,0),encodeTo$4(i,d,a),d.set(s,c),d}const cidSymbol$3=Symbol.for("@ipld/js-cid/CID"),textDecoder=new TextDecoder;function decodeVarint(o,i){let s=0;for(let a=0;;a+=7){if(a>=64)throw new Error("protobuf: varint overflow");if(i>=o.length)throw new Error("protobuf: unexpected end of data");const c=o[i++];if(s+=a<28?(c&127)<o.length)throw new Error("protobuf: unexpected end of data");return[o.subarray(i,a),a]}function decodeKey(o,i){let s;return[s,i]=decodeVarint(o,i),[s&7,s>>3,i]}function decodeLink(o){const i={},s=o.length;let a=0;for(;as)throw new Error("protobuf: (PBLink) unexpected end of data");return i}function decodeNode(o){const i=o.length;let s=0,a,c=!1,d;for(;si)throw new Error("protobuf: (PBNode) unexpected end of data");const f={};return d&&(f.Data=d),f.Links=a||[],f}const textEncoder$1=new TextEncoder,maxInt32=2**32,maxUInt32=2**31;function encodeLink$1(o,i){let s=i.length;if(typeof o.Tsize=="number"){if(o.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(o.Tsize))throw new Error("Tsize too large for encoding");s=encodeVarint(i,s,o.Tsize)-1,i[s]=24}if(typeof o.Name=="string"){const a=textEncoder$1.encode(o.Name);s-=a.length,i.set(a,s),s=encodeVarint(i,s,a.length)-1,i[s]=18}return o.Hash&&(s-=o.Hash.length,i.set(o.Hash,s),s=encodeVarint(i,s,o.Hash.length)-1,i[s]=10),i.length-s}function encodeNode(o){const i=sizeNode(o),s=new Uint8Array(i);let a=i;if(o.Data&&(a-=o.Data.length,s.set(o.Data,a),a=encodeVarint(s,a,o.Data.length)-1,s[a]=10),o.Links)for(let c=o.Links.length-1;c>=0;c--){const d=encodeLink$1(o.Links[c],s.subarray(0,a));a-=d,a=encodeVarint(s,a,d)-1,s[a]=18}return s}function sizeLink(o){let i=0;if(o.Hash){const s=o.Hash.length;i+=1+s+sov(s)}if(typeof o.Name=="string"){const s=textEncoder$1.encode(o.Name).length;i+=1+s+sov(s)}return typeof o.Tsize=="number"&&(i+=1+sov(o.Tsize)),i}function sizeNode(o){let i=0;if(o.Data){const s=o.Data.length;i+=1+s+sov(s)}if(o.Links)for(const s of o.Links){const a=sizeLink(s);i+=1+a+sov(a)}return i}function encodeVarint(o,i,s){i-=sov(s);const a=i;for(;s>=maxUInt32;)o[i++]=s&127|128,s/=128;for(;s>=128;)o[i++]=s&127|128,s>>>=7;return o[i]=s,a}function sov(o){return o%2===0&&o++,Math.floor((len64(o)+6)/7)}function len64(o){let i=0;return o>=maxInt32&&(o=Math.floor(o/maxInt32),i=32),o>=65536&&(o>>>=16,i+=16),o>=256&&(o>>>=8,i+=8),i+len8tab[o]}const len8tab=[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],pbNodeProperties=["Data","Links"],pbLinkProperties=["Hash","Name","Tsize"],textEncoder=new TextEncoder;function linkComparator(o,i){if(o===i)return 0;const s=o.Name?textEncoder.encode(o.Name):[],a=i.Name?textEncoder.encode(i.Name):[];let c=s.length,d=a.length;for(let f=0,g=Math.min(c,d);f!i.includes(s))}function asLink(o){if(typeof o.asCID=="object"){const s=CID$3.asCID(o);if(!s)throw new TypeError("Invalid DAG-PB form");return{Hash:s}}if(typeof o!="object"||Array.isArray(o))throw new TypeError("Invalid DAG-PB form");const i={};if(o.Hash){let s=CID$3.asCID(o.Hash);try{s||(typeof o.Hash=="string"?s=CID$3.parse(o.Hash):o.Hash instanceof Uint8Array&&(s=CID$3.decode(o.Hash)))}catch(a){throw new TypeError(`Invalid DAG-PB form: ${a.message}`)}s&&(i.Hash=s)}if(!i.Hash)throw new TypeError("Invalid DAG-PB form");return typeof o.Name=="string"&&(i.Name=o.Name),typeof o.Tsize=="number"&&(i.Tsize=o.Tsize),i}function prepare(o){if((o instanceof Uint8Array||typeof o=="string")&&(o={Data:o}),typeof o!="object"||Array.isArray(o))throw new TypeError("Invalid DAG-PB form");const i={};if(o.Data!==void 0)if(typeof o.Data=="string")i.Data=textEncoder.encode(o.Data);else if(o.Data instanceof Uint8Array)i.Data=o.Data;else throw new TypeError("Invalid DAG-PB form");if(o.Links!==void 0)if(Array.isArray(o.Links))i.Links=o.Links.map(asLink),i.Links.sort(linkComparator);else throw new TypeError("Invalid DAG-PB form");else i.Links=[];return i}function validate(o){if(!o||typeof o!="object"||Array.isArray(o)||o instanceof Uint8Array||o["/"]&&o["/"]===o.bytes)throw new TypeError("Invalid DAG-PB form");if(!hasOnlyProperties(o,pbNodeProperties))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(o.Data!==void 0&&!(o.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(o.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let i=0;i0&&linkComparator(s,o.Links[i-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function toByteView(o){return o instanceof ArrayBuffer?new Uint8Array(o,0,o.byteLength):o}const code$2=112;function encode$c(o){validate(o);const i={};return o.Links&&(i.Links=o.Links.map(s=>{const a={};return s.Hash&&(a.Hash=s.Hash.bytes),s.Name!==void 0&&(a.Name=s.Name),s.Tsize!==void 0&&(a.Tsize=s.Tsize),a})),o.Data&&(i.Data=o.Data),encodeNode(i)}function decode$h(o){const i=toByteView(o),s=decodeNode(i),a={};return s.Data&&(a.Data=s.Data),s.Links&&(a.Links=s.Links.map(c=>{const d={};try{d.Hash=CID$3.decode(c.Hash)}catch{}if(!d.Hash)throw new Error("Invalid Hash field found in link, expected CID");return c.Name!==void 0&&(d.Name=c.Name),c.Tsize!==void 0&&(d.Tsize=c.Tsize),d})),a}var indexMinimal={},minimal$1={},aspromise=asPromise;function asPromise(o,i){for(var s=new Array(arguments.length-1),a=0,c=2,d=!0;c1&&g.charAt(y)==="=";)++b;return Math.ceil(g.length*3)/4-b};for(var s=new Array(64),a=new Array(123),c=0;c<64;)a[s[c]=c<26?c+65:c<52?c+71:c<62?c-4:c-59|43]=c++;i.encode=function(g,y,b){for(var $=null,x=[],T=0,A=0,E;y>2],E=(S&3)<<4,A=1;break;case 1:x[T++]=s[E|S>>4],E=(S&15)<<2,A=2;break;case 2:x[T++]=s[E|S>>6],x[T++]=s[S&63],A=0;break}T>8191&&(($||($=[])).push(String.fromCharCode.apply(String,x)),T=0)}return A&&(x[T++]=s[E],x[T++]=61,A===1&&(x[T++]=61)),$?(T&&$.push(String.fromCharCode.apply(String,x.slice(0,T))),$.join("")):String.fromCharCode.apply(String,x.slice(0,T))};var d="invalid encoding";i.decode=function(g,y,b){for(var $=b,x=0,T,A=0;A1)break;if((E=a[E])===void 0)throw Error(d);switch(x){case 0:T=E,x=1;break;case 1:y[b++]=T<<2|(E&48)>>4,T=E,x=2;break;case 2:y[b++]=(T&15)<<4|(E&60)>>2,T=E,x=3;break;case 3:y[b++]=(T&3)<<6|E,x=0;break}}if(x===1)throw Error(d);return b-$},i.test=function(g){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(g)}})(base64$1);var eventemitter=EventEmitter;function EventEmitter(){this._listeners={}}EventEmitter.prototype.on=function(i,s,a){return(this._listeners[i]||(this._listeners[i]=[])).push({fn:s,ctx:a||this}),this};EventEmitter.prototype.off=function(i,s){if(i===void 0)this._listeners={};else if(s===void 0)this._listeners[i]=[];else for(var a=this._listeners[i],c=0;c0?0:2147483648,d,f);else if(isNaN(c))a(2143289344,d,f);else if(c>34028234663852886e22)a((g<<31|2139095040)>>>0,d,f);else if(c<11754943508222875e-54)a((g<<31|Math.round(c/1401298464324817e-60))>>>0,d,f);else{var y=Math.floor(Math.log(c)/Math.LN2),b=Math.round(c*Math.pow(2,-y)*8388608)&8388607;a((g<<31|y+127<<23|b)>>>0,d,f)}}o.writeFloatLE=i.bind(null,writeUintLE),o.writeFloatBE=i.bind(null,writeUintBE);function s(a,c,d){var f=a(c,d),g=(f>>31)*2+1,y=f>>>23&255,b=f&8388607;return y===255?b?NaN:g*(1/0):y===0?g*1401298464324817e-60*b:g*Math.pow(2,y-150)*(b+8388608)}o.readFloatLE=s.bind(null,readUintLE),o.readFloatBE=s.bind(null,readUintBE)}(),typeof Float64Array<"u"?function(){var i=new Float64Array([-0]),s=new Uint8Array(i.buffer),a=s[7]===128;function c(y,b,$){i[0]=y,b[$]=s[0],b[$+1]=s[1],b[$+2]=s[2],b[$+3]=s[3],b[$+4]=s[4],b[$+5]=s[5],b[$+6]=s[6],b[$+7]=s[7]}function d(y,b,$){i[0]=y,b[$]=s[7],b[$+1]=s[6],b[$+2]=s[5],b[$+3]=s[4],b[$+4]=s[3],b[$+5]=s[2],b[$+6]=s[1],b[$+7]=s[0]}o.writeDoubleLE=a?c:d,o.writeDoubleBE=a?d:c;function f(y,b){return s[0]=y[b],s[1]=y[b+1],s[2]=y[b+2],s[3]=y[b+3],s[4]=y[b+4],s[5]=y[b+5],s[6]=y[b+6],s[7]=y[b+7],i[0]}function g(y,b){return s[7]=y[b],s[6]=y[b+1],s[5]=y[b+2],s[4]=y[b+3],s[3]=y[b+4],s[2]=y[b+5],s[1]=y[b+6],s[0]=y[b+7],i[0]}o.readDoubleLE=a?f:g,o.readDoubleBE=a?g:f}():function(){function i(a,c,d,f,g,y){var b=f<0?1:0;if(b&&(f=-f),f===0)a(0,g,y+c),a(1/f>0?0:2147483648,g,y+d);else if(isNaN(f))a(0,g,y+c),a(2146959360,g,y+d);else if(f>17976931348623157e292)a(0,g,y+c),a((b<<31|2146435072)>>>0,g,y+d);else{var $;if(f<22250738585072014e-324)$=f/5e-324,a($>>>0,g,y+c),a((b<<31|$/4294967296)>>>0,g,y+d);else{var x=Math.floor(Math.log(f)/Math.LN2);x===1024&&(x=1023),$=f*Math.pow(2,-x),a($*4503599627370496>>>0,g,y+c),a((b<<31|x+1023<<20|$*1048576&1048575)>>>0,g,y+d)}}}o.writeDoubleLE=i.bind(null,writeUintLE,0,4),o.writeDoubleBE=i.bind(null,writeUintBE,4,0);function s(a,c,d,f,g){var y=a(f,g+c),b=a(f,g+d),$=(b>>31)*2+1,x=b>>>20&2047,T=4294967296*(b&1048575)+y;return x===2047?T?NaN:$*(1/0):x===0?$*5e-324*T:$*Math.pow(2,x-1075)*(T+4503599627370496)}o.readDoubleLE=s.bind(null,readUintLE,0,4),o.readDoubleBE=s.bind(null,readUintBE,4,0)}(),o}function writeUintLE(o,i,s){i[s]=o&255,i[s+1]=o>>>8&255,i[s+2]=o>>>16&255,i[s+3]=o>>>24}function writeUintBE(o,i,s){i[s]=o>>>24,i[s+1]=o>>>16&255,i[s+2]=o>>>8&255,i[s+3]=o&255}function readUintLE(o,i){return(o[i]|o[i+1]<<8|o[i+2]<<16|o[i+3]<<24)>>>0}function readUintBE(o,i){return(o[i]<<24|o[i+1]<<16|o[i+2]<<8|o[i+3])>>>0}var inquire_1=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(o){}return null}var utf8$5={};(function(o){var i=o;i.length=function(a){for(var c=0,d=0,f=0;f191&&$<224?y[b++]=($&31)<<6|a[c++]&63:$>239&&$<365?($=(($&7)<<18|(a[c++]&63)<<12|(a[c++]&63)<<6|a[c++]&63)-65536,y[b++]=55296+($>>10),y[b++]=56320+($&1023)):y[b++]=($&15)<<12|(a[c++]&63)<<6|a[c++]&63,b>8191&&((g||(g=[])).push(String.fromCharCode.apply(String,y)),b=0);return g?(b&&g.push(String.fromCharCode.apply(String,y.slice(0,b))),g.join("")):String.fromCharCode.apply(String,y.slice(0,b))},i.write=function(a,c,d){for(var f=d,g,y,b=0;b>6|192,c[d++]=g&63|128):(g&64512)===55296&&((y=a.charCodeAt(b+1))&64512)===56320?(g=65536+((g&1023)<<10)+(y&1023),++b,c[d++]=g>>18|240,c[d++]=g>>12&63|128,c[d++]=g>>6&63|128,c[d++]=g&63|128):(c[d++]=g>>12|224,c[d++]=g>>6&63|128,c[d++]=g&63|128);return d-f}})(utf8$5);var pool_1=pool;function pool(o,i,s){var a=s||8192,c=a>>>1,d=null,f=a;return function(y){if(y<1||y>c)return o(y);f+y>a&&(d=o(a),f=0);var b=i.call(d,f,f+=y);return f&7&&(f=(f|7)+1),b}}var longbits,hasRequiredLongbits;function requireLongbits(){if(hasRequiredLongbits)return longbits;hasRequiredLongbits=1,longbits=i;var o=requireMinimal();function i(d,f){this.lo=d>>>0,this.hi=f>>>0}var s=i.zero=new i(0,0);s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1};var a=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(f){if(f===0)return s;var g=f<0;g&&(f=-f);var y=f>>>0,b=(f-y)/4294967296>>>0;return g&&(b=~b>>>0,y=~y>>>0,++y>4294967295&&(y=0,++b>4294967295&&(b=0))),new i(y,b)},i.from=function(f){if(typeof f=="number")return i.fromNumber(f);if(o.isString(f))if(o.Long)f=o.Long.fromString(f);else return i.fromNumber(parseInt(f,10));return f.low||f.high?new i(f.low>>>0,f.high>>>0):s},i.prototype.toNumber=function(f){if(!f&&this.hi>>>31){var g=~this.lo+1>>>0,y=~this.hi>>>0;return g||(y=y+1>>>0),-(g+y*4294967296)}return this.lo+this.hi*4294967296},i.prototype.toLong=function(f){return o.Long?new o.Long(this.lo|0,this.hi|0,!!f):{low:this.lo|0,high:this.hi|0,unsigned:!!f}};var c=String.prototype.charCodeAt;return i.fromHash=function(f){return f===a?s:new i((c.call(f,0)|c.call(f,1)<<8|c.call(f,2)<<16|c.call(f,3)<<24)>>>0,(c.call(f,4)|c.call(f,5)<<8|c.call(f,6)<<16|c.call(f,7)<<24)>>>0)},i.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)},i.prototype.zzEncode=function(){var f=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^f)>>>0,this.lo=(this.lo<<1^f)>>>0,this},i.prototype.zzDecode=function(){var f=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^f)>>>0,this.hi=(this.hi>>>1^f)>>>0,this},i.prototype.length=function(){var f=this.lo,g=(this.lo>>>28|this.hi<<4)>>>0,y=this.hi>>>24;return y===0?g===0?f<16384?f<128?1:2:f<2097152?3:4:g<16384?g<128?5:6:g<2097152?7:8:y<128?9:10},longbits}var hasRequiredMinimal;function requireMinimal(){return hasRequiredMinimal||(hasRequiredMinimal=1,function(o){var i=o;i.asPromise=aspromise,i.base64=base64$1,i.EventEmitter=eventemitter,i.float=float,i.inquire=inquire_1,i.utf8=utf8$5,i.pool=pool_1,i.LongBits=requireLongbits(),i.isNode=!!(typeof commonjsGlobal<"u"&&commonjsGlobal&&commonjsGlobal.process&&commonjsGlobal.process.versions&&commonjsGlobal.process.versions.node),i.global=i.isNode&&commonjsGlobal||typeof window<"u"&&window||typeof self<"u"&&self||commonjsGlobal,i.emptyArray=Object.freeze?Object.freeze([]):[],i.emptyObject=Object.freeze?Object.freeze({}):{},i.isInteger=Number.isInteger||function(d){return typeof d=="number"&&isFinite(d)&&Math.floor(d)===d},i.isString=function(d){return typeof d=="string"||d instanceof String},i.isObject=function(d){return d&&typeof d=="object"},i.isset=i.isSet=function(d,f){var g=d[f];return g!=null&&d.hasOwnProperty(f)?typeof g!="object"||(Array.isArray(g)?g.length:Object.keys(g).length)>0:!1},i.Buffer=function(){try{var c=i.inquire("buffer").Buffer;return c.prototype.utf8Write?c:null}catch{return null}}(),i._Buffer_from=null,i._Buffer_allocUnsafe=null,i.newBuffer=function(d){return typeof d=="number"?i.Buffer?i._Buffer_allocUnsafe(d):new i.Array(d):i.Buffer?i._Buffer_from(d):typeof Uint8Array>"u"?d:new Uint8Array(d)},i.Array=typeof Uint8Array<"u"?Uint8Array:Array,i.Long=i.global.dcodeIO&&i.global.dcodeIO.Long||i.global.Long||i.inquire("long"),i.key2Re=/^true|false|0|1$/,i.key32Re=/^-?(?:0|[1-9][0-9]*)$/,i.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,i.longToHash=function(d){return d?i.LongBits.from(d).toHash():i.LongBits.zeroHash},i.longFromHash=function(d,f){var g=i.LongBits.fromHash(d);return i.Long?i.Long.fromBits(g.lo,g.hi,f):g.toNumber(!!f)};function s(c,d,f){for(var g=Object.keys(d),y=0;y-1;--b)if(f[y[b]]===1&&this[y[b]]!==void 0&&this[y[b]]!==null)return y[b]}},i.oneOfSetter=function(d){return function(f){for(var g=0;g127;)i[s++]=o&127|128,o>>>=7;i[s]=o}function VarintOp(o,i){this.len=o,this.next=void 0,this.val=i}VarintOp.prototype=Object.create(Op.prototype);VarintOp.prototype.fn=writeVarint32;Writer$1.prototype.uint32=function o(i){return this.len+=(this.tail=this.tail.next=new VarintOp((i=i>>>0)<128?1:i<16384?2:i<2097152?3:i<268435456?4:5,i)).len,this};Writer$1.prototype.int32=function o(i){return i<0?this._push(writeVarint64,10,LongBits$1.fromNumber(i)):this.uint32(i)};Writer$1.prototype.sint32=function o(i){return this.uint32((i<<1^i>>31)>>>0)};function writeVarint64(o,i,s){for(;o.hi;)i[s++]=o.lo&127|128,o.lo=(o.lo>>>7|o.hi<<25)>>>0,o.hi>>>=7;for(;o.lo>127;)i[s++]=o.lo&127|128,o.lo=o.lo>>>7;i[s++]=o.lo}Writer$1.prototype.uint64=function o(i){var s=LongBits$1.from(i);return this._push(writeVarint64,s.length(),s)};Writer$1.prototype.int64=Writer$1.prototype.uint64;Writer$1.prototype.sint64=function o(i){var s=LongBits$1.from(i).zzEncode();return this._push(writeVarint64,s.length(),s)};Writer$1.prototype.bool=function o(i){return this._push(writeByte,1,i?1:0)};function writeFixed32(o,i,s){i[s]=o&255,i[s+1]=o>>>8&255,i[s+2]=o>>>16&255,i[s+3]=o>>>24}Writer$1.prototype.fixed32=function o(i){return this._push(writeFixed32,4,i>>>0)};Writer$1.prototype.sfixed32=Writer$1.prototype.fixed32;Writer$1.prototype.fixed64=function o(i){var s=LongBits$1.from(i);return this._push(writeFixed32,4,s.lo)._push(writeFixed32,4,s.hi)};Writer$1.prototype.sfixed64=Writer$1.prototype.fixed64;Writer$1.prototype.float=function o(i){return this._push(util$4.float.writeFloatLE,4,i)};Writer$1.prototype.double=function o(i){return this._push(util$4.float.writeDoubleLE,8,i)};var writeBytes=util$4.Array.prototype.set?function o(i,s,a){s.set(i,a)}:function o(i,s,a){for(var c=0;c>>0;if(!s)return this._push(writeByte,1,0);if(util$4.isString(i)){var a=Writer$1.alloc(s=base64.length(i));base64.decode(i,a,0),i=a}return this.uint32(s)._push(writeBytes,s,i)};Writer$1.prototype.string=function o(i){var s=utf8$4.length(i);return s?this.uint32(s)._push(utf8$4.write,s,i):this._push(writeByte,1,0)};Writer$1.prototype.fork=function o(){return this.states=new State$1(this),this.head=this.tail=new Op(noop$1,0,0),this.len=0,this};Writer$1.prototype.reset=function o(){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 Op(noop$1,0,0),this.len=0),this};Writer$1.prototype.ldelim=function o(){var i=this.head,s=this.tail,a=this.len;return this.reset().uint32(a),a&&(this.tail.next=i.next,this.tail=s,this.len+=a),this};Writer$1.prototype.finish=function o(){for(var i=this.head.next,s=this.constructor.alloc(this.len),a=0;i;)i.fn(i.val,s,a),a+=i.len,i=i.next;return s};Writer$1._configure=function(o){BufferWriter$1=o,Writer$1.create=create$e(),BufferWriter$1._configure()};var writer_buffer=BufferWriter,Writer=writer;(BufferWriter.prototype=Object.create(Writer.prototype)).constructor=BufferWriter;var util$3=requireMinimal();function BufferWriter(){Writer.call(this)}BufferWriter._configure=function(){BufferWriter.alloc=util$3._Buffer_allocUnsafe,BufferWriter.writeBytesBuffer=util$3.Buffer&&util$3.Buffer.prototype instanceof Uint8Array&&util$3.Buffer.prototype.set.name==="set"?function(i,s,a){s.set(i,a)}:function(i,s,a){if(i.copy)i.copy(s,a,0,i.length);else for(var c=0;c>>0;return this.uint32(s),s&&this._push(BufferWriter.writeBytesBuffer,s,i),this};function writeStringBuffer(o,i,s){o.length<40?util$3.utf8.write(o,i,s):i.utf8Write?i.utf8Write(o,s):i.write(o,s)}BufferWriter.prototype.string=function o(i){var s=util$3.Buffer.byteLength(i);return this.uint32(s),s&&this._push(writeStringBuffer,s,i),this};BufferWriter._configure();var reader=Reader$1,util$2=requireMinimal(),BufferReader$1,LongBits=util$2.LongBits,utf8$3=util$2.utf8;function indexOutOfRange(o,i){return RangeError("index out of range: "+o.pos+" + "+(i||1)+" > "+o.len)}function Reader$1(o){this.buf=o,this.pos=0,this.len=o.length}var create_array=typeof Uint8Array<"u"?function o(i){if(i instanceof Uint8Array||Array.isArray(i))return new Reader$1(i);throw Error("illegal buffer")}:function o(i){if(Array.isArray(i))return new Reader$1(i);throw Error("illegal buffer")},create$d=function o(){return util$2.Buffer?function(s){return(Reader$1.create=function(c){return util$2.Buffer.isBuffer(c)?new BufferReader$1(c):create_array(c)})(s)}:create_array};Reader$1.create=create$d();Reader$1.prototype._slice=util$2.Array.prototype.subarray||util$2.Array.prototype.slice;Reader$1.prototype.uint32=function o(){var i=4294967295;return function(){if(i=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(i=(i|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(i=(i|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(i=(i|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(i=(i|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return i;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange(this,10);return i}}();Reader$1.prototype.int32=function o(){return this.uint32()|0};Reader$1.prototype.sint32=function o(){var i=this.uint32();return i>>>1^-(i&1)|0};function readLongVarint(){var o=new LongBits(0,0),i=0;if(this.len-this.pos>4){for(;i<4;++i)if(o.lo=(o.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return o;if(o.lo=(o.lo|(this.buf[this.pos]&127)<<28)>>>0,o.hi=(o.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return o;i=0}else{for(;i<3;++i){if(this.pos>=this.len)throw indexOutOfRange(this);if(o.lo=(o.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return o}return o.lo=(o.lo|(this.buf[this.pos++]&127)<>>0,o}if(this.len-this.pos>4){for(;i<5;++i)if(o.hi=(o.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return o}else for(;i<5;++i){if(this.pos>=this.len)throw indexOutOfRange(this);if(o.hi=(o.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return o}throw Error("invalid varint encoding")}Reader$1.prototype.bool=function o(){return this.uint32()!==0};function readFixed32_end(o,i){return(o[i-4]|o[i-3]<<8|o[i-2]<<16|o[i-1]<<24)>>>0}Reader$1.prototype.fixed32=function o(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)};Reader$1.prototype.sfixed32=function o(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)|0};function readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange(this,8);return new LongBits(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader$1.prototype.float=function o(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var i=util$2.float.readFloatLE(this.buf,this.pos);return this.pos+=4,i};Reader$1.prototype.double=function o(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var i=util$2.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,i};Reader$1.prototype.bytes=function o(){var i=this.uint32(),s=this.pos,a=this.pos+i;if(a>this.len)throw indexOutOfRange(this,i);if(this.pos+=i,Array.isArray(this.buf))return this.buf.slice(s,a);if(s===a){var c=util$2.Buffer;return c?c.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,s,a)};Reader$1.prototype.string=function o(){var i=this.bytes();return utf8$3.read(i,0,i.length)};Reader$1.prototype.skip=function o(i){if(typeof i=="number"){if(this.pos+i>this.len)throw indexOutOfRange(this,i);this.pos+=i}else do if(this.pos>=this.len)throw indexOutOfRange(this);while(this.buf[this.pos++]&128);return this};Reader$1.prototype.skipType=function(o){switch(o){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(o=this.uint32()&7)!==4;)this.skipType(o);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+o+" at offset "+this.pos)}return this};Reader$1._configure=function(o){BufferReader$1=o,Reader$1.create=create$d(),BufferReader$1._configure();var i=util$2.Long?"toLong":"toNumber";util$2.merge(Reader$1.prototype,{int64:function(){return readLongVarint.call(this)[i](!1)},uint64:function(){return readLongVarint.call(this)[i](!0)},sint64:function(){return readLongVarint.call(this).zzDecode()[i](!1)},fixed64:function(){return readFixed64.call(this)[i](!0)},sfixed64:function(){return readFixed64.call(this)[i](!1)}})};var reader_buffer=BufferReader,Reader=reader;(BufferReader.prototype=Object.create(Reader.prototype)).constructor=BufferReader;var util$1=requireMinimal();function BufferReader(o){Reader.call(this,o)}BufferReader._configure=function(){util$1.Buffer&&(BufferReader.prototype._slice=util$1.Buffer.prototype.slice)};BufferReader.prototype.string=function o(){var i=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+i,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+i,this.len))};BufferReader._configure();var rpc={},service=Service,util=requireMinimal();(Service.prototype=Object.create(util.EventEmitter.prototype)).constructor=Service;function Service(o,i,s){if(typeof o!="function")throw TypeError("rpcImpl must be a function");util.EventEmitter.call(this),this.rpcImpl=o,this.requestDelimited=!!i,this.responseDelimited=!!s}Service.prototype.rpcCall=function o(i,s,a,c,d){if(!c)throw TypeError("request must be specified");var f=this;if(!d)return util.asPromise(o,f,i,s,a,c);if(!f.rpcImpl){setTimeout(function(){d(Error("already ended"))},0);return}try{return f.rpcImpl(i,s[f.requestDelimited?"encodeDelimited":"encode"](c).finish(),function(y,b){if(y)return f.emit("error",y,i),d(y);if(b===null){f.end(!0);return}if(!(b instanceof a))try{b=a[f.responseDelimited?"decodeDelimited":"decode"](b)}catch($){return f.emit("error",$,i),d($)}return f.emit("data",b,i),d(null,b)})}catch(g){f.emit("error",g,i),setTimeout(function(){d(g)},0);return}};Service.prototype.end=function o(i){return this.rpcImpl&&(i||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this};(function(o){var i=o;i.Service=service})(rpc);var roots={};(function(o){var i=o;i.build="minimal",i.Writer=writer,i.BufferWriter=writer_buffer,i.Reader=reader,i.BufferReader=reader_buffer,i.util=requireMinimal(),i.rpc=rpc,i.roots=roots,i.configure=s;function s(){i.util._configure(),i.Writer._configure(i.BufferWriter),i.Reader._configure(i.BufferReader)}s()})(indexMinimal);var minimal=indexMinimal;const $protobuf=getDefaultExportFromCjs(minimal),$Reader=$protobuf.Reader,$Writer=$protobuf.Writer,$util=$protobuf.util,$root=$protobuf.roots.unixfs||($protobuf.roots.unixfs={}),Data=$root.Data=(()=>{function o(i){if(this.blocksizes=[],i)for(var s=Object.keys(i),a=0;a>>3){case 1:d.Type=s.int32();break;case 2:d.Data=s.bytes();break;case 3:d.filesize=s.uint64();break;case 4:if(d.blocksizes&&d.blocksizes.length||(d.blocksizes=[]),(f&7)===2)for(var g=s.uint32()+s.pos;s.pos>>0,s.filesize.high>>>0).toNumber(!0))),s.blocksizes){if(!Array.isArray(s.blocksizes))throw TypeError(".Data.blocksizes: array expected");a.blocksizes=[];for(var c=0;c>>0,s.blocksizes[c].high>>>0).toNumber(!0))}if(s.hashType!=null&&($util.Long?(a.hashType=$util.Long.fromValue(s.hashType)).unsigned=!0:typeof s.hashType=="string"?a.hashType=parseInt(s.hashType,10):typeof s.hashType=="number"?a.hashType=s.hashType:typeof s.hashType=="object"&&(a.hashType=new $util.LongBits(s.hashType.low>>>0,s.hashType.high>>>0).toNumber(!0))),s.fanout!=null&&($util.Long?(a.fanout=$util.Long.fromValue(s.fanout)).unsigned=!0:typeof s.fanout=="string"?a.fanout=parseInt(s.fanout,10):typeof s.fanout=="number"?a.fanout=s.fanout:typeof s.fanout=="object"&&(a.fanout=new $util.LongBits(s.fanout.low>>>0,s.fanout.high>>>0).toNumber(!0))),s.mode!=null&&(a.mode=s.mode>>>0),s.mtime!=null){if(typeof s.mtime!="object")throw TypeError(".Data.mtime: object expected");a.mtime=$root.UnixTime.fromObject(s.mtime)}return a},o.toObject=function(s,a){a||(a={});var c={};if((a.arrays||a.defaults)&&(c.blocksizes=[]),a.defaults){if(c.Type=a.enums===String?"Raw":0,a.bytes===String?c.Data="":(c.Data=[],a.bytes!==Array&&(c.Data=$util.newBuffer(c.Data))),$util.Long){var d=new $util.Long(0,0,!0);c.filesize=a.longs===String?d.toString():a.longs===Number?d.toNumber():d}else c.filesize=a.longs===String?"0":0;if($util.Long){var d=new $util.Long(0,0,!0);c.hashType=a.longs===String?d.toString():a.longs===Number?d.toNumber():d}else c.hashType=a.longs===String?"0":0;if($util.Long){var d=new $util.Long(0,0,!0);c.fanout=a.longs===String?d.toString():a.longs===Number?d.toNumber():d}else c.fanout=a.longs===String?"0":0;c.mode=0,c.mtime=null}if(s.Type!=null&&s.hasOwnProperty("Type")&&(c.Type=a.enums===String?$root.Data.DataType[s.Type]:s.Type),s.Data!=null&&s.hasOwnProperty("Data")&&(c.Data=a.bytes===String?$util.base64.encode(s.Data,0,s.Data.length):a.bytes===Array?Array.prototype.slice.call(s.Data):s.Data),s.filesize!=null&&s.hasOwnProperty("filesize")&&(typeof s.filesize=="number"?c.filesize=a.longs===String?String(s.filesize):s.filesize:c.filesize=a.longs===String?$util.Long.prototype.toString.call(s.filesize):a.longs===Number?new $util.LongBits(s.filesize.low>>>0,s.filesize.high>>>0).toNumber(!0):s.filesize),s.blocksizes&&s.blocksizes.length){c.blocksizes=[];for(var f=0;f>>0,s.blocksizes[f].high>>>0).toNumber(!0):s.blocksizes[f]}return s.hashType!=null&&s.hasOwnProperty("hashType")&&(typeof s.hashType=="number"?c.hashType=a.longs===String?String(s.hashType):s.hashType:c.hashType=a.longs===String?$util.Long.prototype.toString.call(s.hashType):a.longs===Number?new $util.LongBits(s.hashType.low>>>0,s.hashType.high>>>0).toNumber(!0):s.hashType),s.fanout!=null&&s.hasOwnProperty("fanout")&&(typeof s.fanout=="number"?c.fanout=a.longs===String?String(s.fanout):s.fanout:c.fanout=a.longs===String?$util.Long.prototype.toString.call(s.fanout):a.longs===Number?new $util.LongBits(s.fanout.low>>>0,s.fanout.high>>>0).toNumber(!0):s.fanout),s.mode!=null&&s.hasOwnProperty("mode")&&(c.mode=s.mode),s.mtime!=null&&s.hasOwnProperty("mtime")&&(c.mtime=$root.UnixTime.toObject(s.mtime,a)),c},o.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},o.DataType=function(){const i={},s=Object.create(i);return s[i[0]="Raw"]=0,s[i[1]="Directory"]=1,s[i[2]="File"]=2,s[i[3]="Metadata"]=3,s[i[4]="Symlink"]=4,s[i[5]="HAMTShard"]=5,s}(),o})();$root.UnixTime=(()=>{function o(i){if(i)for(var s=Object.keys(i),a=0;a>>3){case 1:d.Seconds=s.int64();break;case 2:d.FractionalNanoseconds=s.fixed32();break;default:s.skipType(f&7);break}}if(!d.hasOwnProperty("Seconds"))throw $util.ProtocolError("missing required 'Seconds'",{instance:d});return d},o.fromObject=function(s){if(s instanceof $root.UnixTime)return s;var a=new $root.UnixTime;return s.Seconds!=null&&($util.Long?(a.Seconds=$util.Long.fromValue(s.Seconds)).unsigned=!1:typeof s.Seconds=="string"?a.Seconds=parseInt(s.Seconds,10):typeof s.Seconds=="number"?a.Seconds=s.Seconds:typeof s.Seconds=="object"&&(a.Seconds=new $util.LongBits(s.Seconds.low>>>0,s.Seconds.high>>>0).toNumber())),s.FractionalNanoseconds!=null&&(a.FractionalNanoseconds=s.FractionalNanoseconds>>>0),a},o.toObject=function(s,a){a||(a={});var c={};if(a.defaults){if($util.Long){var d=new $util.Long(0,0,!1);c.Seconds=a.longs===String?d.toString():a.longs===Number?d.toNumber():d}else c.Seconds=a.longs===String?"0":0;c.FractionalNanoseconds=0}return s.Seconds!=null&&s.hasOwnProperty("Seconds")&&(typeof s.Seconds=="number"?c.Seconds=a.longs===String?String(s.Seconds):s.Seconds:c.Seconds=a.longs===String?$util.Long.prototype.toString.call(s.Seconds):a.longs===Number?new $util.LongBits(s.Seconds.low>>>0,s.Seconds.high>>>0).toNumber():s.Seconds),s.FractionalNanoseconds!=null&&s.hasOwnProperty("FractionalNanoseconds")&&(c.FractionalNanoseconds=s.FractionalNanoseconds),c},o.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},o})();$root.Metadata=(()=>{function o(i){if(i)for(var s=Object.keys(i),a=0;a>>3){case 1:d.MimeType=s.string();break;default:s.skipType(f&7);break}}return d},o.fromObject=function(s){if(s instanceof $root.Metadata)return s;var a=new $root.Metadata;return s.MimeType!=null&&(a.MimeType=String(s.MimeType)),a},o.toObject=function(s,a){a||(a={});var c={};return a.defaults&&(c.MimeType=""),s.MimeType!=null&&s.hasOwnProperty("MimeType")&&(c.MimeType=s.MimeType),c},o.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},o})();const NodeType=Data.DataType,EMPTY$3=Object.freeze([]),EMPTY_BUFFER$1=new Uint8Array(0),BLANK$2=Object.freeze({}),DEFAULT_FILE_MODE=parseInt("0644",8),DEFAULT_DIRECTORY_MODE=parseInt("0755",8),code$1=code$2,name$1="UnixFS",encodePB=(o,i)=>(Object(globalThis).debug&&console.log({data:o,links:i}),encode$c(prepare({Data:Data.encode(o).finish(),Links:i}))),createRaw=o=>({type:NodeType.Raw,content:o}),createEmptyFile=o=>createSimpleFile(EMPTY_BUFFER$1,o),createSimpleFile=(o,i)=>({type:NodeType.File,layout:"simple",content:o,metadata:decodeMetadata(i)}),createFileChunk=o=>({type:NodeType.File,layout:"simple",content:o}),createAdvancedFile=(o,i)=>({type:NodeType.File,layout:"advanced",parts:o,metadata:decodeMetadata(i)}),createFileShard=o=>({type:NodeType.File,layout:"advanced",parts:o}),createComplexFile=(o,i,s)=>({type:NodeType.File,layout:"complex",content:o,parts:i,metadata:decodeMetadata(s)}),createFlatDirectory=(o,i)=>({type:NodeType.Directory,metadata:decodeMetadata(i),entries:o}),createShardedDirectory=(o,i,s,a,c=BLANK$2)=>({type:NodeType.HAMTShard,bitfield:i,fanout:readFanout(s),hashType:readInt(a),entries:o,metadata:decodeMetadata(c)}),createDirectoryShard=(o,i,s,a)=>({type:NodeType.HAMTShard,bitfield:i,fanout:readFanout(s),hashType:readInt(a),entries:o}),encodeRaw=o=>encodePB({Type:NodeType.Raw,Data:o.byteLength>0?o:void 0,filesize:o.byteLength,blocksizes:EMPTY$3},[]),encodeFile=(o,i=!1)=>{const s=i?BLANK$2:Object(o).metadata;switch(o.layout){case"simple":return encodeSimpleFile(o.content,s);case"advanced":return encodeAdvancedFile(o.parts,s);case"complex":return encodeComplexFile(o.content,o.parts,s);default:throw new TypeError(`File with unknown layout "${Object(o).layout}" was passed`)}},encodeFileChunk=o=>encodeSimpleFile(o,BLANK$2),encodeFileShard=o=>encodePB({Type:NodeType.File,blocksizes:o.map(contentByteLength),filesize:cumulativeContentByteLength(o)},o.map(encodeLink)),encodeAdvancedFile=(o,i=BLANK$2)=>encodePB({Type:NodeType.File,blocksizes:o.map(contentByteLength),filesize:cumulativeContentByteLength(o),...encodeMetadata(i)},o.map(encodeLink)),encodeLink=o=>({Name:"",Tsize:o.dagByteLength,Hash:o.cid}),encodeSimpleFile=(o,i=BLANK$2)=>encodePB({Type:NodeType.File,Data:o.byteLength>0?o:void 0,filesize:o.byteLength,blocksizes:[],...encodeMetadata(i)},[]),encodeComplexFile=(o,i,s=BLANK$2)=>encodePB({Type:NodeType.File,Data:o,filesize:o.byteLength+cumulativeContentByteLength(i),blocksizes:i.map(contentByteLength)},i.map(encodeLink)),encodeDirectory=o=>encodePB({Type:o.type,...encodeDirectoryMetadata(o.metadata||BLANK$2)},o.entries.map(encodeNamedLink)),encodeHAMTShard=({bitfield:o,fanout:i,hashType:s,entries:a,metadata:c=BLANK$2})=>encodePB({Type:NodeType.HAMTShard,Data:o.byteLength>0?o:void 0,fanout:readFanout(i),hashType:readInt(s),...encodeDirectoryMetadata(c)},a.map(encodeNamedLink)),readFanout=o=>{if(Math.log2(o)%1===0)return o;throw new TypeError(`Expected hamt size to be a power of two instead got ${o}`)},readInt=o=>{if(Number.isInteger(o))return o;throw new TypeError(`Expected an integer value instead got ${o}`)},createSymlink=(o,i=BLANK$2)=>({type:NodeType.Symlink,content:o,metadata:decodeMetadata(i)}),encodeSymlink=(o,i=!1)=>{const s=i?BLANK$2:Object(o).metadata;return encodePB({Type:NodeType.Symlink,Data:o.content,...encodeMetadata(s||BLANK$2)},[])},encode$b=(o,i=!0)=>{switch(o.type){case NodeType.Raw:return encodeRaw(o.content);case NodeType.File:return encodeFile(o);case NodeType.Directory:return encodeDirectory(o);case NodeType.HAMTShard:return encodeHAMTShard(o);case NodeType.Symlink:return encodeSymlink(o);default:throw new Error(`Unknown node type ${Object(o).type}`)}},decode$g=o=>{const i=decode$h(o),s=Data.decode(i.Data),{Type:a,Data:c,mtime:d,mode:f,blocksizes:g,...y}=Data.toObject(s,{defaults:!1,arrays:!0,longs:Number,objects:!1}),b={...f&&{mode:f},...decodeMtime(d)},$=i.Links;switch(s.Type){case NodeType.Raw:return createRaw(c);case NodeType.File:return $.length===0?new SimpleFileView(c,b):c.byteLength===0?new AdvancedFileView(decodeFileLinks(y.blocksizes,$),b):new ComplexFileView(c,decodeFileLinks(y.blocksizes,$),b);case NodeType.Directory:return createFlatDirectory(decodeDirectoryLinks($),b);case NodeType.HAMTShard:return createShardedDirectory(decodeDirectoryLinks($),c||EMPTY_BUFFER$1,y.fanout,y.hashType,b);case NodeType.Symlink:return createSymlink(c,b);default:throw new TypeError(`Unsupported node type ${s.Type}`)}},decodeMtime=o=>o==null?void 0:{mtime:{secs:o.Seconds,nsecs:o.FractionalNanoseconds||0}},decodeFileLinks=(o,i)=>{const s=[],a=o.length;let c=0;for(;co.map(i=>({cid:i.Hash,name:i.Name||"",dagByteLength:i.Tsize||0})),cumulativeContentByteLength=o=>o.reduce((i,s)=>i+s.contentByteLength,0),cumulativeDagByteLength=(o,i)=>i.reduce((s,a)=>s+a.dagByteLength,o.byteLength),contentByteLength=o=>o.contentByteLength,encodeNamedLink=({name:o,dagByteLength:i,cid:s})=>({Name:o,Tsize:i,Hash:s}),encodeDirectoryMetadata=o=>encodeMetadata(o,DEFAULT_DIRECTORY_MODE),encodeMetadata=({mode:o,mtime:i},s=DEFAULT_FILE_MODE)=>({mode:o!=null?encodeMode(o,s):void 0,mtime:i!=null?encodeMTime(i):void 0}),decodeMetadata=o=>o==null?BLANK$2:{...o.mode==null?void 0:{mode:decodeMode(o.mode)},...o.mtime==null?void 0:{mtime:o.mtime}},encodeMTime=o=>o==null?void 0:o.nsecs!==0?{Seconds:o.secs,FractionalNanoseconds:o.nsecs}:{Seconds:o.secs},encodeMode=(o,i)=>{const s=o==null?void 0:decodeMode(o);return s===i||s==null?void 0:s},decodeMode=o=>o&4095|o&4294963200,matchFile=({content:o=EMPTY_BUFFER$1,parts:i=EMPTY$3,metadata:s=BLANK$2,...a})=>i.length===0?new SimpleFileView(o,s):o.byteLength===0?new AdvancedFileView(i,s):new ComplexFileView(o,i,s);class SimpleFileView{constructor(i,s){this.content=i,this.metadata=s,this.layout="simple",this.type=NodeType.File}get filesize(){return this.content.byteLength}encode(){return encodeSimpleFile(this.content,this.metadata)}}class AdvancedFileView{constructor(i,s){this.parts=i,this.metadata=s}get layout(){return"advanced"}get type(){return NodeType.File}get fileSize(){return cumulativeContentByteLength(this.parts)}get blockSizes(){return this.parts.map(contentByteLength)}encode(){return encodeAdvancedFile(this.parts,this.metadata)}}class ComplexFileView{constructor(i,s,a){this.content=i,this.parts=s,this.metadata=a}get layout(){return"complex"}get type(){return NodeType.File}get fileSize(){return this.content.byteLength+cumulativeContentByteLength(this.parts)}get blockSizes(){return this.parts.map(contentByteLength)}encode(){return encodeComplexFile(this.content,this.parts,this.metadata)}}const filesize=o=>{switch(o.type){case NodeType.Raw:case NodeType.Symlink:return o.content.byteLength;case NodeType.File:switch(o.layout){case"simple":return o.content.byteLength;case"advanced":return cumulativeContentByteLength(o.parts);case"complex":return o.content.byteLength+cumulativeContentByteLength(o.parts)}default:return 0}},UnixFS=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_DIRECTORY_MODE,DEFAULT_FILE_MODE,NodeType,code:code$1,createAdvancedFile,createComplexFile,createDirectoryShard,createEmptyFile,createFileChunk,createFileShard,createFlatDirectory,createRaw,createShardedDirectory,createSimpleFile,createSymlink,cumulativeContentByteLength,cumulativeDagByteLength,decode:decode$g,decodeMetadata,encode:encode$b,encodeAdvancedFile,encodeComplexFile,encodeDirectory,encodeDirectoryMetadata,encodeFile,encodeFileChunk,encodeFileShard,encodeHAMTShard,encodeLink,encodeMetadata,encodeMode,encodeRaw,encodeSimpleFile,encodeSymlink,filesize,matchFile,name:name$1},Symbol.toStringTag,{value:"Module"})),effect=function*(o){const i=yield*o;yield*send(i)};function*current(){return yield CURRENT}const suspend=function*(){yield SUSPEND},wait=function*(o){const i=yield*current();if(isAsync(o)){let s=!1,a;if(o.then(c=>{s=!1,a=c,enqueue(i)},c=>{s=!0,a=c,enqueue(i)}),yield*suspend(),s)throw a;return a}else return main(wake(i)),yield*suspend(),o};function*wake(o){enqueue(o)}const isAsync=o=>o!=null&&typeof o.then=="function",send=function*(o){yield o},listen=function*(o){const i=[];for(const s of Object.entries(o)){const[a,c]=s;c!==NONE&&i.push(yield*fork$3(tag(c,a)))}yield*group(i)},effects=o=>o.length>0?batch(o.map(effect)):NONE;function*batch(o){const i=[];for(const s of o)i.push(yield*fork$3(s));yield*group(i)}const tag=(o,i)=>o===NONE?NONE:o instanceof Tagger?new Tagger([...o.tags,i],o.source):new Tagger([i],o);class Tagger{constructor(i,s){this.tags=i,this.source=s,this.controller}[Symbol.iterator](){return this.controller||(this.controller=this.source[Symbol.iterator]()),this}box(i){if(i.done)return i;switch(i.value){case SUSPEND:case CURRENT:return i;default:{const s=i;let{value:a}=s;for(const c of this.tags)a=withTag(c,a);return s.value=a,s}}}next(i){return this.box(this.controller.next(i))}throw(i){return this.box(this.controller.throw(i))}return(i){return this.box(this.controller.return(i))}get[Symbol.toStringTag](){return"TaggedEffect"}}const none=()=>NONE,withTag=(o,i)=>({type:o,[o]:i}),CURRENT=Symbol("current"),SUSPEND=Symbol("suspend");class Group{static of(i){return i.group||MAIN}static enqueue(i,s){i.group=s,s.stack.active.push(i)}constructor(i,s=[],a=new Set,c=new Stack(s,a)){this.driver=i,this.parent=Group.of(i),this.stack=c,this.id=++ID}}class Main{constructor(){this.status=IDLE,this.stack=new Stack,this.id=0}}class Stack{constructor(i=[],s=new Set){this.active=i,this.idle=s}static size({active:i,idle:s}){return i.length+s.size}}const main=o=>enqueue(o[Symbol.iterator]()),enqueue=o=>{let i=Group.of(o);for(i.stack.active.push(o),i.stack.idle.delete(o);i.parent;){const{idle:s,active:a}=i.parent.stack;if(s.has(i.driver))s.delete(i.driver),a.push(i.driver);else break;i=i.parent}if(MAIN.status===IDLE)for(MAIN.status=ACTIVE;;)try{for(const s of step(MAIN));MAIN.status=IDLE;break}catch{MAIN.stack.active.shift()}},resume=o=>enqueue(o),step=function*(o){const{active:i}=o.stack;let s=i[0];for(o.stack.idle.delete(s);s;){let a=INIT;e:for(;!a.done&&s===i[0];){const c=a.value;switch(c){case SUSPEND:o.stack.idle.add(s);break e;case CURRENT:a=s.next(s);break;default:a=s.next(yield c);break}}i.shift(),s=i[0],o.stack.idle.delete(s)}},fork$3=(o,i)=>new Fork(o,i),exit=(o,i)=>conclude(o,{ok:!0,value:i}),abort=(o,i)=>conclude(o,{ok:!1,error:i});function*conclude(o,i){try{const s=o,a=i.ok?s.return(i.value):s.throw(i.error);if(!a.done)if(a.value===SUSPEND){const{idle:c}=Group.of(s).stack;c.add(s)}else enqueue(s)}catch{}}function*group(o){if(o.length===0)return;const i=yield*current(),s=new Group(i);let a=null;for(const c of o){const{result:d}=c;if(d){!d.ok&&!a&&(a=d);continue}move(c,s)}try{if(a)throw a.error;for(;yield*step(s),Stack.size(s.stack)>0;)yield*suspend()}catch(c){for(const d of s.stack.active)yield*abort(d,c);for(const d of s.stack.idle)yield*abort(d,c),enqueue(d);throw c}}const move=(o,i)=>{const s=Group.of(o);if(s!==i){const{active:a,idle:c}=s.stack,d=i.stack;if(o.group=i,c.has(o))c.delete(o),d.idle.add(o);else{const f=a.indexOf(o);f>=0&&(a.splice(f,1),d.active.push(o))}}};function*join(o){o.status===IDLE&&(yield*o),o.result||(yield*group([o]));const i=o.result;if(i.ok)return i.value;throw i.error}class Future{constructor(i){this.handler=i,this.result}get promise(){const{result:i}=this,s=i==null?new Promise((a,c)=>{this.handler.onsuccess=a,this.handler.onfailure=c}):i.ok?Promise.resolve(i.value):Promise.reject(i.error);return Object.defineProperty(this,"promise",{value:s}),s}then(i,s){return this.activate().promise.then(i,s)}catch(i){return this.activate().promise.catch(i)}finally(i){return this.activate().promise.finally(i)}activate(){return this}}class Fork extends Future{constructor(i,s=BLANK$1,a={},c=INIT){super(a),this.id=++ID,this.name=s.name||"",this.task=i,this.state=c,this.status=IDLE,this.result,this.handler=a,this.controller}*resume(){resume(this)}join(){return join(this)}abort(i){return abort(this,i)}exit(i){return exit(this,i)}get[Symbol.toStringTag](){return"Fork"}*[Symbol.iterator](){return this.activate()}activate(){return this.controller=this.task[Symbol.iterator](),this.status=ACTIVE,enqueue(this),this}panic(i){this.result={ok:!1,error:i},this.status=FINISHED;const{handler:s}=this;throw s.onfailure&&s.onfailure(i),i}step(i){if(this.state=i,i.done){this.result={ok:!0,value:i.value},this.status=FINISHED;const{handler:s}=this;s.onsuccess&&s.onsuccess(i.value)}return i}next(i){try{return this.step(this.controller.next(i))}catch(s){return this.panic(s)}}return(i){try{return this.step(this.controller.return(i))}catch(s){return this.panic(s)}}throw(i){try{return this.step(this.controller.throw(i))}catch(s){return this.panic(s)}}}const loop=function*(o,i){const s=yield*current(),a=new Group(s);for(Group.enqueue(o[Symbol.iterator](),a);;){for(const c of step(a))Group.enqueue(i(c)[Symbol.iterator](),a);if(Stack.size(a.stack)>0)yield*suspend();else break}};let ID=0;const IDLE="idle",ACTIVE="active",FINISHED="finished",INIT={done:!1,value:CURRENT},BLANK$1={},NONE=function*o(){}(),MAIN=new Main;function Indexed(){}Object.defineProperties(Indexed,{prototype:{value:new Proxy(Object.prototype,{get(o,i,s){return typeof i=="symbol"?Reflect.get(o,i,s):s.get(i)}})}});const empty$3=()=>new BufferView,slice=(o,i=0,s=o.byteLength)=>{const a=[],c=i<0?o.byteLength-i:i,d=s<0?o.byteLength-s:s;if(c===0&&d>=o.byteLength)return o;if(c>d||c>o.byteLength||d<=0)return empty$3();let f=0,g=0;for(const y of o.segments){const b=g+y.byteLength;if(f===0){if(d<=b){const $=y.subarray(c-g,d-g);a.push($),f=$.byteLength;break}else if(ci.byteLength>0?(o.segments.push(i),new BufferView(o.segments,o.byteOffset,o.byteLength+i.byteLength)):o,get$6=(o,i)=>{if(i{let a=s;for(const c of o.segments)i.set(c,a),a+=c.byteLength;return i};function*iterate$1(o){for(const i of o.segments)yield*i}class BufferView extends Indexed{constructor(i=[],s=0,a=0){super(),this.segments=i,this.byteLength=a,this.length=a,this.byteOffset=s}[Symbol.iterator](){return iterate$1(this)}slice(i,s){return slice(this,i,s)}subarray(i,s){return slice(this,i,s)}push(i){return push(this,i)}get(i){return get$6(this,i)}copyTo(i,s){return copyTo(this,i,s)}}const panic=o=>{throw new Error(o)},unreachable=(o,i,...s)=>panic(String.raw(o,JSON.stringify(i),...s)),EMPTY_BUFFER=new Uint8Array(0),EMPTY$2=[],open$1=o=>({config:o,buffer:empty$3()}),write$3=(o,i)=>i.byteLength>0?split(o.config,o.buffer.push(i),!1):{...o,chunks:EMPTY$2},close$6=o=>split(o.config,o.buffer,!0),split=(o,i,s)=>{const a=o.chunker,c=[];let d=0;for(const f of a.cut(a.context,i,s))if(f>0){const g=i.subarray(d,d+f);c.push(g),d+=f}return{config:o,chunks:c,buffer:i.subarray(d)}},mutable=()=>({mutable:!0,needs:{},nodes:{},links:{},linked:EMPTY$1}),addNodes=(o,i)=>{let s=patch(i,{});for(const a of o){const{ready:c,has:d,wants:f}=collect(a.children,s.links);f.length===0?s=patch(s,{links:assign(void 0,d),linked:[{id:a.id,links:c}]}):s=patch(s,{needs:assign(a.id,f),nodes:{[a.id]:{children:a.children,count:f.length}}})}return s},addLink=(o,i,s)=>{const a=s.needs[o],c=s.nodes[a];if(c!=null)if(c.count===1){const{ready:d,has:f}=collect(c.children,{...s.links,[o]:i});return patch(s,{needs:{[o]:void 0},links:assign(void 0,f),nodes:{[a]:void 0},linked:[{id:a,links:d}]})}else return patch(s,{needs:{[o]:void 0},links:{[o]:i},nodes:{[a]:{...c,count:c.count-1}}});else return patch(s,{links:{[o]:i}})},patch=(o,{needs:i,nodes:s,links:a,linked:c})=>{const d=o.mutable?o:{...o},f=o.mutable?BLANK:void 0;return i&&(d.needs=patchDict(o.needs,i,f)),s&&(d.nodes=patchDict(o.nodes,s,f)),a&&(d.links=patchDict(o.links,a,f)),d.linked=c?append(o.linked||EMPTY$1,c,EMPTY$1):o.linked||[],d},assign=(o,i)=>{const s={};for(const a of i)s[a]=o;return s},patchDict=(o,i,s=o)=>{const a=o===s?{...o}:o;for(const c of Object.entries(i)){const[d,f]=c;f==null?delete a[d]:a[d]=f}return a},append=(o,i,s=o)=>{if(o===s)return[...o,...i];for(const a of i)o.push(a);return o},collect=(o,i)=>{const s=[],a=[],c=[];for(const d of o){const f=i[d];f?(s.push(d),c.push(f)):a.push(d)}return{has:s,wants:a,ready:c}},EMPTY$1=Object.freeze([]),BLANK=Object.freeze({}),update=(o,i)=>{switch(o.type){case"write":return write$2(i,o.bytes);case"link":return link(i,o.link);case"block":return{state:i,effect:none()};case"close":return close$5(i);case"end":return{state:i,effect:none()};default:return unreachable`File Writer got unknown message ${o}`}},init=(o,i,s)=>({status:"open",metadata:i,config:s,writer:o,chunker:open$1({chunker:s.chunker}),layout:s.fileLayout.open(),nodeQueue:mutable()}),write$2=(o,i)=>{if(o.status==="open"){const{chunks:s,...a}=write$3(o.chunker,i),{nodes:c,leaves:d,layout:f}=o.config.fileLayout.write(o.layout,s),{linked:g,...y}=addNodes(c,o.nodeQueue),b=[...encodeLeaves(d,o.config),...encodeBranches(g,o.config)];return{state:{...o,chunker:a,layout:f,nodeQueue:y},effect:listen({link:effects(b)})}}else return panic("Unable to perform write on closed file")},link=(o,{id:i,link:s,block:a})=>{let{linked:c,...d}=addLink(i,s,o.nodeQueue);const f=encodeBranches(c,o.config),g=o.status==="closed"&&i===o.rootID?{...o,status:"linked",link:s,nodeQueue:d}:{...o,nodeQueue:d},y=o.status==="closed"&&i===o.rootID&&o.end?o.end.resume():none();return{state:g,effect:listen({link:effects(f),block:writeBlock(o.writer,a),end:y})}},close$5=o=>{if(o.status==="open"){const{chunks:i}=close$6(o.chunker),{layout:s,...a}=o.config.fileLayout.write(o.layout,i),{root:c,...d}=o.config.fileLayout.close(s,o.metadata),[f,g]=isLeafNode(c)?[[...a.nodes,...d.nodes],[...a.leaves,...d.leaves,c]]:[[...a.nodes,...d.nodes,c],[...a.leaves,...d.leaves]],{linked:y,...b}=addNodes(f,o.nodeQueue),$=[...encodeLeaves(g,o.config),...encodeBranches(y,o.config)],x=fork$3(suspend());return{state:{...o,chunker:null,layout:null,rootID:c.id,status:"closed",end:x,nodeQueue:b},effect:listen({link:effects($),end:join(x)})}}else return{state:o,effect:none()}},encodeLeaves=(o,i)=>o.map(s=>encodeLeaf(i,s,i.fileChunkEncoder)),encodeLeaf=function*({hasher:o,linker:i},{id:s,content:a},c){const d=c.encode(a?asUint8Array$1(a):EMPTY_BUFFER),f=yield*wait(o.digest(d)),g=i.createLink(c.code,f),y={cid:g,bytes:d},b={cid:g,contentByteLength:a?a.byteLength:0,dagByteLength:d.byteLength};return{id:s,block:y,link:b}},encodeBranches=(o,i)=>o.map(s=>encodeBranch(i,s)),encodeBranch=function*(o,{id:i,links:s},a){const c=o.fileEncoder.encode({type:NodeType.File,layout:"advanced",parts:s,metadata:a}),d=yield*wait(Promise.resolve(o.hasher.digest(c))),f=o.linker.createLink(o.fileEncoder.code,d),g={bytes:c,cid:f},y={cid:f,contentByteLength:cumulativeContentByteLength(s),dagByteLength:cumulativeDagByteLength(c,s)};return{id:i,block:g,link:y}},writeBlock=function*(o,i){(o.desiredSize||0)<=0&&(yield*wait(o.ready)),o.write(i)},asUint8Array$1=o=>o instanceof Uint8Array?o:o.copyTo(new Uint8Array(o.byteLength),0),isLeafNode=o=>o.children==null,name="fixed",context={maxChunkSize:262144},type="Stateless",withMaxChunkSize=o=>({type:"Stateless",context:{maxChunkSize:o},name,cut}),cut=({maxChunkSize:o},{byteLength:i},s)=>{const a=i/o|0,c=new Array(a).fill(o),d=s?i-a*o:0;return d>0&&c.push(d),c},FixedSize=Object.freeze(Object.defineProperty({__proto__:null,context,cut,name,type,withMaxChunkSize},Symbol.toStringTag,{value:"Module"})),equals$6=(o,i)=>{if(o===i)return!0;if(o.byteLength!==i.byteLength)return!1;for(let s=0;s{if(o instanceof Uint8Array&&o.constructor.name==="Uint8Array")return o;if(o instanceof ArrayBuffer)return new Uint8Array(o);if(ArrayBuffer.isView(o))return new Uint8Array(o.buffer,o.byteOffset,o.byteLength);throw new Error("Unknown type, must be binary type")};var encode_1$3=encode$a,MSB$4=128,REST$4=127,MSBALL$4=~REST$4,INT$4=Math.pow(2,31);function encode$a(o,i,s){i=i||[],s=s||0;for(var a=s;o>=INT$4;)i[s++]=o&255|MSB$4,o/=128;for(;o&MSBALL$4;)i[s++]=o&255|MSB$4,o>>>=7;return i[s]=o|0,encode$a.bytes=s-a+1,i}var decode$f=read$4,MSB$1$4=128,REST$1$4=127;function read$4(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$4.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$4)<=MSB$1$4);return read$4.bytes=d-a,s}var N1$3=Math.pow(2,7),N2$3=Math.pow(2,14),N3$3=Math.pow(2,21),N4$3=Math.pow(2,28),N5$3=Math.pow(2,35),N6$3=Math.pow(2,42),N7$3=Math.pow(2,49),N8$3=Math.pow(2,56),N9$3=Math.pow(2,63),length$3=function(o){return o[_brrp_varint$3.decode(o,i),_brrp_varint$3.decode.bytes],encodeTo$3=(o,i,s=0)=>(_brrp_varint$3.encode(o,i,s),i),encodingLength$3=o=>_brrp_varint$3.encodingLength(o),create$c=(o,i)=>{const s=i.byteLength,a=encodingLength$3(o),c=a+encodingLength$3(s),d=new Uint8Array(c+s);return encodeTo$3(o,d,0),encodeTo$3(s,d,a),d.set(i,c),new Digest$3(o,s,i,d)},decode$d=o=>{const i=coerce$3(o),[s,a]=decode$e(i),[c,d]=decode$e(i.subarray(a)),f=i.subarray(a+d);if(f.byteLength!==c)throw new Error("Incorrect length");return new Digest$3(s,c,f,i)},equals$5=(o,i)=>{if(o===i)return!0;{const s=i;return o.code===s.code&&o.size===s.size&&s.bytes instanceof Uint8Array&&equals$6(o.bytes,s.bytes)}};let Digest$3=class{constructor(i,s,a,c){this.code=i,this.size=s,this.digest=a,this.bytes=c}};const from$a=({name:o,code:i,encode:s})=>new Hasher$2(o,i,s);let Hasher$2=class{constructor(i,s,a){this.name=i,this.code=s,this.encode=a}digest(i){if(i instanceof Uint8Array){const s=this.encode(i);return s instanceof Uint8Array?create$c(this.code,s):s.then(a=>create$c(this.code,a))}else throw Error("Unknown type, must be binary type")}};const sha$1=o=>async i=>new Uint8Array(await crypto.subtle.digest(o,i)),sha256$1=from$a({name:"sha2-256",code:18,encode:sha$1("SHA-256")});function base$3(o,i){if(o.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src$3=base$3,_brrp__multiformats_scope_baseX$3=src$3;let Encoder$3=class{constructor(i,s,a){this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}},Decoder$3=class{constructor(i,s,a){if(this.name=i,this.prefix=s,s.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s.codePointAt(0),this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or$5(this,i)}},ComposedDecoder$3=class{constructor(i){this.decoders=i}or(i){return or$5(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const or$5=(o,i)=>new ComposedDecoder$3({...o.decoders||{[o.prefix]:o},...i.decoders||{[i.prefix]:i}});let Codec$3=class{constructor(i,s,a,c){this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder$3(i,s,a),this.decoder=new Decoder$3(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}};const from$9=({name:o,prefix:i,encode:s,decode:a})=>new Codec$3(o,i,s,a),baseX$3=({prefix:o,name:i,alphabet:s})=>{const{encode:a,decode:c}=_brrp__multiformats_scope_baseX$3(s,i);return from$9({prefix:o,name:i,encode:a,decode:d=>coerce$3(c(d))})},decode$c=(o,i,s,a)=>{const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f},encode$9=(o,i,s)=>{const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f&&(d+=i[c&g<from$9({prefix:i,name:o,encode(c){return encode$9(c,a,s)},decode(c){return decode$c(c,a,s,o)}}),base58btc$2=baseX$3({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});baseX$3({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});const base32$2=rfc4648$3({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5});rfc4648$3({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5});rfc4648$3({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5});rfc4648$3({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5});rfc4648$3({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5});rfc4648$3({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5});rfc4648$3({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5});rfc4648$3({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5});rfc4648$3({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});const format$2=(o,i)=>{const{bytes:s,version:a}=o;switch(a){case 0:return toStringV0$2(s,baseCache$2(o),i||base58btc$2.encoder);default:return toStringV1$2(s,baseCache$2(o),i||base32$2.encoder)}},cache$3=new WeakMap,baseCache$2=o=>{const i=cache$3.get(o);if(i==null){const s=new Map;return cache$3.set(o,s),s}return i};let CID$2=class be{constructor(i,s,a,c){this.code=s,this.version=i,this.multihash=a,this.bytes=c,this["/"]=c}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:{const{code:i,multihash:s}=this;if(i!==DAG_PB_CODE$3)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(s.code!==SHA_256_CODE$2)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return be.createV0(s)}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:{const{code:i,digest:s}=this.multihash,a=create$c(i,s);return be.createV1(this.code,a)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(i){return be.equals(this,i)}static equals(i,s){const a=s;return a&&i.code===a.code&&i.version===a.version&&equals$5(i.multihash,a.multihash)}toString(i){return format$2(this,i)}toJSON(){return{"/":format$2(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(i){if(i==null)return null;const s=i;if(s instanceof be)return s;if(s["/"]!=null&&s["/"]===s.bytes||s.asCID===s){const{version:a,code:c,multihash:d,bytes:f}=s;return new be(a,c,d,f||encodeCID$2(a,c,d.bytes))}else if(s[cidSymbol$2]===!0){const{version:a,multihash:c,code:d}=s,f=decode$d(c);return be.create(a,d,f)}else return null}static create(i,s,a){if(typeof s!="number")throw new Error("String codecs are no longer supported");if(!(a.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(i){case 0:{if(s!==DAG_PB_CODE$3)throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE$3}) block encoding`);return new be(i,s,a,a.bytes)}case 1:{const c=encodeCID$2(i,s,a.bytes);return new be(i,s,a,c)}default:throw new Error("Invalid version")}}static createV0(i){return be.create(0,DAG_PB_CODE$3,i)}static createV1(i,s){return be.create(1,i,s)}static decode(i){const[s,a]=be.decodeFirst(i);if(a.length)throw new Error("Incorrect length");return s}static decodeFirst(i){const s=be.inspectBytes(i),a=s.size-s.multihashSize,c=coerce$3(i.subarray(a,a+s.multihashSize));if(c.byteLength!==s.multihashSize)throw new Error("Incorrect length");const d=c.subarray(s.multihashSize-s.digestSize),f=new Digest$3(s.multihashCode,s.digestSize,d,c);return[s.version===0?be.createV0(f):be.createV1(s.codec,f),i.subarray(s.size)]}static inspectBytes(i){let s=0;const a=()=>{const[x,T]=decode$e(i.subarray(s));return s+=T,x};let c=a(),d=DAG_PB_CODE$3;if(c===18?(c=0,s=0):d=a(),c!==0&&c!==1)throw new RangeError(`Invalid CID version ${c}`);const f=s,g=a(),y=a(),b=s+y,$=b-f;return{version:c,codec:d,multihashCode:g,digestSize:y,multihashSize:$,size:b}}static parse(i,s){const[a,c]=parseCIDtoBytes$2(i,s),d=be.decode(c);if(d.version===0&&i[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache$2(d).set(a,i),d}};const parseCIDtoBytes$2=(o,i)=>{switch(o[0]){case"Q":{const s=i||base58btc$2;return[base58btc$2.prefix,s.decode(`${base58btc$2.prefix}${o}`)]}case base58btc$2.prefix:{const s=i||base58btc$2;return[base58btc$2.prefix,s.decode(o)]}case base32$2.prefix:{const s=i||base32$2;return[base32$2.prefix,s.decode(o)]}default:{if(i==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[o[0],i.decode(o)]}}},toStringV0$2=(o,i,s)=>{const{prefix:a}=s;if(a!==base58btc$2.prefix)throw Error(`Cannot string encode V0 in ${s.name} encoding`);const c=i.get(a);if(c==null){const d=s.encode(o).slice(1);return i.set(a,d),d}else return c},toStringV1$2=(o,i,s)=>{const{prefix:a}=s,c=i.get(a);if(c==null){const d=s.encode(o);return i.set(a,d),d}else return c},DAG_PB_CODE$3=112,SHA_256_CODE$2=18,encodeCID$2=(o,i,s)=>{const a=encodingLength$3(o),c=a+encodingLength$3(i),d=new Uint8Array(c+s.byteLength);return encodeTo$3(o,d,0),encodeTo$3(i,d,a),d.set(s,c),d},cidSymbol$2=Symbol.for("@ipld/js-cid/CID");class Node{constructor(i,s,a){this.id=i,this.children=s,this.metadata=a}}const withWidth=o=>({open:()=>open({width:o}),write:write$1,close:close$4}),defaults$3={width:174},open=({width:o}=defaults$3)=>({width:o,head:null,leafIndex:[],nodeIndex:[],lastID:0}),write$1=(o,i)=>{if(i.length===0)return{layout:o,nodes:EMPTY,leaves:EMPTY};{let{lastID:s}=o;const[a,c]=o.head?[null,(i.unshift(o.head),i)]:i.length===1&&o.leafIndex.length===0?[i[0],EMPTY]:[null,i];if(c.length===0)return{layout:{...o,head:a},nodes:EMPTY,leaves:EMPTY};{const d=[...o.leafIndex],f=[];for(const g of c){const y={id:++s,content:g};f.push(y),d.push(y.id)}return d.length>o.width?flush({...o,leafIndex:d,head:a,lastID:s},f):{layout:{...o,head:a,leafIndex:d,lastID:s},leaves:f,nodes:EMPTY}}}},flush=(o,i=EMPTY,s=[],a=!1)=>{let{lastID:c}=o;const d=o.nodeIndex.map(b=>[...b]),f=[...o.leafIndex],{width:g}=o;for(;f.length>g||f.length>0&&a;){grow(d,1);const b=new Node(++c,f.splice(0,g));d[0].push(b.id),s.push(b)}let y=0;for(;yg||b.length>0&&a&&y{const s=o;if(o.head)return{root:{id:1,content:o.head,metadata:i},leaves:EMPTY,nodes:EMPTY};if(o.leafIndex.length===0)return{root:{id:1,metadata:i},leaves:EMPTY,nodes:EMPTY};{const{nodes:a,layout:c}=flush(s,EMPTY,[],!0),{nodeIndex:d}=c,f=d.length-1,g=d[f];if(g.length===1){const y=a[a.length-1];return a.length=a.length-1,{root:y,nodes:a,leaves:EMPTY}}else return{root:new Node(c.lastID+1,g,i),nodes:a,leaves:EMPTY}}},grow=(o,i)=>{for(;o.length({chunker:FixedSize,fileChunkEncoder:UnixFSLeaf,smallFileEncoder:UnixFSLeaf,fileEncoder:UnixFS,fileLayout:withWidth(174),hasher:sha256$1,linker:{createLink:CID$2.createV1}}),configure$4=o=>({...defaults$2(),...o}),UnixFSLeaf={code:code$1,name:name$1,encode:encodeFileChunk},create$b=({writer:o,metadata:i={},settings:s=defaults$2()})=>new FileWriterView(init(o,i,configure$4(s))),write=async(o,i)=>(await perform(o,send({type:"write",bytes:i})),o),close$3=async(o,{releaseLock:i=!1,closeWriter:s=!1}={})=>{await perform(o,send({type:"close"}));const{state:a}=o;if(a.status==="linked")return s?await o.state.writer.close():i&&o.state.writer.releaseLock(),a.link;panic(`Expected writer to be in 'linked' state after close, but it is in "${a.status}" instead`)},perform=(o,i)=>fork$3(loop(i,s=>{const{state:a,effect:c}=update(s,o.state);return o.state=a,c}));class FileWriterView{constructor(i){this.state=i}get writer(){return this.state.writer}get settings(){return this.state.config}write(i){return write(this,i)}close(i){return close$3(this,i)}}const defaults$1=defaults$2,create$a=({writer:o,settings:i=defaults$1(),metadata:s={}})=>new DirectoryWriter({writer:o,metadata:s,settings:i,entries:new Map,closed:!1}),set$4=(o,i,s,{overwrite:a=!1}={})=>{const c=asWritable$1(o.state);if(i.includes("/"))throw new Error(`Directory entry name "${i}" contains forbidden "/" character`);if(!a&&c.entries.has(i))throw new Error(`Directory already contains entry with name "${i}"`);return c.entries.set(i,s),o},remove$1=(o,i)=>(asWritable$1(o.state).entries.delete(i),o),asWritable$1=o=>{if(o.closed)throw new Error("Can not change written directory, but you can .fork() and make changes to it");return o},close$2=async(o,{closeWriter:i=!1,releaseLock:s=!1}={})=>{const{writer:a,settings:c,metadata:d}=asWritable$1(o.state);o.state.closed=!0;const f=[...links$1(o)],g=createFlatDirectory(f,d),y=encodeDirectory(g),b=await c.hasher.digest(y),$=c.linker.createLink(code$1,b);return(a.desiredSize||0)<=0&&await a.ready,a.write({cid:$,bytes:y}),i?await a.close():s&&a.releaseLock(),{cid:$,dagByteLength:cumulativeDagByteLength(y,f)}},links$1=function*({state:o}){for(const[i,{dagByteLength:s,cid:a}]of o.entries)yield{name:i,dagByteLength:s,cid:a}},fork$2=({state:o},{writer:i=o.writer,metadata:s=o.metadata,settings:a=o.settings}={})=>new DirectoryWriter({writer:i,metadata:s,settings:a,entries:new Map(o.entries.entries()),closed:!1});class DirectoryWriter{constructor(i){this.state=i}get writer(){return this.state.writer}get settings(){return this.state.settings}links(){return links$1(this)}set(i,s,a){return set$4(this,i,s,a)}remove(i){return remove$1(this,i)}fork(i){return fork$2(this,i)}close(i){return close$2(this,i)}entries(){return this.state.entries.entries()}has(i){return this.state.entries.has(i)}get size(){return this.state.entries.size}}const api=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),empty$2=(o=32)=>{if(o!==32)throw new Error(`Uint32 BitField does not support size: ${o}`);return 0},from$8=(o,i)=>{let s=empty$2(i);for(const a of o)s=set$3(s,a);return s},size$1=o=>32,mask=(o,i)=>o>>>i&31,offset=(o,i)=>1<bitCount(o&offset(i,0)-1),set$3=(o,i)=>o|1<o&(255^1<(o>>i&1)!==0,bitCount=o=>{const i=o-(o>>1&1431655765),s=(i&858993459)+(i>>2&858993459);return(s+(s>>4)&252645135)*16843009>>24},and$1=(o,i)=>o&i,or$4=(o,i)=>o|i,toBytes$1=o=>Uint8Array.of(o>>24&255,o>>16&255,o>>8&255,o&255),fromBytes$2=o=>{if(o.length!==4)throw new Error(`Expected 4 bytes instead got ${o.length}`);return(o[0]<<24)+(o[1]<<16)+(o[2]<<8)+o[3]},Uint32BitField=Object.freeze(Object.defineProperty({__proto__:null,API:api,and:and$1,bitCount,empty:empty$2,from:from$8,fromBytes:fromBytes$2,get:get$5,or:or$4,popcount:popcount$1,set:set$3,size:size$1,toBytes:toBytes$1,unset:unset$1},Symbol.toStringTag,{value:"Module"}));var murmurHash3js={exports:{}};(function(o,i){(function(s,a){var c={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function d(S){if(!Array.isArray(S)&&!ArrayBuffer.isView(S))return!1;for(var _=0;_255)return!1;return!0}function f(S,_){return(S&65535)*_+(((S>>>16)*_&65535)<<16)}function g(S,_){return S<<_|S>>>32-_}function y(S){return S^=S>>>16,S=f(S,2246822507),S^=S>>>13,S=f(S,3266489909),S^=S>>>16,S}function b(S,_){S=[S[0]>>>16,S[0]&65535,S[1]>>>16,S[1]&65535],_=[_[0]>>>16,_[0]&65535,_[1]>>>16,_[1]&65535];var C=[0,0,0,0];return C[3]+=S[3]+_[3],C[2]+=C[3]>>>16,C[3]&=65535,C[2]+=S[2]+_[2],C[1]+=C[2]>>>16,C[2]&=65535,C[1]+=S[1]+_[1],C[0]+=C[1]>>>16,C[1]&=65535,C[0]+=S[0]+_[0],C[0]&=65535,[C[0]<<16|C[1],C[2]<<16|C[3]]}function $(S,_){S=[S[0]>>>16,S[0]&65535,S[1]>>>16,S[1]&65535],_=[_[0]>>>16,_[0]&65535,_[1]>>>16,_[1]&65535];var C=[0,0,0,0];return C[3]+=S[3]*_[3],C[2]+=C[3]>>>16,C[3]&=65535,C[2]+=S[2]*_[3],C[1]+=C[2]>>>16,C[2]&=65535,C[2]+=S[3]*_[2],C[1]+=C[2]>>>16,C[2]&=65535,C[1]+=S[1]*_[3],C[0]+=C[1]>>>16,C[1]&=65535,C[1]+=S[2]*_[2],C[0]+=C[1]>>>16,C[1]&=65535,C[1]+=S[3]*_[1],C[0]+=C[1]>>>16,C[1]&=65535,C[0]+=S[0]*_[3]+S[1]*_[2]+S[2]*_[1]+S[3]*_[0],C[0]&=65535,[C[0]<<16|C[1],C[2]<<16|C[3]]}function x(S,_){return _%=64,_===32?[S[1],S[0]]:_<32?[S[0]<<_|S[1]>>>32-_,S[1]<<_|S[0]>>>32-_]:(_-=32,[S[1]<<_|S[0]>>>32-_,S[0]<<_|S[1]>>>32-_])}function T(S,_){return _%=64,_===0?S:_<32?[S[0]<<_|S[1]>>>32-_,S[1]<<_]:[S[1]<<_-32,0]}function A(S,_){return[S[0]^_[0],S[1]^_[1]]}function E(S){return S=A(S,[0,S[0]>>>1]),S=$(S,[4283543511,3981806797]),S=A(S,[0,S[0]>>>1]),S=$(S,[3301882366,444984403]),S=A(S,[0,S[0]>>>1]),S}c.x86.hash32=function(S,_){if(c.inputValidation&&!d(S))return a;_=_||0;for(var C=S.length%4,B=S.length-C,D=_,I=0,O=3432918353,N=461845907,L=0;L>>0},c.x86.hash128=function(S,_){if(c.inputValidation&&!d(S))return a;_=_||0;for(var C=S.length%16,B=S.length-C,D=_,I=_,O=_,N=_,L=0,R=0,z=0,K=0,G=597399067,W=2869860233,J=951274213,ie=2716044179,H=0;H>>0).toString(16)).slice(-8)+("00000000"+(I>>>0).toString(16)).slice(-8)+("00000000"+(O>>>0).toString(16)).slice(-8)+("00000000"+(N>>>0).toString(16)).slice(-8)},c.x64.hash128=function(S,_){if(c.inputValidation&&!d(S))return a;_=_||0;for(var C=S.length%16,B=S.length-C,D=[0,_],I=[0,_],O=[0,0],N=[0,0],L=[2277735313,289559509],R=[1291169091,658871167],z=0;z>>0).toString(16)).slice(-8)+("00000000"+(D[1]>>>0).toString(16)).slice(-8)+("00000000"+(I[0]>>>0).toString(16)).slice(-8)+("00000000"+(I[1]>>>0).toString(16)).slice(-8)},o.exports&&(i=o.exports=c),i.murmurHash3=c})()})(murmurHash3js,murmurHash3js.exports);var murmurHash3jsExports=murmurHash3js.exports,murmurhash3jsRevisited=murmurHash3jsExports;const mur=getDefaultExportFromCjs(murmurhash3jsRevisited),utf8$2=new TextEncoder,hash32=mur.x64.hash126,configure$3=({bitWidth:o=5,hash:i=hash32})=>{if(o>4*8)throw new RangeError(`Can not use bitWidth ${o} which exceeds the hashSize 4`);const a=4294967295>>>32-o;return{at:(f,g)=>f>>>g*o&a,from:f=>i(utf8$2.encode(f)),size:Math.ceil(4*8/o)}};class BitmapIndexedNode{constructor(i,s,a,c,d){this.edit=i,this.config=d,this.datamap=s,this.nodemap=a,this.children=c}get nodeArity(){return this.config.BitField.popcount(this.nodemap)}get dataArity(){return this.config.BitField.popcount(this.datamap)}empty(){return create$9(this.config)}lookup(i,s,a,c){return lookup(this,i,s,a,c)}associate(i,s,a,c,d,f){return associate(this,i,s,a,c,d,f)}dissociate(i,s,a,c,d){return dissociate(this,i,s,a,c,d)}fork(i=null){return fork$1(this,i)}entries(){return entries(this)}keys(){return keys(this)}values(){return values(this)}}class HashCollisionNode{constructor(i,s,a,c){this.edit=i,this.count=s,this.children=a,this.config=c}get nodeArity(){return 0}get dataArity(){return this.count}lookup(i,s,a,c){return lookupCollision(this,a,c)}associate(i,s,a,c,d,f){return associateCollision(this,i,a,c,d,f)}dissociate(i,s,a,c,d){return dissociateCollision(this,i,a,c,d)}fork(i=null){return forkCollision(this,i)}entries(){return entries(this)}keys(){return keys(this)}values(){return values(this)}}const lookupCollision=(o,i,s)=>{const{children:a,count:c}=o,d=findHashCollisionNodeIndex(a,c,i);return a[d]===i?a[d+1]:s},associateCollision=(o,i,s,a,c,d)=>{const{children:f,count:g}=o,y=findHashCollisionNodeIndex(f,g,a);if(f[y]!==a){const b=o.fork(i);return d.value=!0,b.count+=1,b.children.splice(y,s,c),b}else if(f[y+1]!==c){const b=o.fork(i);return b.children[y+1]=c,b}else return o},dissociateCollision=(o,i,s,a,c)=>{const{children:d,count:f,config:g}=o,y=findHashCollisionNodeIndex(d,f,a);if(d[y]!==a)return o;if(c.value=!0,f===2){const b=y===0?2:0;return associate(create$9(g),i,0,s,d[b],d[b+1],c)}else{const b=o.fork(i);return b.children.splice(y,2),b.count-=1,b}},forkCollision=(o,i=null)=>canEdit(o.edit,i)?o:new HashCollisionNode(i,o.count,o.children.slice(),o.config),findHashCollisionNodeIndex=(o,i,s)=>{let a=0;for(;as;)a+=2;return a},create$9=(o,i=null)=>new BitmapIndexedNode(i,o.BitField.empty(Math.pow(2,o.bitWidth)),o.BitField.empty(Math.pow(2,o.bitWidth)),[],o),get$4=(o,i,s)=>lookup(o,0,o.config.Path.from(i),i,s),lookup=(o,i,s,a,c)=>{const{datamap:d,nodemap:f,config:g}=o,{Path:y,BitField:b}=g,$=y.at(s,i);if(b.get(d,$)){const x=b.popcount(d,$);return keyAt(o,x)===a?valueAt(o,x):c}else return b.get(f,$)?resolveNode(o,$).lookup(i+1,s,a,c):c},set$2=(o,i,s,a,c)=>associate(o,i,0,o.config.Path.from(s),s,a,c),associate=(o,i,s,a,c,d,f)=>{const{datamap:g,nodemap:y,config:b}=o,{Path:$,BitField:x}=b,T=$.at(a,s);if(x.get(g,T)){const A=x.popcount(g,T),E=keyAt(o,A);if(c===E)return valueAt(o,A)===d?o:forkAndSet(o,i,A,d);{const S=mergeTwoLeaves(b,i,s+1,$.from(E),E,valueAt(o,A),a,c,d);return f.value=!0,migrateLeafToBranch(o,i,T,S)}}else if(x.get(y,T)){const A=resolveNode(o,T),E=A.associate(i,s+1,a,c,d,f);return A===E?o:copyAndSetChild(o,i,T,E)}else{const A=x.popcount(g,T);f.value=!0;const E=o.fork(i);return E.datamap=x.set(g,T),E.children.splice(keyPosition(A),0,c,d),E}},remove=(o,i,s,a)=>dissociate(o,i,0,o.config.Path.from(s),s,a),dissociate=(o,i,s,a,c,d)=>{const{datamap:f,nodemap:g,config:y}=o,{BitField:b,Path:$}=y,x=$.at(a,s);if(b.get(f,x)){const T=b.popcount(f,x);if(c===keyAt(o,T)){d.value=!0;const A=fork$1(o,i);return A.datamap=b.unset(o.datamap,x),A.children.splice(keyPosition(T),2),A}else return o}else if(b.get(g,x)){const T=resolveNode(o,x),A=T.dissociate(i,s+1,a,c,d);return hasSingleLeaf(A)?hasSingleNode(o)?A:inlineChild(o,i,x,A):T===A?o:copyAndSetChild(o,i,x,A)}else return o},entries=function*({children:o}){let i=0;const s=o.length;for(;icanEdit(o.edit,i)?o:new BitmapIndexedNode(i,o.datamap,o.nodemap,o.children.slice(),o.config),keys=function*({children:o}){let i=0;const s=o.length;for(;i{const c=o.fork(i);return c.children[valuePosition(s)]=a,c},inlineChild=(o,i,s,a)=>{const{datamap:c,nodemap:d,config:f}=o,{BitField:g}=f,y=fork$1(o,i);return y.children.splice(nodePosition(o,s),1),y.children.splice(keyPosition(g.popcount(c,s)),0,a.children[0],a.children[1]),y.datamap=g.set(c,s),y.nodemap=g.unset(d,s),y},copyAndSetChild=(o,i,s,a)=>{const c=fork$1(o,i);return c.children[nodePosition(o,s)]=a,c},migrateLeafToBranch=(o,i,s,a)=>{const{nodemap:c,datamap:d,config:f}=o,{BitField:g}=f,y=g.popcount(d,s),b=keyPosition(y),$=nodePosition(o,s),x=fork$1(o,i);return x.datamap=g.unset(d,s),x.children.splice(b,2),x.nodemap=g.set(c,s),x.children.splice($-1,0,a),x},mergeTwoLeaves=(o,i,s,a,c,d,f,g,y)=>{const{BitField:b,Path:$}=o;if($.sizeo[keyPosition(i)],keyPosition=o=>o*2,valueAt=({children:o},i)=>o[valuePosition(i)],valuePosition=o=>o*2+1,resolveNode=(o,i)=>o.children[nodePosition(o,i)],nodePosition=({children:o,nodemap:i,config:s},a)=>o.length-1-s.BitField.popcount(i,a),canEdit=(o,i)=>o!=null&&o===i,hasSingleLeaf=o=>o.nodeArity===0&&o.dataArity===1,hasSingleNode=({config:{BitField:o},datamap:i,nodemap:s})=>o.popcount(i)===0&&o.popcount(s)===1,empty$1=new Uint8Array(0);function fromHex(o){const i=o.match(/../g);return i!=null?new Uint8Array(i.map(s=>parseInt(s,16))):empty$1}function coerce$2(o){if(o instanceof Uint8Array&&o.constructor.name==="Uint8Array")return o;if(o instanceof ArrayBuffer)return new Uint8Array(o);if(ArrayBuffer.isView(o))return new Uint8Array(o.buffer,o.byteOffset,o.byteLength);throw new Error("Unknown type, must be binary type")}function base$2(o,i){if(o.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src$2=base$2,_brrp__multiformats_scope_baseX$2=src$2;let Encoder$2=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseEncode");this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}},Decoder$2=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseDecode");U(this,"prefixCodePoint");this.name=i,this.prefix=s;const c=s.codePointAt(0);if(c===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=c,this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or$3(this,i)}},ComposedDecoder$2=class{constructor(i){U(this,"decoders");this.decoders=i}or(i){return or$3(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a!=null)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$3(o,i){return new ComposedDecoder$2({...o.decoders??{[o.prefix]:o},...i.decoders??{[i.prefix]:i}})}let Codec$2=class{constructor(i,s,a,c){U(this,"name");U(this,"prefix");U(this,"baseEncode");U(this,"baseDecode");U(this,"encoder");U(this,"decoder");this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder$2(i,s,a),this.decoder=new Decoder$2(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}};function from$7({name:o,prefix:i,encode:s,decode:a}){return new Codec$2(o,i,s,a)}function baseX$2({name:o,prefix:i,alphabet:s}){const{encode:a,decode:c}=_brrp__multiformats_scope_baseX$2(s,o);return from$7({prefix:i,name:o,encode:a,decode:d=>coerce$2(c(d))})}function decode$b(o,i,s,a){const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f}function encode$8(o,i,s){const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f!==0&&(d+=i[c&g<=INT$3;)i[s++]=o&255|MSB$3,o/=128;for(;o&MSBALL$3;)i[s++]=o&255|MSB$3,o>>>=7;return i[s]=o|0,encode$7.bytes=s-a+1,i}var decode$a=read$3,MSB$1$3=128,REST$1$3=127;function read$3(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$3.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$3)<=MSB$1$3);return read$3.bytes=d-a,s}var N1$2=Math.pow(2,7),N2$2=Math.pow(2,14),N3$2=Math.pow(2,21),N4$2=Math.pow(2,28),N5$2=Math.pow(2,35),N6$2=Math.pow(2,42),N7$2=Math.pow(2,49),N8$2=Math.pow(2,56),N9$2=Math.pow(2,63),length$2=function(o){return ocreate$8(this.code,a))}else throw Error("Unknown type, must be binary type")}};const murmur364=from$6({name:"murmur3-x64-64",code:34,encode:o=>fromHex(mur.x64.hash128(o)).subarray(0,8)}),utf8$1=new TextEncoder,hash64$1=o=>murmur364.encode(o),configure$2=({bitWidth:o=8,hash:i=hash64$1}={})=>{const s=i(new Uint8Array).byteLength;return{from:d=>i(utf8$1.encode(d)),at:(d,f)=>{const g=f*o;if(g>s)throw new RangeError("Out of bounds");return toInt(d,g,o)},size:Math.ceil(s*8/o)}},toInt=(o,i,s)=>{let a=i/8|0,c=i%8,d=s,f=0;for(;d>0&&a>c&g)>>$;f=(f<{if(o%8!==0)throw new Error("Must be multiple of 8");return new Uint8Array(o/8)},from$5=(o,i)=>{let s=empty(i);for(const a of o){const{byte:c,byteOffset:d,bitOffset:f}=at(s,a);s[d]=c|1<o.byteLength*8,at=(o,i)=>{const s=o.byteLength-1-(i/8|0),a=i%8;return{byte:o[s],byteOffset:s,bitOffset:a}},setByte=(o,i,s)=>{if(o[i]!==s){const a=o.slice(0);return a[i]=s,a}return o},set$1=(o,i)=>{const{byte:s,byteOffset:a,bitOffset:c}=at(o,i);return setByte(o,a,s|1<{const{byte:s,byteOffset:a,bitOffset:c}=at(o,i);return setByte(o,a,s&(255^1<{var{byte:s,bitOffset:a}=at(o,i);return(s>>a&1)!==0},toBytes=o=>o,fromBytes$1=o=>o,popcount=(o,i=o.byteLength*8)=>{const{byteOffset:s,bitOffset:a,byte:c}=at(o,i);let d=popcount$1(c,a),f=o.byteLength-1;for(;f>s;){const g=o[f];d+=bitCount(g),f--}return d},or$2=(o,i)=>{const s=o.slice();let a=0;for(;a{const s=o.slice();let a=0;for(;a({bitWidth:o,BitField:i,Path:s}),from$4=(o,i)=>{const s=builder$1(i);for(const[a,c]of o)s.set(a,c);return s.build()},has=(o,i)=>get$4(o.root,i,NOT_FOUND)!==NOT_FOUND,get$2=(o,i,s=void 0)=>get$4(o.root,i,s),builder$1=o=>{const i={},s=configure$1(o);return new HashMapBuilder(i,0,create$9(s,i),s)};class PersistentHashMap{constructor(i=0,s,a){this.count=i,this.root=s,this.config=a}get size(){return this.count}clone(){return new PersistentHashMap(this.count,this.root,this.config)}empty(){return new PersistentHashMap(0,create$9(this.config,null),this.config)}has(i){return has(this,i)}get(i){return get$4(this.root,i,void 0)}set(i,s){const a={value:!1},c=set$2(this.root,null,i,s,a);return c===this.root?this:new PersistentHashMap(a.value?this.count+1:this.count,c,this.config)}delete(i){const s=remove(this.root,null,i,{value:!1});return s===this.root?this:new PersistentHashMap(this.count-1,s,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 HashMapBuilder({},this.count,this.root,this.config)}}class HashMapBuilder{constructor(i,s,a,c){this.edit=i,this.count=s,this.root=a,this.config=c}get size(){if(this.edit)return this.count;throw new Error(".size was accessed on the finalized builder")}set(i,s){if(this.edit){const a={value:!1},c=set$2(this.root,this.edit,i,s,a);return this.root!==c&&(this.root=c),a.value&&(this.count+=1),this}else throw new Error(".set was called on the finalized builder")}delete(i){if(this.edit){if(this.count===0)return this;const s={value:!1},a=remove(this.root,this.edit,i,s);return a!==this.root&&(this.root=a),s.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 PersistentHashMap(this.count,this.root,this.config);throw new Error(".build was called on the finalized builder")}}const utf8=new TextEncoder,hash64=o=>murmur364.encode(o),configure=({bitWidth:o=8,hash:i=hash64})=>{const s=i(new Uint8Array).byteLength,a={bitWidth:o,hash:i,hashSize:s};return{at:(f,g)=>read$2(f,g,a),from:f=>utf8.encode(f),size:1/0}},read$2=(o,i=0,{bitWidth:s=8,hash:a,hashSize:c})=>{const d=c*8;let f=0,g=s,y=s*i;for(;g>0;){const b=y/d>>0,$=a(b===0?o:appendByte(o,b)),x=d<=y?y%d:y,T=d-x,A=T{const s=new Uint8Array(o.byteLength+1).fill(i,o.byteLength);return s.set(o),s},bitWidth=8,config={bitWidth,Path:configure({bitWidth})},tableSize=o=>Math.pow(2,o.config.bitWidth),builder=(o=config)=>builder$1(o),from$3=(o,i=config)=>from$4(o,i),bitField=({datamap:o,nodemap:i,config:{BitField:s}})=>withoutLeadingZeros(s.toBytes(s.or(o,i))),withoutLeadingZeros=o=>{let i=0;for(;i`[${JSON.stringify(f)}]`).join("")}`);const d=CID$2.asCID(s);if(d)return{value:d,remaining:i.slice(a+1).join("/")}}return{value:s}}class Block{constructor({cid:i,bytes:s,value:a}){if(!i||!s||typeof a>"u")throw new Error("Missing required argument");this.cid=i,this.bytes=s,this.value=a,this.asBlock=this,Object.defineProperties(this,{cid:readonly(),bytes:readonly(),value:readonly(),asBlock:readonly()})}links(){return links(this.value,[])}tree(){return tree(this.value,[])}get(i="/"){return get$1(this.value,i.split("/").filter(Boolean))}}const defaults=defaults$2,create$7=({writer:o,settings:i=defaults(),metadata:s={}})=>new HAMTDirectoryWriter({writer:o,metadata:s,settings:i,entries:new HashMap,closed:!1}),asWritable=o=>{if(o.closed)throw new Error("Can not change written HAMT directory, but you can .fork() and make changes to it");return o},close$1=async(o,{closeWriter:i=!1,releaseLock:s=!1}={})=>{const{writer:a,settings:c,metadata:d}=asWritable(o.state);o.state.closed=!0;const{entries:f}=o.state;if(!(f instanceof HashMap))throw new Error(`not a HAMT: ${f}`);const g=f.builder.build(),y=iterateBlocks(g,g.root,c);let b=null;for await(const $ of y)b=$,(a.desiredSize||0)<=0&&await a.ready,a.write($);if(b==null)throw new Error("no root block yielded");return i?await a.close():s&&a.releaseLock(),{cid:b.cid,dagByteLength:cumulativeDagByteLength(b.bytes,b.value.entries)}},iterateBlocks=async function*(o,i,s){const a=[];for(const d of iterate(i))if("key"in d)a.push({name:`${d.prefix??""}${d.key??""}`,dagByteLength:d.value.dagByteLength,cid:d.value.cid});else{let f=null;for await(const g of iterateBlocks(o,d.node,s))yield g,f=g;if(f==null)throw new Error("no root block yielded");a.push({name:d.prefix,dagByteLength:cumulativeDagByteLength(f.bytes,f.value.entries),cid:f.cid})}const c=createDirectoryShard(a,bitField(i),tableSize(o),murmur364.code);yield await encodeHAMTShardBlock(c,s)};async function encodeHAMTShardBlock(o,i){const s=encodeHAMTShard(o),a=await i.hasher.digest(s),c=i.linker.createLink(code$2,a);return new Block({cid:c,bytes:s,value:o})}const fork=({state:o},{writer:i=o.writer,metadata:s=o.metadata,settings:a=o.settings}={})=>new HAMTDirectoryWriter({writer:i,metadata:s,settings:a,entries:new HashMap(from$3(o.entries.entries()).createBuilder()),closed:!1});class HAMTDirectoryWriter{constructor(i){this.state=i}get writer(){return this.state.writer}get settings(){return this.state.settings}set(i,s,a){return set$4(this,i,s,a)}remove(i){return remove$1(this,i)}fork(i){return fork(this,i)}close(i){return close$1(this,i)}entries(){return this.state.entries.entries()}has(i){return this.state.entries.has(i)}get size(){return this.state.entries.size}}class HashMap extends Map{constructor(i=builder()){super(),this.builder=i}clear(){this.builder=builder()}delete(i){const{root:s}=this.builder;return this.builder.delete(i),this.builder.root!==s}forEach(i,s=this){for(const[a,c]of this.builder.root.entries())i.call(s,c,a,this)}get(i){return get$2(this.builder,i)}has(i){return has(this.builder,i)}set(i,s){return this.builder.set(i,s),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()}}const createWriter=({writable:o,settings:i=defaults$2()})=>new FileSystemWriter({writer:o.getWriter(),settings:i}),close=async(o,{releaseLock:i=!0,closeWriter:s=!0}={})=>(s?await o.writer.close():i&&o.writer.releaseLock(),o);class FileSystemWriter{constructor({writer:i,settings:s}){this.writer=i,this.settings=configure$4(s)}createFileWriter({settings:i=this.settings,metadata:s}={}){return create$b({writer:this.writer,settings:i,metadata:s})}createDirectoryWriter({settings:i=this.settings,metadata:s}={}){return create$a({writer:this.writer,settings:i,metadata:s})}close(i){return close(this,i)}}const BLOCK_SIZE_LIMIT=1048576,defaultCapacity=BLOCK_SIZE_LIMIT*100,withCapacity=(o=defaultCapacity)=>({highWaterMark:o,size:i=>i.bytes.length}),SHARD_THRESHOLD=1e3,queuingStrategy=withCapacity(),defaultSettings=configure$4({fileChunkEncoder:raw,smallFileEncoder:raw,chunker:withMaxChunkSize(1024*1024),fileLayout:withWidth(1024)});function createFileEncoderStream(o,i){const{readable:s,writable:a}=new TransformStream({},queuingStrategy),c=(i==null?void 0:i.settings)??defaultSettings,d=createWriter({writable:a,settings:c}),f=new UnixFSFileBuilder("",o);return(async()=>(await f.finalize(d),await d.close()))(),s}var wt;class UnixFSFileBuilder{constructor(i,s){Y(this,wt);this.name=i,Q(this,wt,s)}async finalize(i){const s=create$b(i);return await F(this,wt).stream().pipeTo(new WritableStream({async write(a){await s.write(a)}})),await s.close()}}wt=new WeakMap;var ot;class UnixFSDirectoryBuilder{constructor(i,s){Y(this,ot);U(this,"entries",new Map);this.name=i,Q(this,ot,s)}async finalize(i){var a;const s=this.entries.size<=SHARD_THRESHOLD?create$a(i):create$7(i);for(const[c,d]of this.entries){const f=await d.finalize(i);(a=F(this,ot))!=null&&a.onDirectoryEntryLink&&F(this,ot).onDirectoryEntryLink({name:d.name,...f}),s.set(c,f)}return await s.close()}}ot=new WeakMap;function createDirectoryEncoderStream(o,i){const s=new UnixFSDirectoryBuilder("",i);for(const g of o){const y=g.name.split("/");(y[0]===""||y[0]===".")&&y.shift();let b=s;for(const[$,x]of y.entries()){if($===y.length-1){b.entries.set(x,new UnixFSFileBuilder(y.join("/"),g));break}let T=b.entries.get(x);if(T==null){const A=b===s?x:`${b.name}/${x}`;T=new UnixFSDirectoryBuilder(A,i),b.entries.set(x,T)}if(!(T instanceof UnixFSDirectoryBuilder))throw new Error(`"${g.name}" cannot be a file and a directory`);b=T}}const{readable:a,writable:c}=new TransformStream({},queuingStrategy),d=(i==null?void 0:i.settings)??defaultSettings,f=createWriter({writable:c,settings:d});return(async()=>{const g=await s.finalize(f);i!=null&&i.onDirectoryEntryLink&&i.onDirectoryEntryLink({name:"",...g}),await f.close()})(),a}async function readHeader(o,i){const s=decodeVarint$1(await o.upTo(8),o);if(s===0)throw new Error("Invalid CAR header (zero length)");const a=await o.exactly(s,!0),c=decode$1a(a);if(CarV1HeaderOrV2Pragma.toTyped(c)===void 0)throw new Error("Invalid CAR header format");if(c.version!==1&&c.version!==2||i!==void 0&&c.version!==i)throw new Error(`Invalid CAR version: ${c.version}${i!==void 0?` (expected ${i})`:""}`);if(c.version===1){if(!Array.isArray(c.roots))throw new Error("Invalid CAR header format");return c}if(c.roots!==void 0)throw new Error("Invalid CAR header format");const d=decodeV2Header(await o.exactly(V2_HEADER_LENGTH,!0));o.seek(d.dataOffset-o.pos);const f=await readHeader(o,1);return Object.assign(f,d)}async function readCid(o){const i=await o.exactly(2,!1);if(i[0]===CIDV0_BYTES$1.SHA2_256&&i[1]===CIDV0_BYTES$1.LENGTH){const f=await o.exactly(34,!0),g=decode$O(f);return CID$6.create(0,CIDV0_BYTES$1.DAG_PB,g)}const s=decodeVarint$1(await o.upTo(8),o);if(s!==1)throw new Error(`Unexpected CID version (${s})`);const a=decodeVarint$1(await o.upTo(8),o),c=await o.exactly(getMultihashLength$1(await o.upTo(8)),!0),d=decode$O(c);return CID$6.create(s,a,d)}async function readBlockHead(o){const i=o.pos;let s=decodeVarint$1(await o.upTo(8),o);if(s===0)throw new Error("Invalid CAR section (zero length)");s+=o.pos-i;const a=await readCid(o),c=s-Number(o.pos-i);return{cid:a,length:s,blockLength:c}}async function readBlock(o){const{cid:i,blockLength:s}=await readBlockHead(o);return{bytes:await o.exactly(s,!0),cid:i}}async function readBlockIndex(o){const i=o.pos,{cid:s,length:a,blockLength:c}=await readBlockHead(o),d={cid:s,length:a,blockLength:c,offset:i,blockOffset:o.pos};return o.seek(d.blockLength),d}function createDecoder(o){const i=(async()=>{const s=await readHeader(o);if(s.version===2){const a=o.pos-s.dataOffset;o=limitReader(o,s.dataSize-a)}return s})();return{header:()=>i,async*blocks(){for(await i;(await o.upTo(8)).length>0;)yield await readBlock(o)},async*blocksIndex(){for(await i;(await o.upTo(8)).length>0;)yield await readBlockIndex(o)}}}function bytesReader(o){let i=0;return{async upTo(s){return o.subarray(i,i+Math.min(s,o.length-i))},async exactly(s,a=!1){if(s>o.length-i)throw new Error("Unexpected end of data");const c=o.subarray(i,i+s);return a&&(i+=s),c},seek(s){i+=s},get pos(){return i}}}function chunkReader(o){let i=0,s=0,a=0,c=new Uint8Array(0);const d=async f=>{s=c.length-a;const g=[c.subarray(a)];for(;ss&&g.push(b.subarray(-s)):g.push(b),s+=b.length}c=new Uint8Array(g.reduce((b,$)=>b+$.length,0));let y=0;for(const b of g)c.set(b,y),y+=b.length;a=0};return{async upTo(f){return c.length-ai&&(c=c.subarray(0,i-s)),c},async exactly(a,c=!1){const d=await o.exactly(a,c);if(d.length+s>i)throw new Error("Unexpected end of data");return c&&(s+=a),d},seek(a){s+=a,o.seek(a)},get pos(){return o.pos}}}class CarIteratorBase{constructor(i,s,a){this._version=i,this._roots=s,this._iterable=a,this._decoded=!1}get version(){return this._version}async getRoots(){return this._roots}}class CarBlockIterator extends CarIteratorBase{[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(i){const{version:s,roots:a,iterator:c}=await fromBytes(i);return new CarBlockIterator(s,a,c)}static async fromIterable(i){const{version:s,roots:a,iterator:c}=await fromIterable(i);return new CarBlockIterator(s,a,c)}}async function fromBytes(o){if(!(o instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return decodeIterator(bytesReader(o))}async function fromIterable(o){if(!o||typeof o[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return decodeIterator(asyncIterableReader(o))}async function decodeIterator(o){const i=createDecoder(o),{version:s,roots:a}=await i.header();return{version:s,roots:a,iterator:i.blocks()}}const CAR_V1_VERSION=1;function createHeader(o){const i=encode$O({version:CAR_V1_VERSION,roots:o}),s=varint$a.encode(i.length),a=new Uint8Array(s.length+i.length);return a.set(s,0),a.set(i,s.length),a}function createEncoder(o){return{async setRoots(i){const s=createHeader(i);await o.write(s)},async writeBlock(i){const{cid:s,bytes:a}=i;await o.write(new Uint8Array(varint$a.encode(s.bytes.length+a.length))),await o.write(s.bytes),a.length&&await o.write(a)},async close(){await o.end()},version(){return CAR_V1_VERSION}}}function noop(){}function create$6(){const o=[];let i=null,s=noop,a=!1,c=null,d=noop;const f=()=>(i||(i=new Promise(b=>{s=()=>{i=null,s=noop,b()}})),i),g={write(b){o.push(b);const $=f();return d(),$},async end(){a=!0;const b=f();d(),await b}},y={async next(){const b=o.shift();return b?(o.length===0&&s(),{done:!1,value:b}):a?(s(),{done:!0,value:void 0}):(c||(c=new Promise($=>{d=()=>(c=null,d=noop,$(y.next()))})),c)}};return{writer:g,iterator:y}}class CarWriter{constructor(i,s){this._encoder=s,this._mutex=s.setRoots(i),this._ended=!1}async put(i){if(!(i.bytes instanceof Uint8Array)||!i.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");const s=CID$6.asCID(i.cid);if(!s)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:s,bytes:i.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(i){i=toRoots(i);const{encoder:s,iterator:a}=encodeWriter(),c=new CarWriter(i,s),d=new CarWriterOut(a);return{writer:c,out:d}}static createAppender(){const{encoder:i,iterator:s}=encodeWriter();i.setRoots=()=>Promise.resolve();const a=new CarWriter([],i),c=new CarWriterOut(s);return{writer:a,out:c}}static async updateRootsInBytes(i,s){const a=bytesReader(i);await readHeader(a);const c=createHeader(s);if(Number(a.pos)!==c.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${a.pos} bytes, new header is ${c.length} bytes)`);return i.set(c,0),i}}class CarWriterOut{constructor(i){this._iterator=i}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}}function encodeWriter(){const o=create$6(),{writer:i,iterator:s}=o;return{encoder:createEncoder(i),iterator:s}}function toRoots(o){if(o===void 0)return[];if(!Array.isArray(o)){const s=CID$6.asCID(o);if(!s)throw new TypeError("roots must be a single CID or an array of CIDs");return[s]}const i=[];for(const s of o){const a=CID$6.asCID(s);if(!a)throw new TypeError("roots must be a single CID or an array of CIDs");i.push(a)}return i}const code=514,NO_ROOTS_HEADER_LENGTH=18;function headerEncodingLength(o){if(!o)return NO_ROOTS_HEADER_LENGTH;const i=encode$O({version:1,roots:[o]}).length;return varint$a.encodingLength(i)+i}function blockHeaderEncodingLength(o){const i=o.cid.bytes.length+o.bytes.length;return varint$a.encodingLength(i)+o.cid.bytes.length}function blockEncodingLength(o){return blockHeaderEncodingLength(o)+o.bytes.length}async function encode$6(o,i){const{writer:s,out:a}=CarWriter.create(i);let c;(async()=>{try{for await(const g of o)await s.put(g)}catch(g){c=g}finally{await s.close()}})();const d=[];for await(const g of a)d.push(g);if(c!=null)throw c;const f=i!=null?[i]:[];return Object.assign(new Blob(d),{version:1,roots:f})}class BlockStream extends ReadableStream{constructor(i){let s=null;const a=()=>s||(s=CarBlockIterator.fromIterable(toIterable(i.stream())),s);let c=null;super({async start(){c=(await a())[Symbol.asyncIterator]()},async pull(d){if(!c)throw new Error("missing blocks iterator");const{value:f,done:g}=await c.next();if(g)return d.close();d.enqueue(f)}}),this.getRoots=async()=>await(await a()).getRoots()}}function toIterable(o){return Symbol.asyncIterator in o?o:async function*(){const i=o.getReader();try{for(;;){const{done:s,value:a}=await i.read();if(s)return;yield a}}finally{i.releaseLock()}}()}function compare(o,i){for(let s=0;si[s])return 1}return o.byteLength>i.byteLength?1:o.byteLength=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src$1=base$1,_brrp__multiformats_scope_baseX$1=src$1;let Encoder$1=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseEncode");this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}},Decoder$1=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseDecode");U(this,"prefixCodePoint");this.name=i,this.prefix=s;const c=s.codePointAt(0);if(c===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=c,this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or$1(this,i)}},ComposedDecoder$1=class{constructor(i){U(this,"decoders");this.decoders=i}or(i){return or$1(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a!=null)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$1(o,i){return new ComposedDecoder$1({...o.decoders??{[o.prefix]:o},...i.decoders??{[i.prefix]:i}})}let Codec$1=class{constructor(i,s,a,c){U(this,"name");U(this,"prefix");U(this,"baseEncode");U(this,"baseDecode");U(this,"encoder");U(this,"decoder");this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder$1(i,s,a),this.decoder=new Decoder$1(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}};function from$2({name:o,prefix:i,encode:s,decode:a}){return new Codec$1(o,i,s,a)}function baseX$1({name:o,prefix:i,alphabet:s}){const{encode:a,decode:c}=_brrp__multiformats_scope_baseX$1(s,o);return from$2({prefix:i,name:o,encode:a,decode:d=>coerce$1(c(d))})}function decode$9(o,i,s,a){const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f}function encode$5(o,i,s){const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f!==0&&(d+=i[c&g<(o[s]=i,o),[]),alphabetCharsToBytes=alphabet.reduce((o,i,s)=>{const a=i.codePointAt(0);if(a==null)throw new Error(`Invalid character: ${i}`);return o[a]=s,o},[]);function encode$4(o){return o.reduce((i,s)=>(i+=alphabetBytesToChars[s],i),"")}function decode$8(o){const i=[];for(const s of o){const a=s.codePointAt(0);if(a==null)throw new Error(`Invalid character: ${s}`);const c=alphabetCharsToBytes[a];if(c==null)throw new Error(`Non-base256emoji character: ${s}`);i.push(c)}return new Uint8Array(i)}from$2({prefix:"🚀",name:"base256emoji",encode:encode$4,decode:decode$8});const base32$1=rfc4648$1({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5});rfc4648$1({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5});rfc4648$1({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5});rfc4648$1({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5});rfc4648$1({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5});rfc4648$1({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5});rfc4648$1({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5});rfc4648$1({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5});rfc4648$1({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});const base36$1=baseX$1({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"});baseX$1({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});const base58btc$1=baseX$1({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});baseX$1({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});rfc4648$1({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6});rfc4648$1({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6});rfc4648$1({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6});rfc4648$1({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});rfc4648$1({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});from$2({prefix:"\0",name:"identity",encode:o=>toString(o),decode:o=>fromString(o)});new TextEncoder;new TextDecoder;var encode_1$1=encode$3,MSB$2=128,REST$2=127,MSBALL$2=~REST$2,INT$2=Math.pow(2,31);function encode$3(o,i,s){i=i||[],s=s||0;for(var a=s;o>=INT$2;)i[s++]=o&255|MSB$2,o/=128;for(;o&MSBALL$2;)i[s++]=o&255|MSB$2,o>>>=7;return i[s]=o|0,encode$3.bytes=s-a+1,i}var decode$7=read$1,MSB$1$2=128,REST$1$2=127;function read$1(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$1.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$2)<=MSB$1$2);return read$1.bytes=d-a,s}var N1$1=Math.pow(2,7),N2$1=Math.pow(2,14),N3$1=Math.pow(2,21),N4$1=Math.pow(2,28),N5$1=Math.pow(2,35),N6$1=Math.pow(2,42),N7$1=Math.pow(2,49),N8$1=Math.pow(2,56),N9$1=Math.pow(2,63),length$1=function(o){return ocreate$5(this.code,a))}else throw Error("Unknown type, must be binary type")}}function sha(o){return async i=>new Uint8Array(await crypto.subtle.digest(o,i))}const sha256=from$1({name:"sha2-256",code:18,encode:sha("SHA-256")});function format$1(o,i){const{bytes:s,version:a}=o;switch(a){case 0:return toStringV0$1(s,baseCache$1(o),i??base58btc$1.encoder);default:return toStringV1$1(s,baseCache$1(o),i??base32$1.encoder)}}const cache$2=new WeakMap;function baseCache$1(o){const i=cache$2.get(o);if(i==null){const s=new Map;return cache$2.set(o,s),s}return i}var Yt;let CID$1=class we{constructor(i,s,a,c){U(this,"code");U(this,"version");U(this,"multihash");U(this,"bytes");U(this,"/");U(this,Yt,"CID");this.code=s,this.version=i,this.multihash=a,this.bytes=c,this["/"]=c}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:{const{code:i,multihash:s}=this;if(i!==DAG_PB_CODE$2)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(s.code!==SHA_256_CODE$1)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return we.createV0(s)}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:{const{code:i,digest:s}=this.multihash,a=create$5(i,s);return we.createV1(this.code,a)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(i){return we.equals(this,i)}static equals(i,s){const a=s;return a!=null&&i.code===a.code&&i.version===a.version&&equals$3(i.multihash,a.multihash)}toString(i){return format$1(this,i)}toJSON(){return{"/":format$1(this)}}link(){return this}[(Yt=Symbol.toStringTag,Symbol.for("nodejs.util.inspect.custom"))](){return`CID(${this.toString()})`}static asCID(i){if(i==null)return null;const s=i;if(s instanceof we)return s;if(s["/"]!=null&&s["/"]===s.bytes||s.asCID===s){const{version:a,code:c,multihash:d,bytes:f}=s;return new we(a,c,d,f??encodeCID$1(a,c,d.bytes))}else if(s[cidSymbol$1]===!0){const{version:a,multihash:c,code:d}=s,f=decode$5(c);return we.create(a,d,f)}else return null}static create(i,s,a){if(typeof s!="number")throw new Error("String codecs are no longer supported");if(!(a.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(i){case 0:{if(s!==DAG_PB_CODE$2)throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE$2}) block encoding`);return new we(i,s,a,a.bytes)}case 1:{const c=encodeCID$1(i,s,a.bytes);return new we(i,s,a,c)}default:throw new Error("Invalid version")}}static createV0(i){return we.create(0,DAG_PB_CODE$2,i)}static createV1(i,s){return we.create(1,i,s)}static decode(i){const[s,a]=we.decodeFirst(i);if(a.length!==0)throw new Error("Incorrect length");return s}static decodeFirst(i){const s=we.inspectBytes(i),a=s.size-s.multihashSize,c=coerce$1(i.subarray(a,a+s.multihashSize));if(c.byteLength!==s.multihashSize)throw new Error("Incorrect length");const d=c.subarray(s.multihashSize-s.digestSize),f=new Digest$1(s.multihashCode,s.digestSize,d,c);return[s.version===0?we.createV0(f):we.createV1(s.codec,f),i.subarray(s.size)]}static inspectBytes(i){let s=0;const a=()=>{const[x,T]=decode$6(i.subarray(s));return s+=T,x};let c=a(),d=DAG_PB_CODE$2;if(c===18?(c=0,s=0):d=a(),c!==0&&c!==1)throw new RangeError(`Invalid CID version ${c}`);const f=s,g=a(),y=a(),b=s+y,$=b-f;return{version:c,codec:d,multihashCode:g,digestSize:y,multihashSize:$,size:b}}static parse(i,s){const[a,c]=parseCIDtoBytes$1(i,s),d=we.decode(c);if(d.version===0&&i[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache$1(d).set(a,i),d}};function parseCIDtoBytes$1(o,i){switch(o[0]){case"Q":{const s=i??base58btc$1;return[base58btc$1.prefix,s.decode(`${base58btc$1.prefix}${o}`)]}case base58btc$1.prefix:{const s=i??base58btc$1;return[base58btc$1.prefix,s.decode(o)]}case base32$1.prefix:{const s=i??base32$1;return[base32$1.prefix,s.decode(o)]}case base36$1.prefix:{const s=i??base36$1;return[base36$1.prefix,s.decode(o)]}default:{if(i==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[o[0],i.decode(o)]}}}function toStringV0$1(o,i,s){const{prefix:a}=s;if(a!==base58btc$1.prefix)throw Error(`Cannot string encode V0 in ${s.name} encoding`);const c=i.get(a);if(c==null){const d=s.encode(o).slice(1);return i.set(a,d),d}else return c}function toStringV1$1(o,i,s){const{prefix:a}=s,c=i.get(a);if(c==null){const d=s.encode(o);return i.set(a,d),d}else return c}const DAG_PB_CODE$2=112,SHA_256_CODE$1=18;function encodeCID$1(o,i,s){const a=encodingLength$1(o),c=a+encodingLength$1(i),d=new Uint8Array(c+s.byteLength);return encodeTo$1(o,d,0),encodeTo$1(i,d,a),d.set(s,c),d}const cidSymbol$1=Symbol.for("@ipld/js-cid/CID");function create$4(o,i){return CID$1.create(1,o,i)}const cache$1=new WeakMap,toBase58String=o=>{let i=cache$1.get(o.bytes);return i||(i=base58btc$1.encode(o.bytes),cache$1.set(o.bytes,i)),i};var ve;class DigestMap{constructor(i){Y(this,ve);Q(this,ve,new Map);for(const[s,a]of i??[])this.set(s,a)}get[Symbol.toStringTag](){return"DigestMap"}clear(){F(this,ve).clear()}delete(i){const s=toBase58String(i);return F(this,ve).delete(s)}forEach(i,s){for(const[a,c]of F(this,ve).values())i.call(s,c,a,this)}get(i){const s=F(this,ve).get(toBase58String(i));if(s)return s[1]}has(i){return F(this,ve).has(toBase58String(i))}set(i,s){return F(this,ve).set(toBase58String(i),[i,s]),this}get size(){return F(this,ve).size}[Symbol.iterator](){return this.entries()}*entries(){yield*F(this,ve).values()}*keys(){for(const[i]of F(this,ve).values())yield i}*values(){for(const[,i]of F(this,ve).values())yield i}}ve=new WeakMap;const version="index/sharded/dag@0.1";variant({[version]:struct({content:match$2(),shards:array(match$2())})});var $t,Ke;class ShardedDAGIndex{constructor(i){Y(this,$t);Y(this,Ke);Q(this,$t,i),Q(this,Ke,new DigestMap)}get content(){return F(this,$t)}get shards(){return F(this,Ke)}setSlice(i,s,a){let c=F(this,Ke).get(i);c||(c=new DigestMap,F(this,Ke).set(i,c)),c.set(s,a)}archive(){return archive$1(this)}}$t=new WeakMap,Ke=new WeakMap;const create$3=o=>new ShardedDAGIndex(o),archive$1=async o=>{const i=new Map,s=[...o.shards.entries()].sort((g,y)=>compare(g[0].digest,y[0].digest)),a={content:o.content,shards:[]};for(const g of s){const y=[...g[1].entries()].sort((T,A)=>compare(T[0].digest,A[0].digest)).map(T=>[T[0].bytes,T[1]]),b=encode$O([g[0].bytes,y]),$=await sha256.digest(b),x=create$4(code$h,$);i.set(x.toString(),{cid:x,bytes:b}),a.shards.push(x)}const c=encode$O({[version]:a}),d=await sha256.digest(c),f=create$4(code$h,d);return ok(encode$v({roots:[{cid:f,bytes:c}],blocks:i}))};function alloc(o=0){return new Uint8Array(o)}function allocUnsafe(o=0){return new Uint8Array(o)}function asUint8Array(o){return o}function concat(o,i){i==null&&(i=o.reduce((c,d)=>c+d.length,0));const s=allocUnsafe(i);let a=0;for(const c of o)s.set(c,a),a+=c.length;return s}function equals$2(o,i){if(o===i)return!0;if(o.byteLength!==i.byteLength)return!1;for(let s=0;s0&&this.appendAll(i)}*[(Jt=symbol,Symbol.iterator)](){yield*this.bufs}get byteLength(){return this.length}append(...i){this.appendAll(i)}appendAll(i){let s=0;for(const a of i)if(a instanceof Uint8Array)s+=a.byteLength,this.bufs.push(a);else if(isUint8ArrayList(a))s+=a.byteLength,this.bufs.push(...a.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=s}prepend(...i){this.prependAll(i)}prependAll(i){let s=0;for(const a of i.reverse())if(a instanceof Uint8Array)s+=a.byteLength,this.bufs.unshift(a);else if(isUint8ArrayList(a))s+=a.byteLength,this.bufs.unshift(...a.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=s}get(i){const s=findBufAndOffset(this.bufs,i);return s.buf[s.index]}set(i,s){const a=findBufAndOffset(this.bufs,i);a.buf[a.index]=s}write(i,s=0){if(i instanceof Uint8Array)for(let a=0;a0;)if(i>=this.bufs[0].byteLength)i-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(i),this.length-=i;break}}}slice(i,s){const{bufs:a,length:c}=this._subList(i,s);return concat(a,c)}subarray(i,s){const{bufs:a,length:c}=this._subList(i,s);return a.length===1?a[0]:concat(a,c)}sublist(i,s){const{bufs:a,length:c}=this._subList(i,s),d=new Uint8ArrayList;return d.length=c,d.bufs=[...a],d}_subList(i,s){if(i=i??0,s=s??this.length,i<0&&(i=this.length+i),s<0&&(s=this.length+s),i<0||s>this.length)throw new RangeError("index is out of bounds");if(i===s)return{bufs:[],length:0};if(i===0&&s===this.length)return{bufs:this.bufs,length:this.length};const a=[];let c=0;for(let d=0;d=y)continue;const b=i>=g&&ig&&s<=y;if(b&&$){if(i===g&&s===y){a.push(f);break}const x=i-g;a.push(f.subarray(x,x+(s-i)));break}if(b){if(i===0){a.push(f);continue}a.push(f.subarray(i-g));continue}if($){if(s===y){a.push(f);break}a.push(f.subarray(0,s-g));break}a.push(f)}return{bufs:a,length:s-i}}indexOf(i,s=0){if(!isUint8ArrayList(i)&&!(i instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const a=i instanceof Uint8Array?i:i.subarray();if(s=Number(s??0),isNaN(s)&&(s=0),s<0&&(s=this.length+s),s<0&&(s=0),i.length===0)return s>this.length?this.length:s;const c=a.byteLength;if(c===0)throw new TypeError("search must be at least 1 byte long");const d=256,f=new Int32Array(d);for(let x=0;x=0;T--){const A=this.get(x+T);if(a[T]!==A){$=Math.max(1,T-g[A]);break}}if($===0)return x}return-1}getInt8(i){const s=this.subarray(i,i+1);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt8(0)}setInt8(i,s){const a=allocUnsafe(1);new DataView(a.buffer,a.byteOffset,a.byteLength).setInt8(0,s),this.write(a,i)}getInt16(i,s){const a=this.subarray(i,i+2);return new DataView(a.buffer,a.byteOffset,a.byteLength).getInt16(0,s)}setInt16(i,s,a){const c=alloc(2);new DataView(c.buffer,c.byteOffset,c.byteLength).setInt16(0,s,a),this.write(c,i)}getInt32(i,s){const a=this.subarray(i,i+4);return new DataView(a.buffer,a.byteOffset,a.byteLength).getInt32(0,s)}setInt32(i,s,a){const c=alloc(4);new DataView(c.buffer,c.byteOffset,c.byteLength).setInt32(0,s,a),this.write(c,i)}getBigInt64(i,s){const a=this.subarray(i,i+8);return new DataView(a.buffer,a.byteOffset,a.byteLength).getBigInt64(0,s)}setBigInt64(i,s,a){const c=alloc(8);new DataView(c.buffer,c.byteOffset,c.byteLength).setBigInt64(0,s,a),this.write(c,i)}getUint8(i){const s=this.subarray(i,i+1);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint8(0)}setUint8(i,s){const a=allocUnsafe(1);new DataView(a.buffer,a.byteOffset,a.byteLength).setUint8(0,s),this.write(a,i)}getUint16(i,s){const a=this.subarray(i,i+2);return new DataView(a.buffer,a.byteOffset,a.byteLength).getUint16(0,s)}setUint16(i,s,a){const c=alloc(2);new DataView(c.buffer,c.byteOffset,c.byteLength).setUint16(0,s,a),this.write(c,i)}getUint32(i,s){const a=this.subarray(i,i+4);return new DataView(a.buffer,a.byteOffset,a.byteLength).getUint32(0,s)}setUint32(i,s,a){const c=alloc(4);new DataView(c.buffer,c.byteOffset,c.byteLength).setUint32(0,s,a),this.write(c,i)}getBigUint64(i,s){const a=this.subarray(i,i+8);return new DataView(a.buffer,a.byteOffset,a.byteLength).getBigUint64(0,s)}setBigUint64(i,s,a){const c=alloc(8);new DataView(c.buffer,c.byteOffset,c.byteLength).setBigUint64(0,s,a),this.write(c,i)}getFloat32(i,s){const a=this.subarray(i,i+4);return new DataView(a.buffer,a.byteOffset,a.byteLength).getFloat32(0,s)}setFloat32(i,s,a){const c=alloc(4);new DataView(c.buffer,c.byteOffset,c.byteLength).setFloat32(0,s,a),this.write(c,i)}getFloat64(i,s){const a=this.subarray(i,i+8);return new DataView(a.buffer,a.byteOffset,a.byteLength).getFloat64(0,s)}setFloat64(i,s,a){const c=alloc(8);new DataView(c.buffer,c.byteOffset,c.byteLength).setFloat64(0,s,a),this.write(c,i)}equals(i){if(i==null||!(i instanceof Uint8ArrayList)||i.bufs.length!==this.bufs.length)return!1;for(let s=0;sc+d.byteLength,0)),a.length=s,a}}function equals$1(o,i){if(o===i)return!0;if(o.byteLength!==i.byteLength)return!1;for(let s=0;s=INT$1;)i[s++]=o&255|MSB$1,o/=128;for(;o&MSBALL$1;)i[s++]=o&255|MSB$1,o>>>=7;return i[s]=o|0,encode$2.bytes=s-a+1,i}var decode$4=read,MSB$1$1=128,REST$1$1=127;function read(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$1)<=MSB$1$1);return read.bytes=d-a,s}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length=function(o){return o=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src=base,_brrp__multiformats_scope_baseX=src;class Encoder{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseEncode");this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}}class Decoder{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseDecode");U(this,"prefixCodePoint");this.name=i,this.prefix=s;const c=s.codePointAt(0);if(c===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=c,this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or(this,i)}}class ComposedDecoder{constructor(i){U(this,"decoders");this.decoders=i}or(i){return or(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a!=null)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function or(o,i){return new ComposedDecoder({...o.decoders??{[o.prefix]:o},...i.decoders??{[i.prefix]:i}})}class Codec{constructor(i,s,a,c){U(this,"name");U(this,"prefix");U(this,"baseEncode");U(this,"baseDecode");U(this,"encoder");U(this,"decoder");this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder(i,s,a),this.decoder=new Decoder(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}}function from({name:o,prefix:i,encode:s,decode:a}){return new Codec(o,i,s,a)}function baseX({name:o,prefix:i,alphabet:s}){const{encode:a,decode:c}=_brrp__multiformats_scope_baseX(s,o);return from({prefix:i,name:o,encode:a,decode:d=>coerce(c(d))})}function decode$1(o,i,s,a){const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f}function encode$1(o,i,s){const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f!==0&&(d+=i[c&g<{const[x,T]=decode$3(i.subarray(s));return s+=T,x};let c=a(),d=DAG_PB_CODE$1;if(c===18?(c=0,s=0):d=a(),c!==0&&c!==1)throw new RangeError(`Invalid CID version ${c}`);const f=s,g=a(),y=a(),b=s+y,$=b-f;return{version:c,codec:d,multihashCode:g,digestSize:y,multihashSize:$,size:b}}static parse(i,s){const[a,c]=parseCIDtoBytes(i,s),d=CID.decode(c);if(d.version===0&&i[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache(d).set(a,i),d}}function parseCIDtoBytes(o,i){switch(o[0]){case"Q":{const s=i??base58btc;return[base58btc.prefix,s.decode(`${base58btc.prefix}${o}`)]}case base58btc.prefix:{const s=i??base58btc;return[base58btc.prefix,s.decode(o)]}case base32.prefix:{const s=i??base32;return[base32.prefix,s.decode(o)]}case base36.prefix:{const s=i??base36;return[base36.prefix,s.decode(o)]}default:{if(i==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[o[0],i.decode(o)]}}}function toStringV0(o,i,s){const{prefix:a}=s;if(a!==base58btc.prefix)throw Error(`Cannot string encode V0 in ${s.name} encoding`);const c=i.get(a);if(c==null){const d=s.encode(o).slice(1);return i.set(a,d),d}else return c}function toStringV1(o,i,s){const{prefix:a}=s,c=i.get(a);if(c==null){const d=s.encode(o);return i.set(a,d),d}else return c}const DAG_PB_CODE$1=112,SHA_256_CODE=18;function encodeCID(o,i,s){const a=encodingLength(o),c=a+encodingLength(i),d=new Uint8Array(c+s.byteLength);return encodeTo(o,d,0),encodeTo(i,d,a),d.set(s,c),d}const cidSymbol=Symbol.for("@ipld/js-cid/CID"),DAG_PB_CODE=112;function createLegacy(o){return CID.create(0,DAG_PB_CODE,o)}function create$1(o,i){return CID.create(1,o,i)}const MSB=128,REST=127,MSBALL=~REST,INT=Math.pow(2,31),encode=o=>{const i=[];let s=0;for(;o>=INT;)i[s++]=o&255|MSB,o/=128;for(;o&MSBALL;)i[s++]=o&255|MSB,o>>>=7;return i[s]=o|0,i},decode=(o,i)=>{let s=0;i=i||0;let a=0,c=i,d;const f=o.length;do{if(c>=f||a>49)throw new RangeError("Could not decode varint");d=o.get(c++),s+=a<28?(d&REST)<=MSB);return[s,c-i]},State={ReadHeaderLength:0,ReadHeader:1,ReadBlockLength:2,ReadBlock:3},CIDV0_BYTES={SHA2_256:18,LENGTH:32,DAG_PB:112};var xt;class CARReaderStream extends TransformStream{constructor(s,a){const c=new Uint8ArrayList;let d=0,f=d,g=8,y=State.ReadHeaderLength,b;const $=new Promise(x=>{b=x});super({transform(x,T){for(c.append(x);!(c.length{const[,i]=decode(o),[s,a]=decode(o,i);return i+a+s},encodeHeader=o=>{const i=encode$O({version:1,roots:o}),s=encode(i.length),a=new Uint8Array(s.length+i.length);return a.set(s,0),a.set(i,s.length),a},encodeBlock=o=>{const i=encode(o.cid.bytes.length+o.bytes.length),s=new Uint8Array(i.length+o.cid.bytes.length+o.bytes.length);return s.set(i),s.set(o.cid.bytes,i.length),s.set(o.bytes,i.length+o.cid.bytes.length),s};class CARWriterStream extends TransformStream{constructor(i=[],s,a){super({start:c=>c.enqueue(encodeHeader(i)),transform:(c,d)=>d.enqueue(encodeBlock(c))},s,a)}}async function indexShardedDAG(o,i,s){const a=create$3(o);for(const[c,d]of i.entries()){const f=s[c];a.shards.set(d.multihash,f)}return await a.archive()}const SHARD_SIZE=133169152;class ShardingStream extends TransformStream{constructor(i={}){const s=i.shardSize??SHARD_SIZE,a=s-headerEncodingLength();let c=[],d=null,f=new DigestMap,g=null,y=0;super({async transform(b,$){d!=null&&g!=null&&($.enqueue(await encodeCAR(d,g)),d=null,g=null);const x=blockHeaderEncodingLength(b),T=x+b.bytes.length;if(T>a)throw new Error(`block will cause CAR to exceed shard size: ${b.cid}`);c.length&&y+T>a&&(d=c,g=f,c=[],f=new DigestMap,y=0),c.push(b),f.set(b.cid.multihash,[headerEncodingLength()+y+x,b.bytes.length]),y+=T},async flush(b){d!=null&&g!=null&&b.enqueue(await encodeCAR(d,g));const $=c.at(-1);if($==null)return;const x=i.rootCID??$.cid,T=headerEncodingLength(x);if(T+y>s){const A=T+y-s,E=[];let S=0;for(;Sa.name)=>ascending(o,i,s);function ascending(o,i,s){const a=s(o),c=s(i);return a===c?0:aObject.assign(await encode$6(o,s),{slices:i});async function uploadFile(o,i,s={}){return await uploadBlockStream(o,createFileEncoderStream(i,s),s)}async function uploadDirectory(o,i,s={}){const{customOrder:a=!1}=s,c=a?i:[...i].sort(defaultFileComparator);return await uploadBlockStream(o,createDirectoryEncoderStream(c,s),s)}async function uploadCAR(o,i,s={}){const a=new BlockStream(i);return s.rootCID=s.rootCID??(await a.getRoots())[0],await uploadBlockStream(o,a,s)}async function uploadBlockStream(o,i,{pieceHasher:s=PieceHasher,...a}={}){const c=typeof o=="function"?o:()=>o,d=[],f=[];let g=null;if(await i.pipeThrough(new ShardingStream(a)).pipeThrough(new TransformStream({async transform(E,S){const _=new Uint8Array(await E.arrayBuffer()),C=await sha256$2.digest(_),B=await c([{can:ability$2,nb:input$8(C,_.length)}]);await add$2(B,C,_,a);const D=create$g(code,C);let I;if(s){const z=await s.digest(_);I=create$g(code$3,z);const K=create$g(code$3,C),G=await filecoinOffer({issuer:B.issuer,audience:B.audience,with:B.issuer.did(),proofs:B.proofs},K,I,a);if(G.out.error)throw new Error("failed to offer piece for aggregation into filecoin deal",{cause:G.out.error})}const{version:O,roots:N,size:L,slices:R}=E;S.enqueue({version:O,roots:N,size:L,cid:D,piece:I,slices:R})}})).pipeTo(new WritableStream({write(E){g=g||E.roots[0],f.push(E.cid),E.slices.set(E.cid.multihash,[0,E.size]),d.push(E.slices),a.onShardStored&&a.onShardStored(E)}})),!g)throw new Error("missing root CID");const y=await indexShardedDAG(g,f,d);if(!y.ok)throw new Error("failed to archive DAG index",{cause:y.error});const b=await sha256$2.digest(y.ok),$=create$g(code,b),[x,T,A]=await Promise.all([c([{can:ability$2,nb:input$8(b,y.ok.length)}]),c([{can:ability$1,nb:input$4($)}]),c([{can:ability,nb:input$3(g,f)}])]);return await add$2(x,b,y.ok,a),await add$1(T,$,a),await add(A,g,f,a),g}const accessServiceURL=new URL("https://up.web3.storage"),accessServicePrincipal=parse$2("did:web:web3.storage"),accessServiceConnection=connect({id:accessServicePrincipal,codec:outbound,channel:open$2({url:accessServiceURL,method:"POST"})}),uploadServiceURL=new URL("https://up.web3.storage"),uploadServicePrincipal=parse$2("did:web:web3.storage"),uploadServiceConnection=connect({id:uploadServicePrincipal,codec:outbound,channel:open$2({url:uploadServiceURL,method:"POST"})}),filecoinServiceURL=new URL("https://up.web3.storage"),filecoinServicePrincipal=parse$2("did:web:web3.storage"),filecoinServiceConnection=connect({id:filecoinServicePrincipal,codec:outbound,channel:open$2({url:filecoinServiceURL,method:"POST"})}),serviceConf={access:accessServiceConnection,upload:uploadServiceConnection,filecoin:filecoinServiceConnection};class Base{constructor(i,s={}){U(this,"_agent");U(this,"_serviceConf");this._serviceConf=s.serviceConf??serviceConf,this._agent=new Agent(i,{servicePrincipal:this._serviceConf.access.id,url:this._serviceConf.access.channel.url,connection:this._serviceConf.access}),this._receiptsEndpoint=s.receiptsEndpoint??receiptsEndpoint}get agent(){return this._agent}async _invocationConfig(i){const s=this._agent.currentSpace();if(!s)throw new Error("missing current space: use createSpace() or setCurrentSpace()");const a=this._agent.issuer,c=await this._agent.proofs(i.map(f=>({can:f,with:s}))),d=this._serviceConf.upload.id;return{issuer:a,with:s,proofs:c,audience:d}}}const unwrap=({ok:o,error:i})=>{if(i)throw i;return o};class AccessClient extends Base{async authorize(i,s){const a=fromEmail(i),c=unwrap(await request(this,{account:a})),d=unwrap(await c.claim(s));return await unwrap(await d.save()),d.proofs}async claim(i){const s=unwrap(await claim(this,i));return await unwrap(await s.save()),s.proofs}async request(i){return await request(this,i)}async delegate(i){return await delegate(this,i)}}const claim=async({agent:o},i)=>claim$1(o,i),request=async({agent:o},i)=>request$2(o,i),delegate=async({agent:o},i)=>delegate$1(o,i),{spaceAccess,accountAccess}=access;class PlanClient extends Base{async get(i,s){const a=await get({agent:this.agent},{...s,account:i});if(!a.ok)throw new Error(`failed ${get$c.can} invocation`,{cause:a.error});return a.ok}async set(i,s,a){const c=await set({agent:this.agent},{...a,account:i,product:s});if(!c.ok)throw new Error(`failed ${set$5.can} invocation`,{cause:c.error});return c.ok}async createAdminSession(i,s,a){const c=await createAdminSession({agent:this.agent},{...a,account:i,returnURL:s});if(!c.ok)throw new Error(`failed ${createAdminSession$1.can} invocation`,{cause:c.error});return c.ok}}const get=async({agent:o},{account:i,nonce:s,proofs:a=[]})=>(await o.invokeAndExecute(get$c,{with:i,proofs:a,nonce:s})).out,set=async({agent:o},{account:i,product:s,nonce:a,proofs:c=[]})=>(await o.invokeAndExecute(set$5,{with:i,nb:{product:s},nonce:a,proofs:c})).out,createAdminSession=async({agent:o},{account:i,returnURL:s,nonce:a,proofs:c=[]})=>(await o.invokeAndExecute(createAdminSession$1,{with:i,proofs:c,nonce:a,nb:{returnURL:s}})).out;class SubscriptionClient extends Base{async list(i,s){const a=await list$1({agent:this.agent},{...s,account:i});if(!a.ok)throw new Error(`failed ${list$6.can} invocation`,{cause:a.error});return a.ok}}const list$1=async({agent:o},{account:i,nonce:s,proofs:a=[]})=>(await o.invokeAndExecute(list$6,{with:i,proofs:a,nb:{},nonce:s})).out,list=({agent:o},{account:i}={})=>{const s={with:i??/did:mailto:.*/,can:"*"},a=o.proofs([s]),c={},d={};for(const f of a){const g=allows(f);for(const[y,b]of Object.entries(g)){if(AccountDID.is(y)&&b["*"]){const $=y;(c[$]||(c[$]=new Account({id:$,agent:o,proofs:[]}))).addProof(f)}for(const $ of b["ucan/attest"]||[]){const x=$.proof;x&&(d[`${x}`]=f)}}}for(const f of Object.values(c))for(const g of f.proofs){const y=d[`${g.cid}`];y&&f.addProof(y)}return c},login=async({agent:o},i,s={})=>{const a=fromEmail(i),c=list({agent:o},{account:a})[a];if(c)return{ok:c};const d=await request({agent:o},{account:a,access:accountAccess}),{ok:f,error:g}=d;if(g)return{error:g};{const{ok:y,error:b}=await f.claim({signal:s.signal});return b?{error:b}:{ok:new Account({id:a,proofs:y.proofs,agent:o})}}};class Account{constructor(i){this.model=i,this.plan=new AccountPlan(i)}get agent(){return this.model.agent}get proofs(){return this.model.proofs}did(){return this.model.id}toEmail(){return toEmail(this.did())}addProof(i){this.proofs.push(i)}toJSON(){return{id:this.did(),proofs:this.proofs.sort((i,s)=>i.cid.toString().localeCompare(s.cid.toString())).map(i=>i.toJSON())}}provision(i,s={}){return add$7(this.agent,{...s,account:this.did(),consumer:i,proofs:this.proofs})}async save({agent:i=this.agent}={}){return await importAuthorization(i,this)}}class AccountPlan{constructor(i){this.model=i}async get(i){return await get(this.model,{...i,account:this.model.id,proofs:this.model.proofs})}async set(i,s){return await set(this.model,{...s,account:this.model.id,product:i,proofs:this.model.proofs})}async wait(i){var d;const s=Date.now(),a=(i==null?void 0:i.interval)||1e3,c=(i==null?void 0:i.timeout)||60*15*1e3;for(;;){const f=await this.get();if(f.ok)return f.ok;if(f.error)throw new Error(`Error retrieving payment plan: ${f.error}`);if(Date.now()-s>c)throw new Error("Timeout: Payment plan selection took too long.");if((d=i==null?void 0:i.signal)!=null&&d.aborted)throw new Error("Aborted: Payment plan selection was aborted.");console.log("Waiting for payment plan to be selected..."),await new Promise(g=>setTimeout(g,a))}}async createAdminSession(i,s,a){return await createAdminSession(this.model,{...a,account:i,returnURL:s})}async subscriptions(i){return await list$1(this.model,{...i,account:this.model.id,proofs:this.model.proofs})}}class UsageClient extends Base{async report(i,s,a){const c=await report({agent:this.agent},{...a,space:i,period:s});if(!c.ok)throw new Error(`failed ${report$1.can} invocation`,{cause:c.error});return c.ok}}const report=async({agent:o},{space:i,period:s,nonce:a,proofs:c=[]})=>(await o.invokeAndExecute(report$1,{with:i,proofs:c,nonce:a,nb:{period:{from:Math.floor(s.from.getTime()/1e3),to:Math.ceil(s.to.getTime()/1e3)}}})).out;var Qe;class Space{constructor(i){Y(this,Qe);Q(this,Qe,i),this.usage=new StorageUsage(i)}get name(){var i;return String(((i=F(this,Qe).meta)==null?void 0:i.name)??"")}did(){return F(this,Qe).id}meta(){return F(this,Qe).meta}}Qe=new WeakMap;var st;class StorageUsage{constructor(i){Y(this,st);Q(this,st,i)}async get(){const{agent:i}=F(this,st),s=F(this,st).id,a=new Date,c={from:startOfLastMonth(a),to:a},d=await report({agent:i},{space:s,period:c});if(d.error)return d;const f=i.connection.id.did(),g=d.ok[f];return{ok:(g==null?void 0:g.size.final)==null?void 0:BigInt(g.size.final)}}}st=new WeakMap;const startOfMonth=o=>{const i=new Date(o);return i.setUTCDate(1),i.setUTCHours(0),i.setUTCMinutes(0),i.setUTCSeconds(0),i.setUTCMilliseconds(0),i},startOfLastMonth=o=>{const i=startOfMonth(o);return i.setUTCMonth(i.getUTCMonth()-1),i};class BlobClient extends Base{async add(i,s={}){const a=await this._invocationConfig([add$4.can]);s.connection=this._serviceConf.upload;const c=new Uint8Array(await i.arrayBuffer()),d=await sha256$6.digest(c);return{digest:d,...await add$2(a,d,c,s)}}async list(i={}){const s=await this._invocationConfig([list$5.can]);return i.connection=this._serviceConf.upload,list$3(s,i)}async remove(i,s={}){const a=await this._invocationConfig([remove$5.can]);return s.connection=this._serviceConf.upload,remove$3(a,i,s)}async get(i,s={}){const a=await this._invocationConfig([get$b.can]);return s.connection=this._serviceConf.upload,get$8(a,i,s)}}class IndexClient extends Base{async add(i,s={}){const a=await this._invocationConfig([add$5.can]);return s.connection=this._serviceConf.upload,add$1(a,i,s)}}class StoreClient extends Base{async add(i,s={}){const a=await this._invocationConfig([add$a.can]);return s.connection=this._serviceConf.upload,add$3(a,i,s)}async get(i,s={}){const a=await this._invocationConfig([get$h.can]);return s.connection=this._serviceConf.upload,get$a(a,i,s)}async list(i={}){const s=await this._invocationConfig([list$9.can]);return i.connection=this._serviceConf.upload,list$4(s,i)}async remove(i,s={}){const a=await this._invocationConfig([remove$8.can]);return s.connection=this._serviceConf.upload,remove$4(a,i,s)}}class UploadClient extends Base{async add(i,s,a={}){const c=await this._invocationConfig([add$9.can]);return a.connection=this._serviceConf.upload,add(c,i,s,a)}async get(i,s={}){const a=await this._invocationConfig([get$g.can]);return s.connection=this._serviceConf.upload,get$7(a,i,s)}async list(i={}){const s=await this._invocationConfig([list$8.can]);return i.connection=this._serviceConf.upload,list$2(s,i)}async remove(i,s={}){const a=await this._invocationConfig([remove$7.can]);return s.connection=this._serviceConf.upload,remove$2(a,i,s)}}class SpaceClient extends Base{async info(i,s){return await this._agent.getSpaceInfo(i,s)}}class FilecoinClient extends Base{async offer(i,s,a){const c=await this._invocationConfig([filecoinOffer$1.can]);return filecoinOffer(c,i,s,{...a,connection:this._serviceConf.filecoin})}async info(i,s){const a=await this._invocationConfig([filecoinInfo$1.can]);return filecoinInfo(a,i,{...s,connection:this._serviceConf.filecoin})}}class CouponAPI extends Base{async redeem(i,s={}){const{agent:a}=this,c=unwrap(await extract(i));return unwrap(await redeem(c,{...s,agent:a}))}async issue({proofs:i=[],...s}){const{agent:a}=this;return await issue({...s,issuer:a.issuer,proofs:[...i,...a.proofs(s.capabilities)]})}}const extract=async o=>{const{ok:i,error:s}=await extract$1(o);return i?ok(new Coupon({proofs:[i]})):error$1(s)},archive=async o=>{const[i]=o.proofs;return await archive$2(i)},issue=async({password:o="",...i})=>{const s=await deriveSigner(o),a=await delegate$3({...i,audience:s});return new Coupon({proofs:[a]})},redeem=async(o,{agent:i,password:s=""})=>{const a=await deriveSigner(s),[c]=o.proofs;if(c.audience.did()!==a.did())return error$1(new RangeError(s===""?"Extracting account requires a password":"Provided password is invalid"));{const d=await delegate$3({issuer:a,audience:i,capabilities:c.capabilities,expiration:c.expiration,notBefore:c.notBefore,proofs:[c]});return ok(new GrantedAccess({agent:i,proofs:[d]}))}},deriveSigner=async o=>{const{digest:i}=await sha256$4.digest(new TextEncoder().encode(o));return await derive(i)};class Coupon{constructor(i){this.model=i}get proofs(){return this.model.proofs}redeem(i,s={}){return redeem(this,{...s,agent:i})}archive(){return archive(this)}}class Client extends Base{constructor(i,s){super(i,s),this.capability={access:new AccessClient(i,s),filecoin:new FilecoinClient(i,s),index:new IndexClient(i,s),plan:new PlanClient(i,s),space:new SpaceClient(i,s),blob:new BlobClient(i,s),store:new StoreClient(i,s),subscription:new SubscriptionClient(i,s),upload:new UploadClient(i,s),usage:new UsageClient(i,s)},this.coupon=new CouponAPI(i,s)}did(){return this._agent.did()}async authorize(i,s){await this.capability.access.authorize(i,s)}async login(i,s={}){const a=unwrap(await login(this,i,s));return unwrap(await a.save()),a}accounts(){return list(this)}async uploadFile(i,s={}){const a=await this._invocationConfig([add$4.can,add$5.can,filecoinOffer$1.can,add$9.can]);return s.connection=this._serviceConf.upload,uploadFile(a,i,s)}async uploadDirectory(i,s={}){const a=await this._invocationConfig([add$4.can,add$5.can,filecoinOffer$1.can,add$9.can]);return s.connection=this._serviceConf.upload,uploadDirectory(a,i,s)}async uploadCAR(i,s={}){const a=await this._invocationConfig([add$4.can,add$5.can,filecoinOffer$1.can,add$9.can]);return s.connection=this._serviceConf.upload,uploadCAR(a,i,s)}async getReceipt(i){const s=new URL(this._receiptsEndpoint).toString();return poll(i,{receiptsEndpoint:s})}defaultProvider(){return this._agent.connection.id.did()}currentSpace(){const i=this._agent,s=i.currentSpace();if(!s)return;const a=i.spaces.get(s);return new Space({id:s,meta:a,agent:i})}async setCurrentSpace(i){await this._agent.setCurrentSpace(i)}spaces(){return[...this._agent.spaces].map(([i,s])=>new Space({id:i,meta:s,agent:this._agent}))}async createSpace(i,s={}){const a=await this._agent.createSpace(i),c=s.account;if(c){const d=await c.provision(a.did());if(d.error)throw new Error(`failed to provision account: ${d.error.message}`,{cause:d.error});await a.save();const f=await a.createRecovery(c.did()),g=await this.capability.access.delegate({space:a.did(),delegations:[f]});if(g.error)throw new Error(`failed to authorize recovery account: ${g.error.message}`,{cause:g.error})}return a}async shareSpace(i,s,a={abilities:["space/*","store/*","upload/*","access/*","usage/*","filecoin/offer","filecoin/info","filecoin/accept","filecoin/submit"],expiration:1/0}){const{abilities:c,...d}=a,f=this.agent.currentSpace();try{await this.agent.setCurrentSpace(s);const{root:g,blocks:y}=await this.agent.delegate({...d,abilities:c,audience:{did:()=>fromEmail(email(i))},audienceMeta:a.audienceMeta??{}}),b=new AgentDelegation(g,y,{audience:i}),$=await this.capability.access.delegate({space:s,delegations:[b]});if($.error)throw new Error(`failed to share space with ${i}: ${$.error.message}`,{cause:$.error});return b}finally{f&&f!==s&&await this.agent.setCurrentSpace(f)}}async addSpace(i){return await this._agent.importSpaceFromDelegation(i)}proofs(i){return this._agent.proofs(i)}async addProof(i){await this._agent.addProof(i)}delegations(i){const s=[];for(const{delegation:a,meta:c}of this._agent.delegationsWithMeta(i))s.push(new AgentDelegation(a.root,a.blocks,c));return s}async createDelegation(i,s,a={}){const c=a.audienceMeta??{name:"agent",type:"device"},{root:d,blocks:f}=await this._agent.delegate({...a,abilities:s,audience:i,audienceMeta:c});return new AgentDelegation(d,f,{audience:c})}async revokeDelegation(i,s={}){return this._agent.revoke(i,{proofs:s.proofs})}async remove(i,s={}){var c;if(!s.shards){await this.capability.upload.remove(i);return}const a=await this.capability.upload.get(i);(c=a.shards)!=null&&c.length&&await Promise.allSettled(a.shards.map(async d=>{var f;try{const g=await this.capability.blob.remove(d.multihash);g.ok&&g.ok.size===0&&await this.capability.store.remove(d)}catch(g){if(((f=g==null?void 0:g.cause)==null?void 0:f.name)!=="StoreItemNotFound")throw new Error(`failed to remove shard: ${d}`,{cause:g})}})),await this.capability.upload.remove(i)}}new Set(abilitiesAsStrings);async function create(o={}){const i=o.store??new StoreIndexedDB("w3up-client"),s=await i.load();if(s){const d=AgentData.fromExport(s,{store:i});if(o.principal&&d.principal.did()!==o.principal.did())throw new Error(`store cannot be used with ${o.principal.did()}, stored principal and passed principal must match`);return new Client(d,o)}const a=o.principal??await generate(),c=await AgentData.create({principal:a},{store:i});return new Client(c,o)}const toHTTP=o=>o.replace(/^ipfs:\/\//,"https://w3s.link/ipfs/"),upload=async o=>{const i=await create();console.debug({"W3Up Client":i,accounts:i.accounts(),did:i.did()});const s=await fetch("http://localhost:3000/ucan",{method:"POST",body:JSON.stringify({did:i.did()})}),{delegation:a}=await s.json(),{ok:c,error:d}=await extract$1(new Uint8Array(a));if(!c)throw new Error("Failed to extract delegation.",{cause:d});const f=await i.addSpace(c);return i.setCurrentSpace(f.did()),(await i.uploadDirectory(o)).toString()},Reward=({image:o})=>jsxRuntimeExports.jsx("div",{id:"reward",className:"flex flex-col ml-4 mt-8 md:mt-1",children:jsxRuntimeExports.jsxs("div",{className:"card rounded-sm bg-secondary/25 h-auto max-w-md mr-4 mx-auto",children:[jsxRuntimeExports.jsx("h1",{className:"text-3xl font-bold text-center my-4 mx-2",children:"Completion NFT"}),jsxRuntimeExports.jsx("img",{src:toHTTP(o),alt:"Soulbound NFT",className:"w-full h-full object-contain pb-4 px-4"})]})}),abi=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"editor",type:"address"},{indexed:!1,internalType:"uint256[]",name:"questIdList",type:"uint256[]"},{components:[{internalType:"bool",name:"paused",type:"bool"},{internalType:"bool",name:"optional",type:"bool"},{internalType:"bool",name:"skipReview",type:"bool"}],indexed:!1,internalType:"struct IQuestChain.QuestDetails[]",name:"questDetails",type:"tuple[]"}],name:"ConfiguredQuests",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint8",name:"version",type:"uint8"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"editor",type:"address"},{indexed:!1,internalType:"string",name:"details",type:"string"}],name:"QuestChainEdited",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"details",type:"string"},{indexed:!1,internalType:"string[]",name:"quests",type:"string[]"},{indexed:!1,internalType:"bool",name:"paused",type:"bool"}],name:"QuestChainInit",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"tokenURI",type:"string"}],name:"QuestChainTokenURIUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"reviewer",type:"address"},{indexed:!1,internalType:"address[]",name:"questerList",type:"address[]"},{indexed:!1,internalType:"uint256[]",name:"questIdList",type:"uint256[]"},{indexed:!1,internalType:"bool[]",name:"successList",type:"bool[]"},{indexed:!1,internalType:"string[]",name:"detailsList",type:"string[]"}],name:"QuestProofsReviewed",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"quester",type:"address"},{indexed:!1,internalType:"uint256[]",name:"questIdList",type:"uint256[]"},{indexed:!1,internalType:"string[]",name:"proofList",type:"string[]"}],name:"QuestProofsSubmitted",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"string[]",name:"detailsList",type:"string[]"}],name:"QuestsCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"editor",type:"address"},{indexed:!1,internalType:"uint256[]",name:"questIdList",type:"uint256[]"},{indexed:!1,internalType:"string[]",name:"detailsList",type:"string[]"}],name:"QuestsEdited",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"previousAdminRole",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"newAdminRole",type:"bytes32"}],name:"RoleAdminChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleGranted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleRevoked",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"limiterContract",type:"address"}],name:"SetLimiter",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{inputs:[],name:"ADMIN_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"DEFAULT_ADMIN_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"EDITOR_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"REVIEWER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"burnToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256[]",name:"_questIdList",type:"uint256[]"},{components:[{internalType:"bool",name:"paused",type:"bool"},{internalType:"bool",name:"optional",type:"bool"},{internalType:"bool",name:"skipReview",type:"bool"}],internalType:"struct IQuestChain.QuestDetails[]",name:"_questDetails",type:"tuple[]"}],name:"configureQuests",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string[]",name:"_detailsList",type:"string[]"}],name:"createQuests",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"_details",type:"string"}],name:"edit",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256[]",name:"_questIdList",type:"uint256[]"},{internalType:"string[]",name:"_detailsList",type:"string[]"}],name:"editQuests",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"}],name:"getRoleAdmin",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getTokenURI",outputs:[{internalType:"string",name:"uri",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_role",type:"bytes32"},{internalType:"address",name:"_account",type:"address"}],name:"grantRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"hasRole",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"address[]",name:"owners",type:"address[]"},{internalType:"address[]",name:"admins",type:"address[]"},{internalType:"address[]",name:"editors",type:"address[]"},{internalType:"address[]",name:"reviewers",type:"address[]"},{internalType:"string[]",name:"quests",type:"string[]"},{internalType:"bool",name:"paused",type:"bool"},{internalType:"string",name:"details",type:"string"},{internalType:"string",name:"tokenURI",type:"string"}],internalType:"struct QuestChainCommons.QuestChainInfo",name:"_info",type:"tuple"}],name:"init",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"limiterContract",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"mintToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"premium",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"questChainFactory",outputs:[{internalType:"contract IQuestChainFactory",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"questChainId",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"questChainToken",outputs:[{internalType:"contract IQuestChainToken",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"questCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"questDetails",outputs:[{internalType:"bool",name:"paused",type:"bool"},{internalType:"bool",name:"optional",type:"bool"},{internalType:"bool",name:"skipReview",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_quester",type:"address"},{internalType:"uint256",name:"_questId",type:"uint256"}],name:"questStatus",outputs:[{internalType:"enum IQuestChain.Status",name:"status",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"renounceRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address[]",name:"_questerList",type:"address[]"},{internalType:"uint256[]",name:"_questIdList",type:"uint256[]"},{internalType:"bool[]",name:"_successList",type:"bool[]"},{internalType:"string[]",name:"_detailsList",type:"string[]"}],name:"reviewProofs",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"_role",type:"bytes32"},{internalType:"address",name:"_account",type:"address"}],name:"revokeRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_limiterContract",type:"address"}],name:"setLimiter",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"_tokenURI",type:"string"}],name:"setTokenURI",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256[]",name:"_questIdList",type:"uint256[]"},{internalType:"string[]",name:"_proofList",type:"string[]"}],name:"submitProofs",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"upgrade",outputs:[],stateMutability:"nonpayable",type:"function"}],CHAIN=10,Alert=({children:o})=>jsxRuntimeExports.jsxs("div",{role:"alert",className:"alert alert-warning flex items-center mt-10",children:[jsxRuntimeExports.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6 shrink-0 stroke-current",fill:"none",viewBox:"0 0 24 24",children:jsxRuntimeExports.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),o]}),Submission=({name:o="Submission",contract:i,index:s})=>{const{address:a}=useAccount(),c=useChainId(),d=React__default.useRef(null),[f,g]=reactExports.useState(!1),[y,b]=reactExports.useState({}),$=({type:O,error:N})=>{b(L=>({...L,[O]:N}))},{data:x,writeContract:T,isPending:A}=useWriteContract(),E=useConfig();reactExports.useEffect(()=>{if(E)return watchChainId(E,{onChange(O){O!==CHAIN&&!y.chain&&$({type:"chain",error:jsxRuntimeExports.jsx("h3",{className:"flex text-center items-center justify-center",children:"Please switch to the Optimism network to continue."})})}})},[E]),reactExports.useEffect(()=>{x&&_t.success(jsxRuntimeExports.jsxs("p",{children:["Successfully submitted transaction",jsxRuntimeExports.jsxs("a",{href:`https://optimistic.etherscan.io/tx/${x}`,className:"mx-1 whitespace-nowrap text-primary hover:text-secondary",target:"_blank",children:[x.substring(0,8),"…",x.slice(-6)]}),"to the Quest Chain contract at",jsxRuntimeExports.jsxs("a",{href:`https://optimistic.etherscan.io/address/${i}`,className:"ml-1 whitespace-nowrap text-primary hover:text-secondary",target:"_blank",children:[i.substring(0,6),"…",i.slice(-4)]}),"."]}),{duration:12e3,position:"bottom-center",style:{width:"45ch"}})},[x]);const{isLoading:S,isSuccess:_}=useWaitForTransactionReceipt({hash:x});!a&&!y.account?$({type:"account",error:jsxRuntimeExports.jsxs("h3",{className:"flex text-center items-center justify-center",children:["Please",jsxRuntimeExports.jsx("div",{className:"mx-2",children:jsxRuntimeExports.jsx("w3m-button",{size:"sm"})}),"to submit a proof."]})}):a&&y.account&&$({type:"account",error:null}),c!==CHAIN&&!y.chain?$({type:"chain",error:jsxRuntimeExports.jsx("h3",{className:"flex text-center items-center justify-center",children:"Please switch to the Optimism network to continue."})}):c===CHAIN&&y.chain&&$({type:"chain",error:null});const C=Object.values(y).filter(Boolean);if(C.length>0)return C.map((O,N)=>jsxRuntimeExports.jsx(Alert,{children:O},N));const B=React__default.lazy(()=>__vitePreload(()=>import("./MarkdownEditor-BZjgjvzZ.js").then(O=>O.M),__vite__mapDeps([0,1,2]))),D="Submit Proof",I=S?"Confirming…":A?"Transaction Pending…":f?"Saving to IPFS…":_?"¡Done: Submitted!":D;return jsxRuntimeExports.jsxs(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("h3",{children:"Loading Submission Editor…"}),children:[jsxRuntimeExports.jsx(B,{editorRef:d,markdown:"",className:"dark-theme dark-editor content mt-10"}),jsxRuntimeExports.jsx("button",{onClick:async()=>{var N;const O=(N=d.current)==null?void 0:N.getMarkdown();if(!O)throw new Error(`Invalid \`markdown\`: "${O}".`);g(!0);try{const L=new Blob([JSON.stringify({name:o,description:O})],{type:"application/json"}),R=await upload([new File([L],"submission.json")]);_t.success(jsxRuntimeExports.jsxs("p",{children:["Successfully uploaded your response submission to",jsxRuntimeExports.jsx("a",{href:"https://web3.storage",target:"_blank",className:"mx-1 whitespace-nowrap text-primary hover:text-secondary",children:"Web3.Storage"}),"at",jsxRuntimeExports.jsxs("a",{href:`https://w3s.link/ipfs/${R}`,target:"_blank",className:"ml-1 whitespace-nowrap text-primary hover:text-secondary",children:["ipfs://",R.substring(0,6),"…",R.slice(-4)]}),"."]}),{duration:15e3,position:"bottom-center",style:{width:"45ch"}}),T({address:i,abi,functionName:"submitProofs",args:[[s],[R]]})}catch(L){console.error({error:L}),_t.error(L.message)}finally{g(!1)}},disabled:I!==D,className:"btn btn-wide text-primary my-6",children:I})]})},questChainQueryDocument=gql` +`),Provider$1=match$1({method:"web"}),add$8=capability({can:"provider/add",with:AccountDID$1,nb:struct({provider:Provider$1,consumer:SpaceDID$1}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.provider,i.nb.provider,"provider"))||and$2(equal(o.nb.consumer,i.nb.consumer,"consumer"))||ok({})}),Provider$2=Object.freeze(Object.defineProperty({__proto__:null,AccountDID:AccountDID$1,Provider:Provider$1,add:add$8},Symbol.toStringTag,{value:"Module"})),{Provider:ProviderDID$3,AccountDID}=Provider$2,add$7=async(o,{account:i,consumer:s,provider:a=o.connection.id.did(),proofs:c})=>{if(!ProviderDID$3.is(a))throw new Error(`Unable to determine provider from agent.connection.id did ${a}. expected a did:web:`);const{out:d}=await o.invokeAndExecute(add$8,{with:i,nb:{provider:a,consumer:s},proofs:c});return d},generate$1=async({name:o,agent:i})=>{const{signer:s}=await generate$2();return new OwnedSpace({signer:s,name:o,agent:i})},fromMnemonic=async(o,{name:i,agent:s})=>{const a=mnemonicToEntropy(o,wordlist),c=await derive(a);return new OwnedSpace({signer:c,name:i,agent:s})},toMnemonic=({signer:o})=>{const i=o.secret;return entropyToMnemonic(i,wordlist)},createRecovery=(o,i)=>createAuthorization(o,{agent:o.signer.withDID(i),access:accountAccess$1,expiration:1/0}),SESSION_LIFETIME=60*60*24*365,createAuthorization=async({signer:o,name:i},{agent:s,access:a=spaceAccess$1,expiration:c=now()+SESSION_LIFETIME})=>await delegate$3({issuer:o,audience:s,capabilities:toCapabilities({[o.did()]:a}),...c?{expiration:c}:{},facts:[{space:{name:i}}]}),toCapabilities=o=>{const i=[];for(const[s,a]of Object.entries(o)){const c=Object.entries(a);for(const[d,f]of c)f&&i.push({can:d,with:s})}return i};class OwnedSpace{constructor(i){this.model=i}get signer(){return this.model.signer}get name(){return this.model.name}did(){return this.signer.did()}withName(i){return new OwnedSpace({signer:this.signer,name:i})}async save({agent:i=this.model.agent}={}){if(!i)return fail("Please provide an agent to save the space into");const s=await createAuthorization(this,{agent:i});return await i.importSpaceFromDelegation(s),await i.setCurrentSpace(this.did()),{ok:{}}}provision({proofs:i},{agent:s=this.model.agent}={}){return s?provision(this,{proofs:i,agent:s}):fail("Please provide an agent to save the space into")}async createRecovery(i){return createRecovery(this,i)}createAuthorization(i,s){return createAuthorization(this,{...s,agent:i})}toMnemonic(){return toMnemonic(this)}}const SpaceDID=match$1({method:"key"}),fromDelegation=o=>{var a;const i=SpaceDID.read(o.capabilities[0].with);if(i.error)throw Object.assign(new Error(`Invalid delegation, expected capabilities[0].with to be DID, ${i.error}`),{cause:i.error});const s=((a=o.facts[0])==null?void 0:a.space)??{};return new SharedSpace({id:i.ok,delegation:o,meta:s})},provision=async(o,{proofs:i,agent:s})=>{const[a]=i[0].capabilities,{ok:c,error:d}=AccountDID.read(a.with);return d?error$1(d):await add$7(s,{consumer:o.did(),account:c,proofs:i})};class SharedSpace{constructor(i){this.model=i}get delegation(){return this.model.delegation}get meta(){return this.model.meta}get name(){return this.meta.name??""}did(){return this.model.id}withName(i){return new SharedSpace({...this.model,meta:{...this.meta,name:i}})}}function isExpired(o){return o.expiration===void 0||o.expiration<=Math.floor(Date.now()/1e3)}function isTooEarly(o){return o.notBefore?o.notBefore>Math.floor(Date.now()/1e3):!1}function canDelegateCapability(o,i){const s=allows(o);for(const[a,c]of Object.entries(s))if(matchResource(a,i.with)){const d=Object.keys(c);for(const f of d)if(canDelegateAbility(f,i.can))return!0}return!1}const matchResource=(o,i)=>i==="ucan:*"?!0:typeof i=="string"?o===i:i.test(o),_globalReference=globalThis||window||self,webcrypto=_globalReference.crypto,tagWith=(o,i)=>{const s=encodingLength$7(o),a=new Uint8Array(i.byteLength+s);return encodeTo$7(o,a,0),a.set(i,s),a},untagWith=(o,i,s=0)=>{const a=s!==0?i.subarray(s):i,[c,d]=decode$C(a);if(c!==o)throw new Error(`Expected multiformat with 0x${o.toString(16)} tag instead got 0x${c.toString(16)}`);return new Uint8Array(a.buffer,a.byteOffset+d)},TAG_SIZE$1=1,INT_TAG=2,BITSTRING_TAG=3,OCTET_STRING_TAG=4,SEQUENCE_TAG=48,UNUSED_BIT_PAD=0,encodeDERLength=o=>{if(o<=127)return new Uint8Array([o]);const i=[];for(;o!==0;)i.push(o&255),o=o>>>8;return i.reverse(),new Uint8Array([128|i.length&255,...i])},readDERLength=(o,i=0)=>{if(!(o[i]&128))return{number:o[i],consumed:1};const s=o[i]&127;if(o.length{const a=into(o,i,s);return a.position+a.length},into=(o,i,s)=>{const a=o[s];if(a!==i)throw new Error(`ASN parsing error: Expected tag 0x${i.toString(16)} at position ${s}, but got 0x${a.toString(16)}.`);const c=readDERLength(o,s+TAG_SIZE$1);return{position:s+TAG_SIZE$1+c.consumed,length:c.number}},encodeBitString=o=>{const i=encodeDERLength(o.byteLength+1),s=new Uint8Array(TAG_SIZE$1+i.byteLength+1+o.byteLength);let a=0;return s[a]=BITSTRING_TAG,a+=TAG_SIZE$1,s.set(i,a),a+=i.byteLength,s[a]=UNUSED_BIT_PAD,a+=1,s.set(o,a),s},encodeOctetString=o=>{const i=encodeDERLength(o.byteLength),s=new Uint8Array(TAG_SIZE$1+i.byteLength+o.byteLength);let a=0;return s[a]=OCTET_STRING_TAG,a+=TAG_SIZE$1,s.set(i,a),a+=i.byteLength,s.set(o,a),s},encodeSequence=o=>{let i=0;for(const d of o)i+=d.byteLength;const s=encodeDERLength(i),a=new Uint8Array(TAG_SIZE$1+s.byteLength+i);let c=0;a[c]=SEQUENCE_TAG,c+=TAG_SIZE$1,a.set(s,c),c+=s.byteLength;for(const d of o)a.set(d,c),c+=d.byteLength;return a},readSequence=(o,i=0)=>{const{position:s,length:a}=into(o,SEQUENCE_TAG,i);return new Uint8Array(o.buffer,o.byteOffset+s,a)},encodeInt=o=>{const i=o.byteLength===0||o[0]&128?1:0,s=encodeDERLength(o.byteLength+i),a=new Uint8Array(TAG_SIZE$1+s.byteLength+o.byteLength+i);let c=0;return a[c]=INT_TAG,c+=TAG_SIZE$1,a.set(s,c),c+=s.byteLength,i>0&&(a[c]=UNUSED_BIT_PAD,c+=i),a.set(o,c),a},enterSequence=(o,i=0)=>into(o,SEQUENCE_TAG,i).position,skipSequence=(o,i=0)=>skip(o,SEQUENCE_TAG,i),skipInt=(o,i=0)=>skip(o,INT_TAG,i),readBitString=(o,i=0)=>{const{position:s,length:a}=into(o,BITSTRING_TAG,i),c=o[s];if(c!==UNUSED_BIT_PAD)throw new Error(`Can not read bitstring, expected length to be multiple of 8, but got ${c} unused bits in last byte.`);return new Uint8Array(o.buffer,o.byteOffset+s+1,a-1)},readInt$1=(o,i=0)=>{const{position:s,length:a}=into(o,INT_TAG,i);let c=0;for(;o[s+c]===0;)c++;return new Uint8Array(o.buffer,o.byteOffset+s+c,a-c)},readOctetString=(o,i=0)=>{const{position:s,length:a}=into(o,OCTET_STRING_TAG,i);return new Uint8Array(o.buffer,o.byteOffset+s,a)},readSequenceWith=(o,i,s=0)=>{const a=[],c=readSequence(i,s);let d=0;for(const f of o){const g=f(c,d);a.push(g),d=g.byteOffset+g.byteLength-c.byteOffset}return a},SPKI_PARAMS_ENCODED=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),encode$n=o=>encodeSequence([SPKI_PARAMS_ENCODED,encodeBitString(o)]),decode$y=o=>{const i=enterSequence(o,0),s=skipSequence(o,i);return readBitString(o,s)},PKSC8_HEADER=new Uint8Array([2,1,0,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),decode$x=o=>{let i=0;return i=enterSequence(o,i),i=skipInt(o,i),i=skipSequence(o,i),readOctetString(o,i)},encode$m=o=>encodeSequence([PKSC8_HEADER,encodeOctetString(o)]),encode$l=({n:o,e:i})=>encodeSequence([encodeInt(o),encodeInt(i)]),decode$w=(o,i=0)=>{const[s,a,c,d,f,g,y,b,$]=readSequenceWith([readInt$1,readInt$1,readInt$1,readInt$1,readInt$1,readInt$1,readInt$1,readInt$1,readInt$1],o,i);return{v:s,n:a,e:c,d,p:f,q:g,dp:y,dq:b,qi:$}},name$6="RSA",code$8=4869,verifierCode=4613,signatureCode=RS256,signatureAlgorithm="RS256",ALG="RSASSA-PKCS1-v1_5",HASH_ALG="SHA-256",KEY_SIZE=2048,SALT_LENGTH=128,IMPORT_PARAMS={name:ALG,hash:{name:HASH_ALG}},generate=async({size:o=KEY_SIZE,extractable:i=!1}={})=>{const{publicKey:s,privateKey:a}=await webcrypto.subtle.generateKey({name:ALG,modulusLength:o,publicExponent:new Uint8Array([1,0,1]),hash:{name:HASH_ALG}},i,["sign","verify"]),c=await webcrypto.subtle.exportKey("spki",s),d=tagWith(verifierCode,decode$y(new Uint8Array(c))),f=new RSAVerifier({bytes:d,publicKey:s});if(i){const g=await webcrypto.subtle.exportKey("pkcs8",a),y=tagWith(code$8,decode$x(new Uint8Array(g)));return new ExtractableRSASigner({privateKey:a,bytes:y,verifier:f})}else return new UnextractableRSASigner({privateKey:a,verifier:f})},from$g=({id:o,keys:i})=>{if(o.startsWith("did:key:")){const s=o,a=i[s];return a instanceof Uint8Array?decode$v(a):new UnextractableRSASigner({privateKey:a,verifier:RSAVerifier.parse(s)})}else throw new TypeError(`RSA can not import from ${o} archive, try generic Signer instead`)},or$9=o=>or$b({from:from$g},o),decode$v=o=>{const i=decode$w(untagWith(code$8,o)),s=tagWith(verifierCode,encode$l(i));return new ExtractableRSASigner({bytes:o,privateKey:webcrypto.subtle.importKey("pkcs8",encode$m(untagWith(code$8,o)),IMPORT_PARAMS,!0,["sign"]),verifier:RSAVerifier.decode(s)})};class RSAVerifier{constructor({publicKey:i,bytes:s}){this.publicKey=i,this.bytes=s}withDID(i){return withDID$1(this,i)}toDIDKey(){return this.did()}static decode(i){return new this({bytes:i,publicKey:webcrypto.subtle.importKey("spki",encode$n(untagWith(verifierCode,i)),IMPORT_PARAMS,!0,["verify"])})}static parse(i){return RSAVerifier.decode(parse$2(i))}static or(i){return or$c(this,i)}get code(){return verifierCode}get signatureCode(){return signatureCode}get signatureAlgorithm(){return signatureAlgorithm}did(){return`did:key:${base58btc$5.encode(this.bytes)}`}async verify(i,s){return s.code!==signatureCode?!1:webcrypto.subtle.verify({name:ALG,hash:{name:HASH_ALG}},await this.publicKey,s.raw,i)}}class RSASigner{constructor({privateKey:i,verifier:s}){this.verifier=s,this.privateKey=i}get signer(){return this}get code(){return code$8}get signatureCode(){return signatureCode}get signatureAlgorithm(){return signatureAlgorithm}did(){return this.verifier.did()}toDIDKey(){return this.verifier.toDIDKey()}verify(i,s){return this.verifier.verify(i,s)}async sign(i){const s=await webcrypto.subtle.sign({name:ALG,saltLength:SALT_LENGTH},await this.privateKey,i);return create$r(signatureCode,new Uint8Array(s))}}class ExtractableRSASigner extends RSASigner{constructor(i){super(i),this.bytes=i.bytes}withDID(i){return withDID(this,i)}toArchive(){const i=this.did();return{id:i,keys:{[i]:this.bytes}}}}class UnextractableRSASigner extends RSASigner{constructor(i){super(i),this.privateKey=i.privateKey}withDID(i){return withDID(this,i)}toArchive(){const i=this.did();return{id:i,keys:{[i]:this.privateKey}}}}const RSA=Object.freeze(Object.defineProperty({__proto__:null,Verifier:RSAVerifier,code:code$8,decode:decode$v,from:from$g,generate,name:name$6,or:or$9,signatureAlgorithm,signatureCode},Symbol.toStringTag,{value:"Module"})),Signer=or$a(RSA),ProviderDID$2=match$1({method:"web"}),has$1=capability({can:"consumer/has",with:ProviderDID$2,nb:struct({consumer:SpaceDID$1}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.consumer,i.nb.consumer,"consumer"))||ok({})}),get$f=capability({can:"consumer/get",with:ProviderDID$2,nb:struct({consumer:SpaceDID$1}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.consumer,i.nb.consumer,"consumer"))||ok({})}),ProviderDID$1=match$1({method:"web"}),get$e=capability({can:"customer/get",with:ProviderDID$1,nb:struct({customer:AccountDID$1}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.customer,i.nb.customer,"customer"))||ok({})});capability({can:"console/*",with:match$1(),derives:equalWith});capability({can:"console/log",with:match$1(),nb:struct({value:unknown()}),derives:equalWith});capability({can:"console/error",with:match$1(),nb:struct({error:unknown()}),derives:equalWith});const Provider=DID,add$6=capability({can:"rate-limit/add",with:Provider,nb:struct({subject:string(),rate:number()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.subject,i.nb.subject,"subject"))||and$2(equal(o.nb.rate,i.nb.rate,"rate"))||ok({})}),remove$6=capability({can:"rate-limit/remove",with:Provider,nb:struct({id:string()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.id,i.nb.id,"id"))||ok({})}),list$7=capability({can:"rate-limit/list",with:Provider,nb:struct({subject:string()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.subject,i.nb.subject,"subject"))||ok({})}),admin=capability({can:"admin/*",with:ProviderDID$4,derives:equalWith}),upload$1={inspect:capability({can:"admin/upload/inspect",with:ProviderDID$4,nb:struct({root:Link}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.root,i.nb.root,"root"))||ok({})})},store={inspect:capability({can:"admin/store/inspect",with:ProviderDID$4,nb:struct({link:Link}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.link,i.nb.link,"link"))||ok({})})},ProviderDID=match$1({method:"web"}),get$d=capability({can:"subscription/get",with:ProviderDID,nb:struct({subscription:string()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.subscription,i.nb.subscription,"consumer"))||ok({})}),list$6=capability({can:"subscription/list",with:AccountDID$1,derives:equalWith}),FR32_SHA2_256_TRUNC254_PADDED_BINARY_TREE=4113,RAW_CODE=85,PieceLink=match$2({code:RAW_CODE,version:1,multihash:{code:FR32_SHA2_256_TRUNC254_PADDED_BINARY_TREE}}),filecoinOffer$1=capability({can:"filecoin/offer",with:match$1(),nb:struct({content:match$2(),piece:PieceLink}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.content,i.nb.content,"nb.content"))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||ok({})}),filecoinSubmit=capability({can:"filecoin/submit",with:match$1(),nb:struct({content:match$2(),piece:PieceLink}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.content,i.nb.content,"nb.content"))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||ok({})}),filecoinAccept=capability({can:"filecoin/accept",with:match$1(),nb:struct({content:match$2(),piece:PieceLink}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.content,i.nb.content,"nb.content"))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||ok({})}),filecoinInfo$1=capability({can:"filecoin/info",with:match$1(),nb:struct({piece:PieceLink}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||ok({})}),pieceOffer=capability({can:"piece/offer",with:match$1(),nb:struct({piece:PieceLink,group:match()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||and$2(equal(o.nb.group,i.nb.group,"nb.group"))||ok({})}),pieceAccept=capability({can:"piece/accept",with:match$1(),nb:struct({piece:PieceLink,group:match()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||and$2(equal(o.nb.group,i.nb.group,"nb.group"))||ok({})}),aggregateOffer=capability({can:"aggregate/offer",with:match$1(),nb:struct({aggregate:PieceLink,pieces:match$2({version:1})}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.aggregate,i.nb.aggregate,"nb.aggregate"))||and$2(checkLink(o.nb.pieces,i.nb.pieces,"nb.pieces"))||ok({})}),aggregateAccept=capability({can:"aggregate/accept",with:match$1(),nb:struct({aggregate:PieceLink,pieces:match$2()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.aggregate,i.nb.aggregate,"nb.aggregate"))||and$2(checkLink(o.nb.pieces,i.nb.pieces,"nb.pieces"))||ok({})}),dealInfo=capability({can:"deal/info",with:match$1(),nb:struct({piece:PieceLink}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(checkLink(o.nb.piece,i.nb.piece,"nb.piece"))||ok({})}),index=capability({can:"space/index/*",with:SpaceDID$1,derives:equalWith}),add$5=capability({can:"space/index/add",with:SpaceDID$1,nb:struct({index:match$2({code:code$c,version:1})}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.index,i.nb.index,"index"))||ok({})}),get$c=capability({can:"plan/get",with:AccountDID$1,derives:(o,i)=>and$2(equalWith(o,i))||ok({})}),set$5=capability({can:"plan/set",with:AccountDID$1,nb:struct({product:DID}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.product,i.nb.product,"product"))||ok({})}),createAdminSession$1=capability({can:"plan/create-admin-session",with:AccountDID$1,nb:struct({returnURL:string()}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equal(o.nb.returnURL,i.nb.returnURL,"returnURL"))||ok({})}),usage=capability({can:"usage/*",with:SpaceDID$1,derives:equalWith}),report$1=capability({can:"usage/report",with:SpaceDID$1,nb:struct({period:struct({from:integer().greaterThan(-1),to:integer().greaterThan(-1)})}),derives:(o,i)=>{var s,a,c,d;return and$2(equalWith(o,i))||and$2(equal((s=o.nb.period)==null?void 0:s.from,(a=i.nb.period)==null?void 0:a.from,"period.from"))||and$2(equal((c=o.nb.period)==null?void 0:c.to,(d=i.nb.period)==null?void 0:d.to,"period.to"))||ok({})}}),blob$1=capability({can:"space/blob/*",with:SpaceDID$1,derives:equalWith}),content=struct({digest:bytes$1(),size:integer()}),add$4=capability({can:"space/blob/add",with:SpaceDID$1,nb:struct({blob:content}),derives:equalBlob}),remove$5=capability({can:"space/blob/remove",with:SpaceDID$1,nb:struct({digest:bytes$1()}),derives:(o,i)=>o.with!==i.with?fail(`Expected 'with: "${i.with}"' instead got '${o.with}'`):i.nb.digest&&!equals$d(i.nb.digest,o.nb.digest)?fail(`Link ${o.nb.digest?`${o.nb.digest}`:""} violates imposed ${i.nb.digest} constraint.`):ok({})}),list$5=capability({can:"space/blob/list",with:SpaceDID$1,nb:struct({cursor:string().optional(),size:integer().optional()}),derives:(o,i)=>o.with!==i.with?fail(`Expected 'with: "${i.with}"' instead got '${o.with}'`):ok({})}),get$b=capability({can:"space/blob/get/0/1",with:SpaceDID$1,nb:struct({digest:bytes$1()}),derives:(o,i)=>o.with!==i.with?fail(`Expected 'with: "${i.with}"' instead got '${o.with}'`):i.nb.digest&&!equals$d(i.nb.digest,o.nb.digest)?fail(`Link ${o.nb.digest?`${o.nb.digest}`:""} violates imposed ${i.nb.digest} constraint.`):ok({})}),blob=capability({can:"web3.storage/blob/*",with:SpaceDID$1,derives:equalWith}),allocate=capability({can:"web3.storage/blob/allocate",with:match$1(),nb:struct({blob:content,cause:Link,space:SpaceDID$1}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equalBlob(o,i))||and$2(checkLink(o.nb.cause,i.nb.cause,"cause"))||and$2(equal(o.nb.space,i.nb.space,"space"))||ok({})}),accept=capability({can:"web3.storage/blob/accept",with:match$1(),nb:struct({blob:content,ttl:integer().optional(),space:SpaceDID$1,_put:Await}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equalBlob(o,i))||and$2(equal(o.nb.ttl,i.nb.ttl,"ttl"))||and$2(equal(o.nb.space,i.nb.space,"space"))||ok({})}),put=capability({can:"http/put",with:SpaceDID$1,nb:struct({body:content,url:string().or(Await),headers:dictionary({value:string()}).or(Await)}),derives:(o,i)=>and$2(equalWith(o,i))||and$2(equalBody(o,i))||and$2(equal(o.nb.url,i.nb,"url"))||and$2(equal(o.nb.headers,i.nb,"headers"))||ok({})}),abilitiesAsStrings=[top.can,add$8.can,space.can,info.can,upload$2.can,add$9.can,get$g.can,remove$7.can,list$8.can,store$1.can,add$a.can,get$h.can,remove$8.can,list$9.can,access$1.can,authorize.can,attest.can,conclude$1.can,get$e.can,has$1.can,get$f.can,get$d.can,list$6.can,add$6.can,remove$6.can,list$7.can,filecoinOffer$1.can,filecoinSubmit.can,filecoinAccept.can,filecoinInfo$1.can,pieceOffer.can,pieceAccept.can,aggregateOffer.can,aggregateAccept.can,dealInfo.can,admin.can,upload$1.inspect.can,store.inspect.can,get$c.can,set$5.can,createAdminSession$1.can,usage.can,report$1.can,blob$1.can,add$4.can,remove$5.can,list$5.can,blob.can,allocate.can,accept.can,put.can,index.can,add$5.can];function uint8ArrayToArrayBuffer(o){return o.byteOffset===0&&o.byteLength===o.buffer.byteLength?o.buffer:o.buffer.slice(o.byteOffset,o.byteLength+o.byteOffset)}var Fe;const St=class St{constructor(i,s={}){Y(this,Fe);this.meta=i.meta,this.principal=i.principal,this.spaces=i.spaces,this.delegations=i.delegations,this.currentSpace=i.currentSpace,Q(this,Fe,a=>s.store?s.store.save(a):void 0)}static async create(i={},s={}){const a=new St({meta:{name:"agent",type:"device",...i.meta},principal:i.principal??await generate$2(),spaces:i.spaces??new Map,delegations:i.delegations??new Map,currentSpace:i.currentSpace},s);return s.store&&await s.store.save(a.export()),a}static fromExport(i,s){const a=new Map;for(const[c,d]of i.delegations)a.set(c,{delegation:importDAG(d.delegation.map(f=>({cid:CID$5.parse(f.cid).toV1(),bytes:f.bytes instanceof Uint8Array?f.bytes:new Uint8Array(f.bytes)}))),meta:d.meta});return new St({meta:i.meta,principal:Signer.from(i.principal),currentSpace:i.currentSpace,spaces:i.spaces,delegations:a},s)}export(){const i={meta:this.meta,principal:this.principal.toArchive(),currentSpace:this.currentSpace,spaces:this.spaces,delegations:new Map};for(const[s,a]of this.delegations)i.delegations.set(s,{meta:a.meta,delegation:[...a.delegation.export()].map(c=>({cid:c.cid.toString(),bytes:uint8ArrayToArrayBuffer(c.bytes)}))});return i}async addSpace(i,s,a){this.spaces.set(i,s),await(a?this.addDelegation(a):F(this,Fe).call(this,this.export()))}async setCurrentSpace(i){this.currentSpace=i,await F(this,Fe).call(this,this.export())}async addDelegation(i,s){this.delegations.set(i.cid.toString(),{delegation:i,meta:s??{}}),await F(this,Fe).call(this,this.export())}async removeDelegation(i){this.delegations.delete(i.toString()),await F(this,Fe).call(this,this.export())}};Fe=new WeakMap;let AgentData=St;const isSessionCapability=o=>o.can===attest.can,isSessionProof=o=>o.capabilities.some(i=>isSessionCapability(i));function getSessionProofs(o){const i={};for(const{delegation:s}of o.delegations.values())if(isSessionProof(s)){const a=s.capabilities[0];if(a&&!isExpired(s)){const c=a.nb.proof;if(c){const d=c.toString(),f=s.issuer.did();i[d]=i[d]??{},i[d][f]=i[d][f]??[],i[d][f].push(s)}}}return i}match$1({method:"web"});const HOST="https://up.web3.storage",PRINCIPAL=parse$2("did:web:web3.storage"),agentToData=new WeakMap;function connection$2(o={}){return connect({id:o.principal??PRINCIPAL,codec:outbound,channel:o.channel??open$2({url:o.url??new URL(HOST),method:"POST",fetch:o.fetch??globalThis.fetch.bind(globalThis)})})}var se,gt,Mt;const Tt=class Tt{constructor(i,s={}){Y(this,gt);Y(this,se);var c;const a=(c=s.connection)==null?void 0:c.channel;this.url=s.url??(a==null?void 0:a.url)??new URL(HOST),this.connection=s.connection??connection$2({principal:s.servicePrincipal,url:this.url}),Q(this,se,i),agentToData.set(this,F(this,se))}static async create(i,s={}){const a=await AgentData.create(i,s);return new Tt(a,s)}static from(i,s={}){const a=AgentData.fromExport(i,s);return new Tt(a,s)}get issuer(){return F(this,se).principal}get meta(){return F(this,se).meta}get spaces(){return F(this,se).spaces}did(){return F(this,se).principal.did()}async addProof(i){return await this.addProofs([i])}async addProofs(i){for(const s of i)await F(this,se).addDelegation(s,{audience:this.meta});return await this.removeExpiredDelegations(),{}}async removeExpiredDelegations(){for(const[,i]of F(this,se).delegations)isExpired(i.delegation)&&await F(this,se).removeDelegation(i.delegation.cid)}async revoke(i,s={}){const a=s.proofs??[],c=[...this.delegations(),...a].find(f=>f.cid.equals(i));return c?(await this.invokeAndExecute(revoke,{with:this.issuer.did(),nb:{ucan:c.cid},proofs:[c,...a]})).out:{error:new Error(`could not find delegation ${i.toString()} - please include the delegation in options.proofs`)}}proofs(i,s){const a=[];for(const{delegation:d}of te(this,gt,Mt).call(this,i))d.audience.did()===this.issuer.did()&&a.push(d);const c=getSessionProofs(F(this,se));for(const d of a){const f=c[d.asCID.toString()]??{},g=s!=null&&s.sessionProofIssuer?f[s.sessionProofIssuer]??[]:Object.values(f).flat();g.length&&a.push(...g)}return a}delegations(i){const s=[];for(const{delegation:a}of this.delegationsWithMeta(i))s.push(a);return s}delegationsWithMeta(i){const s=[];for(const a of te(this,gt,Mt).call(this,i)){const{delegation:c}=a;!c.capabilities.some(f=>f.can===attest.can)&&c.audience.did()!==this.issuer.did()&&s.push(a)}return s}async createSpace(i){return await generate$1({name:i,agent:this})}async recoverSpace(i,{name:s}){return await fromMnemonic(i,{name:s,agent:this})}async importSpaceFromDelegation(i,{name:s=""}={}){const a=s===""?fromDelegation(i):fromDelegation(i).withName(s);return F(this,se).spaces.set(a.did(),{...a.meta,name:a.name}),await this.addProof(a.delegation),this.currentSpace()||await this.setCurrentSpace(a.did()),a}async setCurrentSpace(i){if(!F(this,se).spaces.has(i))throw new Error(`Agent has no proofs for ${i}.`);return await F(this,se).setCurrentSpace(i),i}currentSpace(){return F(this,se).currentSpace}currentSpaceWithMeta(){if(!F(this,se).currentSpace)return;const i=this.proofs([{can:"space/info",with:F(this,se).currentSpace}]),s=new Set;for(const a of i)for(const c of a.capabilities)s.add(c.can);return{did:F(this,se).currentSpace,proofs:i,capabilities:[...s],meta:F(this,se).spaces.get(F(this,se).currentSpace)}}async delegate(i){const s=this.currentSpaceWithMeta();if(!s)throw new Error("no space selected.");const a=i.abilities.map(d=>({with:s.did,can:d}));for(const d of a)if(!this.proofs([d]).length)throw new Error(`cannot delegate capability ${d.can} with ${d.with}`);const c=await delegate$3({issuer:this.issuer,capabilities:a,proofs:this.proofs(a),facts:[{space:s.meta??{}}],...i});return await F(this,se).addDelegation(c,{audience:i.audienceMeta}),await this.removeExpiredDelegations(),c}async invokeAndExecute(i,s){return(await this.invoke(i,s)).execute(this.connection)}execute(...i){return this.connection.execute(...i)}async invoke(i,s){const a=s.audience||this.connection.id,c=s.with||this.currentSpace();if(!c)throw new Error("No space or resource selected, you need pass a resource.");const d=[...s.proofs||[],...this.proofs([{with:c,can:i.can}],{sessionProofIssuer:a.did()})];if(d.length===0&&s.with!==this.did())throw new Error(`no proofs available for resource ${c} and ability ${i.can}`);return invoke({...s,audience:a,capability:i.create({with:c,nb:s.nb}),issuer:this.issuer,proofs:[...d],nonce:s.nonce})}async getSpaceInfo(i,s){const a=i||this.currentSpace();if(!a)throw new Error("No space selected, you need pass a resource.");const c=await this.invokeAndExecute(info,{...s,with:a});if(c.out.error)throw c.out.error;return c.out.ok}};se=new WeakMap,gt=new WeakSet,Mt=function(i){const s=new Set(i),a=[];for(const[,c]of F(this,se).delegations)if(!isExpired(c.delegation)&&!isTooEarly(c.delegation))if(Array.isArray(i)&&i.length>0)for(const d of s)canDelegateCapability(c.delegation,d)&&a.push(c);else a.push(c);return a};let Agent=Tt;async function addSpacesFromDelegations(o,i){const s=agentToData.get(o);if(!s)throw Object.assign(new Error("cannot determine AgentData for Agent"),{agent:o});const a=new Map,c=i.filter(f=>f.audience.did()===o.did()),d=c.filter(f=>f.capabilities[0].can==="*"&&f.capabilities[0].with==="ucan:*");for(const f of d)for(const g of f.proofs){if(!isDelegation(g)||!g.capabilities[0].with.startsWith("did:key"))continue;const y=fromDelegation(g);a.set(y.did(),y.meta)}for(const f of c){const g=allows(f);for(const[y,b]of Object.entries(g))y.startsWith("did:key")&&Object.keys(b).length>0&&(a.has(y)||a.set(y,{}))}for(const[f,g]of a)await s.addSpace(f,g)}const importAuthorization=async(o,{proofs:i})=>{try{return await o.addProofs(i),await addSpacesFromDelegations(o,i),{ok:{}}}catch(s){return{error:s}}};function pDefer(){const o={};return o.promise=new Promise((i,s)=>{o.resolve=i,o.reject=s}),o}const STORE_NAME="AccessStore",DATA_ID=1;var yt,mt,je,Be,bt,rt,kt;class IndexedDBDriver{constructor(i,s={}){Y(this,rt);Y(this,yt);Y(this,mt);Y(this,je);Y(this,Be);Y(this,bt);Q(this,yt,i),Q(this,mt,s.dbVersion),Q(this,je,s.dbStoreName??STORE_NAME),Q(this,bt,s.autoOpen??!0)}async open(){if(F(this,Be))return;const{resolve:s,reject:a,promise:c}=pDefer(),d=indexedDB.open(F(this,yt),F(this,mt));return d.addEventListener("upgradeneeded",()=>{d.result.createObjectStore(F(this,je),{keyPath:"id"})}),d.addEventListener("success",()=>{Q(this,Be,d.result),s()}),d.addEventListener("error",()=>a(d.error)),c}async close(){const i=F(this,Be);if(!i)throw new Error("Store is not open");i.close(),Q(this,Be,void 0)}async save(i){const s=await te(this,rt,kt).call(this);return await withObjectStore(s,"readwrite",F(this,je),async c=>{const{resolve:d,reject:f,promise:g}=pDefer(),y=c.put({id:DATA_ID,...i});return y.addEventListener("success",()=>d()),y.addEventListener("error",()=>f(new Error("failed to query DB",{cause:y.error}))),g})()}async load(){const i=await te(this,rt,kt).call(this);return await withObjectStore(i,"readonly",F(this,je),async a=>{const{resolve:c,reject:d,promise:f}=pDefer(),g=a.get(DATA_ID);return g.addEventListener("success",()=>c(g.result)),g.addEventListener("error",()=>d(new Error("failed to query DB",{cause:g.error}))),f})()}async reset(){const i=await te(this,rt,kt).call(this);await withObjectStore(i,"readwrite",F(this,je),a=>{const{resolve:c,reject:d,promise:f}=pDefer(),g=a.clear();return g.addEventListener("success",()=>{c()}),g.addEventListener("error",()=>d(new Error("failed to query DB",{cause:g.error}))),f})()}}yt=new WeakMap,mt=new WeakMap,je=new WeakMap,Be=new WeakMap,bt=new WeakMap,rt=new WeakSet,kt=async function(){if(!F(this,Be)){if(!F(this,bt))throw new Error("Store is not open");await this.open()}return F(this,Be)};function withObjectStore(o,i,s,a){return async()=>{const c=o.transaction(s,i),{resolve:d,reject:f,promise:g}=pDefer();let y;c.addEventListener("complete",()=>d(y)),c.addEventListener("abort",()=>f(c.error||new Error("transaction aborted"))),c.addEventListener("error",()=>f(new Error("transaction error",{cause:c.error})));try{y=await a(c.objectStore(s)),c.commit()}catch(b){f(b),c.abort()}return g}}class StoreIndexedDB extends IndexedDBDriver{}const BITS_PER_BYTE=8,FRS_PER_QUAD=4;BigInt(FRS_PER_QUAD);const IN_BITS_FR=254,OUT_BITS_FR=256,IN_BYTES_PER_QUAD=FRS_PER_QUAD*IN_BITS_FR/BITS_PER_BYTE,OUT_BYTES_PER_QUAD=FRS_PER_QUAD*OUT_BITS_FR/BITS_PER_BYTE,PADDED_BYTES_PER_QUAD=BigInt(IN_BYTES_PER_QUAD);BigInt(OUT_BYTES_PER_QUAD);const FR_RATIO=IN_BITS_FR/OUT_BITS_FR,NODE_SIZE=OUT_BYTES_PER_QUAD/FRS_PER_QUAD,EXPANDED_BYTES_PER_NODE=BigInt(NODE_SIZE),MIN_PAYLOAD_SIZE=2*NODE_SIZE+1,from$f=o=>{if(o instanceof Uint8Array){if(o.length>NODE_SIZE)return o.subarray(0,NODE_SIZE);if(o.length==NODE_SIZE)return o}const i=new Uint8Array(NODE_SIZE);return i.set([...o]),i},empty$4=()=>EMPTY$4,EMPTY$4=from$f(new Uint8Array(NODE_SIZE).fill(0));Object.freeze(EMPTY$4.buffer);function coerce$6(o){if(o instanceof Uint8Array&&o.constructor.name==="Uint8Array")return o;if(o instanceof ArrayBuffer)return new Uint8Array(o);if(ArrayBuffer.isView(o))return new Uint8Array(o.buffer,o.byteOffset,o.byteLength);throw new Error("Unknown type, must be binary type")}const name$5="sha2-256",code$7=18,size$2=32,prefix=new Uint8Array([18,32]);let Digest$7=class{constructor(i){this.code=code$7,this.name=name$5,this.bytes=i,this.size=size$2,this.digest=i.subarray(2)}};const digest$2=o=>{const i=new Uint8Array(prefix.length+size$2);return i.set(prefix,0),i.set(sha256$7(o),prefix.length),new Digest$7(i)},code$6=code$7,SHA256=Object.freeze(Object.defineProperty({__proto__:null,code:code$6,digest:digest$2,name:name$5,size:size$2},Symbol.toStringTag,{value:"Module"}));function base$6(o,i){if(o.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src$6=base$6,_brrp__multiformats_scope_baseX$6=src$6;let Encoder$6=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseEncode");this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}},Decoder$6=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseDecode");U(this,"prefixCodePoint");this.name=i,this.prefix=s;const c=s.codePointAt(0);if(c===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=c,this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or$8(this,i)}},ComposedDecoder$6=class{constructor(i){U(this,"decoders");this.decoders=i}or(i){return or$8(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a!=null)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$8(o,i){return new ComposedDecoder$6({...o.decoders??{[o.prefix]:o},...i.decoders??{[i.prefix]:i}})}let Codec$6=class{constructor(i,s,a,c){U(this,"name");U(this,"prefix");U(this,"baseEncode");U(this,"baseDecode");U(this,"encoder");U(this,"decoder");this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder$6(i,s,a),this.decoder=new Decoder$6(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}};function from$e({name:o,prefix:i,encode:s,decode:a}){return new Codec$6(o,i,s,a)}function baseX$6({name:o,prefix:i,alphabet:s}){const{encode:a,decode:c}=_brrp__multiformats_scope_baseX$6(s,o);return from$e({prefix:i,name:o,encode:a,decode:d=>coerce$6(c(d))})}function decode$u(o,i,s,a){const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f}function encode$k(o,i,s){const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f!==0&&(d+=i[c&g<=INT$7;)i[s++]=o&255|MSB$7,o/=128;for(;o&MSBALL$7;)i[s++]=o&255|MSB$7,o>>>=7;return i[s]=o|0,encode$j.bytes=s-a+1,i}var decode$t=read$7,MSB$1$7=128,REST$1$7=127;function read$7(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$7.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$7)<=MSB$1$7);return read$7.bytes=d-a,s}var N1$6=Math.pow(2,7),N2$6=Math.pow(2,14),N3$6=Math.pow(2,21),N4$6=Math.pow(2,28),N5$6=Math.pow(2,35),N6$6=Math.pow(2,42),N7$6=Math.pow(2,49),N8$6=Math.pow(2,56),N9$6=Math.pow(2,63),length$6=function(o){return o{const a=new Uint8Array(o.length+i.length);return a.set(o,0),a.set(i,o.length),truncatedHash(a,s)};function truncate(o){return o[NODE_SIZE-1]&=63,o}const MAX_LEVEL=64;class ZeroComm{constructor(){this.bytes=new Uint8Array(MAX_LEVEL*NODE_SIZE),this.bytes.set(empty$4(),0),this.node=empty$4(),this.length=NODE_SIZE}slice(i,s){for(;this.length{if(o<0||o>=MAX_LEVEL)throw new Error(`Only levels between 0 and ${MAX_LEVEL-1} inclusive are available`);return ZERO_COMM.slice(NODE_SIZE*o,NODE_SIZE*(o+1))},split$1=o=>{const i=o.length/NODE_SIZE,s=new Array(i);for(let a=0;atoZeroPaddedSize(o)/FR_RATIO,pad=(o,i=new Uint8Array(toPieceSize(o.length)))=>{const a=toZeroPaddedSize(o.byteLength)/IN_BYTES_PER_QUAD;for(let c=0;c>6;i[f+63]&=63;for(let g=64;g<96;g++)i[f+g]=o[d+g]<<4|o[d+g-1]>>4;i[f+95]&=63;for(let g=96;g<127;g++)i[f+g]=o[d+g]<<6|o[d+g-1]>>2;i[f+127]=o[d+126]>>2}return i},log2Floor=o=>{let i=0n;for(;o>>=1n;)i++;return Number(i)},log2Ceil=o=>o<=1n?0:log2Floor(BigInt(o)-1n)+1,toPadding=o=>toPadded(o)-o,toPadded=o=>toQauds(o)*PADDED_BYTES_PER_QUAD,toQauds=o=>{const i=(o+PADDED_BYTES_PER_QUAD-1n)/PADDED_BYTES_PER_QUAD;return 2n**BigInt(log2Ceil(i))},fromHeight=o=>fromWidth(2n**BigInt(o)),fromWidth=o=>o*EXPANDED_BYTES_PER_NODE,name$4="fr32-sha2-256-trunc254-padded-binary-tree",code$5=4113,MAX_PADDING_SIZE=9,HEIGHT_SIZE=1,ROOT_SIZE=size$2,MAX_DIGEST_SIZE=MAX_PADDING_SIZE+HEIGHT_SIZE+size$2,TAG_SIZE=encodingLength$6(code$5),MAX_SIZE=TAG_SIZE+encodingLength$6(MAX_DIGEST_SIZE)+MAX_DIGEST_SIZE,MAX_HEIGHT$1=255,MAX_PAYLOAD_SIZE$1=fromHeight(MAX_HEIGHT$1)*BigInt(IN_BITS_FR)/BigInt(OUT_BITS_FR),fromPiece=({padding:o,height:i,root:s})=>{const a=encodingLength$6(Number(o)),c=a+HEIGHT_SIZE+ROOT_SIZE,d=encodingLength$6(c),f=TAG_SIZE+d+c;let g=0;const y=new Uint8Array(f);return encodeTo$6(code$5,y,g),g+=TAG_SIZE,encodeTo$6(c,y,g),g+=d,encodeTo$6(Number(o),y,g),g+=a,y[g]=i,g+=HEIGHT_SIZE,y.set(s,g),new Digest$6(y)},fromBytes$3=o=>new Digest$6(o),toBytes$2=({digest:o})=>{const s=encodingLength$6(o.length)+TAG_SIZE;if(o.byteOffset>=s){const c=new Uint8Array(o.buffer,o.byteOffset-s,o.byteOffset+o.length),[d,f]=decode$s(c);if(d===code$5&&decode$s(c,f)[0]===o.length)return c}const a=new Uint8Array(o.length+s);return encodeTo$6(code$5,a),encodeTo$6(o.length,a,TAG_SIZE),a.set(o,s),a},height=({digest:o})=>{const[,i]=decode$s(o);return o[i]},padding=({digest:o})=>{const[i]=decode$s(o);return BigInt(i)},root=({digest:o})=>{const[,i]=decode$s(o);return o.subarray(i+HEIGHT_SIZE,i+HEIGHT_SIZE+size$2)};let Digest$6=class{constructor(i){this.bytes=i;const[s]=decode$s(i);if(s!==code$5)throw new RangeError(`Expected multihash with code ${code$5}`);let a=TAG_SIZE;const[c,d]=decode$s(i,a);a+=d;const f=i.subarray(a);if(f.length!==c)throw new RangeError(`Invalid multihash size expected ${a+c} bytes, got ${i.length} bytes`);this.digest=f}get name(){return name$4}get code(){return code$5}get size(){return this.digest.length}get padding(){return padding(this)}get height(){return height(this)}get root(){return root(this)}};const digest$1=Object.freeze(Object.defineProperty({__proto__:null,HEIGHT_SIZE,MAX_DIGEST_SIZE,MAX_HEIGHT:MAX_HEIGHT$1,MAX_PAYLOAD_SIZE:MAX_PAYLOAD_SIZE$1,MAX_SIZE,ROOT_SIZE,TAG_SIZE,code:code$5,fromBytes:fromBytes$3,fromPiece,height,name:name$4,padding,root,toBytes:toBytes$2},Symbol.toStringTag,{value:"Module"})),name$3="fr32-sha2-256-trunc254-padded-binary-tree",code$4=4113,MAX_HEIGHT=255,MAX_PAYLOAD_SIZE=fromHeight(MAX_HEIGHT)*BigInt(IN_BITS_FR)/BigInt(OUT_BITS_FR),digest=o=>{const i=new Hasher$4;return i.write(o),i.digest()},create$i=()=>new Hasher$4;let Hasher$4=class{constructor(){this.bytesWritten=0n,this.buffer=new Uint8Array(IN_BYTES_PER_QUAD),this.offset=0,this.layers=[[]]}count(){return this.bytesWritten}digest(){const i=new Uint8Array(MAX_SIZE),s=this.digestInto(i,0,!0);return fromBytes$3(i.subarray(0,s))}digestInto(i,s=0,a=!0){const{buffer:c,layers:d,offset:f,bytesWritten:g}=this;let[y,...b]=d;(f>0||g===0n)&&(y=[...y,...split$1(pad(c.fill(0,f)))]);const $=build([y,...b]),x=$.length-1,[T]=$[x],A=Number(toPadding(this.bytesWritten)),E=encodingLength$6(A);let S=s;if(a){encodeTo$6(code$4,i,S),S+=TAG_SIZE;const _=E+HEIGHT_SIZE+ROOT_SIZE,C=encodingLength$6(_);encodeTo$6(_,i,S),S+=C}return encodeTo$6(A,i,S),S+=E,i[S]=x,S+=1,i.set(T,S),S+=T.length,S-s}write(i){const{buffer:s,offset:a,layers:c}=this,d=c[0],{length:f}=i;if(f===0)return this;if(this.bytesWritten+BigInt(f)>MAX_PAYLOAD_SIZE)throw new RangeError(`Writing ${f} bytes exceeds max payload size of ${MAX_PAYLOAD_SIZE}`);if(a+fflush$1(o,!1),build=o=>flush$1([...o],!0),flush$1=(o,i)=>{let s=0;for(;s0&&a&&c.push(fromLevel(s)),s+=1,a=a?i?[...a]:a:[];let d=0;for(;d+1{const s=[];for(const c of o.receipts.values()){const d=c.out;d.ok?s.push(d.ok):s.push({...d.error,error:!0})}const a=encode$A(s);return{headers:HEADERS,body:a}},response=Object.freeze(Object.defineProperty({__proto__:null,contentType:contentType$2,encode:encode$i},Symbol.toStringTag,{value:"Module"})),contentType$1="application/car",decode$r=async({body:o})=>{const{roots:i,blocks:s}=decode$M(o),a=[];for(const{cid:d}of i){const f=view$2({root:d,blocks:s});a.push(f)}return await build$1({invocations:a})},request$1=Object.freeze(Object.defineProperty({__proto__:null,contentType:contentType$1,decode:decode$r},Symbol.toStringTag,{value:"Module"})),{contentType}=request$1;inbound({decoders:{[contentType]:request$1,[contentType$3]:request$3},encoders:{"*/*;q=0.1":response,[contentType$3]:response$1}});const services={STOREFRONT:{url:new URL("https://up.web3.storage"),principal:parse$2("did:web:web3.storage")},AGGREGATOR:{url:new URL("https://aggregator.web3.storage"),principal:parse$2("did:web:web3.storage")},DEALER:{url:new URL("https://dealer.web3.storage"),principal:parse$2("did:web:web3.storage")},DEAL_TRACKER:{url:new URL("https://tracker.web3.storage"),principal:parse$2("did:web:web3.storage")}},connection$1=connect({id:services.STOREFRONT.principal,codec:outbound,channel:open$2({url:services.STOREFRONT.url,method:"POST"})});async function filecoinOffer({issuer:o,with:i,proofs:s,audience:a},c,d,f={}){const g=f.connection??connection$1;return await filecoinOffer$1.invoke({issuer:o,audience:a??services.STOREFRONT.principal,with:i,nb:{content:c,piece:d},proofs:s,expiration:1/0}).execute(g)}async function filecoinInfo({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection$1;return await filecoinInfo$1.invoke({issuer:o,audience:a??services.STOREFRONT.principal,with:i,nb:{piece:c},proofs:s}).execute(f)}connect({id:services.AGGREGATOR.principal,codec:outbound,channel:open$2({url:services.AGGREGATOR.url,method:"POST"})});connect({id:services.DEALER.principal,codec:outbound,channel:open$2({url:services.DEALER.url,method:"POST"})});connect({id:services.DEAL_TRACKER.principal,codec:outbound,channel:open$2({url:services.DEAL_TRACKER.url,method:"POST"})});function base$5(o,i){if(o.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src$5=base$5,_brrp__multiformats_scope_baseX$5=src$5;const equals$a=(o,i)=>{if(o===i)return!0;if(o.byteLength!==i.byteLength)return!1;for(let s=0;s{if(o instanceof Uint8Array&&o.constructor.name==="Uint8Array")return o;if(o instanceof ArrayBuffer)return new Uint8Array(o);if(ArrayBuffer.isView(o))return new Uint8Array(o.buffer,o.byteOffset,o.byteLength);throw new Error("Unknown type, must be binary type")};let Encoder$5=class{constructor(i,s,a){this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}},Decoder$5=class{constructor(i,s,a){if(this.name=i,this.prefix=s,s.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s.codePointAt(0),this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or$7(this,i)}},ComposedDecoder$5=class{constructor(i){this.decoders=i}or(i){return or$7(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const or$7=(o,i)=>new ComposedDecoder$5({...o.decoders||{[o.prefix]:o},...i.decoders||{[i.prefix]:i}});let Codec$5=class{constructor(i,s,a,c){this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder$5(i,s,a),this.decoder=new Decoder$5(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}};const from$d=({name:o,prefix:i,encode:s,decode:a})=>new Codec$5(o,i,s,a),baseX$5=({prefix:o,name:i,alphabet:s})=>{const{encode:a,decode:c}=_brrp__multiformats_scope_baseX$5(s,i);return from$d({prefix:o,name:i,encode:a,decode:d=>coerce$5(c(d))})},decode$q=(o,i,s,a)=>{const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f},encode$h=(o,i,s)=>{const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f&&(d+=i[c&g<from$d({prefix:i,name:o,encode(c){return encode$h(c,a,s)},decode(c){return decode$q(c,a,s,o)}}),base32$4=rfc4648$5({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5});rfc4648$5({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5});rfc4648$5({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5});rfc4648$5({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5});rfc4648$5({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5});rfc4648$5({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5});rfc4648$5({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5});rfc4648$5({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5});rfc4648$5({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});const base58btc$4=baseX$5({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});baseX$5({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var encode_1$5=encode$g,MSB$6=128,REST$6=127,MSBALL$6=~REST$6,INT$6=Math.pow(2,31);function encode$g(o,i,s){i=i||[],s=s||0;for(var a=s;o>=INT$6;)i[s++]=o&255|MSB$6,o/=128;for(;o&MSBALL$6;)i[s++]=o&255|MSB$6,o>>>=7;return i[s]=o|0,encode$g.bytes=s-a+1,i}var decode$p=read$6,MSB$1$6=128,REST$1$6=127;function read$6(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$6.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$6)<=MSB$1$6);return read$6.bytes=d-a,s}var N1$5=Math.pow(2,7),N2$5=Math.pow(2,14),N3$5=Math.pow(2,21),N4$5=Math.pow(2,28),N5$5=Math.pow(2,35),N6$5=Math.pow(2,42),N7$5=Math.pow(2,49),N8$5=Math.pow(2,56),N9$5=Math.pow(2,63),length$5=function(o){return o[_brrp_varint$5.decode(o,i),_brrp_varint$5.decode.bytes],encodeTo$5=(o,i,s=0)=>(_brrp_varint$5.encode(o,i,s),i),encodingLength$5=o=>_brrp_varint$5.encodingLength(o),create$h=(o,i)=>{const s=i.byteLength,a=encodingLength$5(o),c=a+encodingLength$5(s),d=new Uint8Array(c+s);return encodeTo$5(o,d,0),encodeTo$5(s,d,a),d.set(i,c),new Digest$5(o,s,i,d)},decode$n=o=>{const i=coerce$5(o),[s,a]=decode$o(i),[c,d]=decode$o(i.subarray(a)),f=i.subarray(a+d);if(f.byteLength!==c)throw new Error("Incorrect length");return new Digest$5(s,c,f,i)},equals$9=(o,i)=>{if(o===i)return!0;{const s=i;return o.code===s.code&&o.size===s.size&&s.bytes instanceof Uint8Array&&equals$a(o.bytes,s.bytes)}};let Digest$5=class{constructor(i,s,a,c){this.code=i,this.size=s,this.digest=a,this.bytes=c}};const format$4=(o,i)=>{const{bytes:s,version:a}=o;switch(a){case 0:return toStringV0$4(s,baseCache$4(o),i||base58btc$4.encoder);default:return toStringV1$4(s,baseCache$4(o),i||base32$4.encoder)}},cache$5=new WeakMap,baseCache$4=o=>{const i=cache$5.get(o);if(i==null){const s=new Map;return cache$5.set(o,s),s}return i};let CID$4=class ye{constructor(i,s,a,c){this.code=s,this.version=i,this.multihash=a,this.bytes=c,this["/"]=c}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:{const{code:i,multihash:s}=this;if(i!==DAG_PB_CODE$5)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(s.code!==SHA_256_CODE$4)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ye.createV0(s)}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:{const{code:i,digest:s}=this.multihash,a=create$h(i,s);return ye.createV1(this.code,a)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(i){return ye.equals(this,i)}static equals(i,s){const a=s;return a&&i.code===a.code&&i.version===a.version&&equals$9(i.multihash,a.multihash)}toString(i){return format$4(this,i)}toJSON(){return{"/":format$4(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(i){if(i==null)return null;const s=i;if(s instanceof ye)return s;if(s["/"]!=null&&s["/"]===s.bytes||s.asCID===s){const{version:a,code:c,multihash:d,bytes:f}=s;return new ye(a,c,d,f||encodeCID$4(a,c,d.bytes))}else if(s[cidSymbol$4]===!0){const{version:a,multihash:c,code:d}=s,f=decode$n(c);return ye.create(a,d,f)}else return null}static create(i,s,a){if(typeof s!="number")throw new Error("String codecs are no longer supported");if(!(a.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(i){case 0:{if(s!==DAG_PB_CODE$5)throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE$5}) block encoding`);return new ye(i,s,a,a.bytes)}case 1:{const c=encodeCID$4(i,s,a.bytes);return new ye(i,s,a,c)}default:throw new Error("Invalid version")}}static createV0(i){return ye.create(0,DAG_PB_CODE$5,i)}static createV1(i,s){return ye.create(1,i,s)}static decode(i){const[s,a]=ye.decodeFirst(i);if(a.length)throw new Error("Incorrect length");return s}static decodeFirst(i){const s=ye.inspectBytes(i),a=s.size-s.multihashSize,c=coerce$5(i.subarray(a,a+s.multihashSize));if(c.byteLength!==s.multihashSize)throw new Error("Incorrect length");const d=c.subarray(s.multihashSize-s.digestSize),f=new Digest$5(s.multihashCode,s.digestSize,d,c);return[s.version===0?ye.createV0(f):ye.createV1(s.codec,f),i.subarray(s.size)]}static inspectBytes(i){let s=0;const a=()=>{const[x,T]=decode$o(i.subarray(s));return s+=T,x};let c=a(),d=DAG_PB_CODE$5;if(c===18?(c=0,s=0):d=a(),c!==0&&c!==1)throw new RangeError(`Invalid CID version ${c}`);const f=s,g=a(),y=a(),b=s+y,$=b-f;return{version:c,codec:d,multihashCode:g,digestSize:y,multihashSize:$,size:b}}static parse(i,s){const[a,c]=parseCIDtoBytes$4(i,s),d=ye.decode(c);if(d.version===0&&i[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache$4(d).set(a,i),d}};const parseCIDtoBytes$4=(o,i)=>{switch(o[0]){case"Q":{const s=i||base58btc$4;return[base58btc$4.prefix,s.decode(`${base58btc$4.prefix}${o}`)]}case base58btc$4.prefix:{const s=i||base58btc$4;return[base58btc$4.prefix,s.decode(o)]}case base32$4.prefix:{const s=i||base32$4;return[base32$4.prefix,s.decode(o)]}default:{if(i==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[o[0],i.decode(o)]}}},toStringV0$4=(o,i,s)=>{const{prefix:a}=s;if(a!==base58btc$4.prefix)throw Error(`Cannot string encode V0 in ${s.name} encoding`);const c=i.get(a);if(c==null){const d=s.encode(o).slice(1);return i.set(a,d),d}else return c},toStringV1$4=(o,i,s)=>{const{prefix:a}=s,c=i.get(a);if(c==null){const d=s.encode(o);return i.set(a,d),d}else return c},DAG_PB_CODE$5=112,SHA_256_CODE$4=18,encodeCID$4=(o,i,s)=>{const a=encodingLength$5(o),c=a+encodingLength$5(i),d=new Uint8Array(c+s.byteLength);return encodeTo$5(o,d,0),encodeTo$5(i,d,a),d.set(s,c),d},cidSymbol$4=Symbol.for("@ipld/js-cid/CID"),create$g=(o,i)=>CID$4.create(1,o,i),name$2="raw",code$3=85,encode$f=o=>coerce$5(o),decode$m=o=>coerce$5(o),raw=Object.freeze(Object.defineProperty({__proto__:null,code:code$3,decode:decode$m,encode:encode$f,name:name$2},Symbol.toStringTag,{value:"Module"})),from$c=({name:o,code:i,encode:s})=>new Hasher$3(o,i,s);let Hasher$3=class{constructor(i,s,a){this.name=i,this.code=s,this.encode=a}digest(i){if(i instanceof Uint8Array){const s=this.encode(i);return s instanceof Uint8Array?create$h(this.code,s):s.then(a=>create$h(this.code,a))}else throw Error("Unknown type, must be binary type")}};const sha$2=o=>async i=>new Uint8Array(await crypto.subtle.digest(o,i)),sha256$2=from$c({name:"sha2-256",code:18,encode:sha$2("SHA-256")});var retry$2={};function RetryOperation(o,i){typeof i=="boolean"&&(i={forever:i}),this._originalTimeouts=JSON.parse(JSON.stringify(o)),this._timeouts=o,this._options=i||{},this._maxRetryTime=i&&i.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))}var retry_operation=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(o){if(this._timeout&&clearTimeout(this._timeout),!o)return!1;var i=new Date().getTime();if(o&&i-this._operationStart>=this._maxRetryTime)return this._errors.push(o),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(o);var s=this._timeouts.shift();if(s===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),s=this._cachedTimeouts.slice(-1);else return!1;var a=this;return this._timer=setTimeout(function(){a._attempts++,a._operationTimeoutCb&&(a._timeout=setTimeout(function(){a._operationTimeoutCb(a._attempts)},a._operationTimeout),a._options.unref&&a._timeout.unref()),a._fn(a._attempts)},s),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(o,i){this._fn=o,i&&(i.timeout&&(this._operationTimeout=i.timeout),i.cb&&(this._operationTimeoutCb=i.cb));var s=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){s._operationTimeoutCb()},s._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(o){console.log("Using RetryOperation.try() is deprecated"),this.attempt(o)};RetryOperation.prototype.start=function(o){console.log("Using RetryOperation.start() is deprecated"),this.attempt(o)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var o={},i=null,s=0,a=0;a=s&&(i=c,s=f)}return i};(function(o){var i=retry_operation;o.operation=function(s){var a=o.timeouts(s);return new i(a,{forever:s&&(s.forever||s.retries===1/0),unref:s&&s.unref,maxRetryTime:s&&s.maxRetryTime})},o.timeouts=function(s){if(s instanceof Array)return[].concat(s);var a={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var c in s)a[c]=s[c];if(a.minTimeout>a.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var d=[],f=0;f{const a=s.retries-(i-1);return o.attemptNumber=i,o.retriesLeft=a,o},isNetworkError=o=>networkErrorMsgs.has(o),getDOMException=o=>globalThis.DOMException===void 0?new Error(o):new DOMException(o);async function pRetry(o,i){return new Promise((s,a)=>{i={onFailedAttempt(){},retries:10,...i};const c=retry$1.operation(i);c.attempt(async d=>{try{s(await o(d))}catch(f){if(!(f instanceof Error)){a(new TypeError(`Non-error was thrown: "${f}". You should only throw errors.`));return}if(f instanceof AbortError)c.stop(),a(f.originalError);else if(f instanceof TypeError&&!isNetworkError(f.message))c.stop(),a(f);else{decorateErrorWithCounts(f,d,i);try{await i.onFailedAttempt(f)}catch(g){a(g);return}c.retry(f)||a(c.mainError())}}}),i.signal&&!i.signal.aborted&&i.signal.addEventListener("abort",()=>{c.stop();const d=i.signal.reason===void 0?getDOMException("The operation was aborted."):i.signal.reason;a(d instanceof Error?d:getDOMException(d))},{once:!0})})}const serviceURL=new URL("https://up.web3.storage"),servicePrincipal=parse$2("did:web:web3.storage"),receiptsEndpoint="https://up.web3.storage/receipt/",connection=connect({id:servicePrincipal,codec:outbound,channel:open$2({url:serviceURL,method:"POST"})}),REQUEST_RETRIES=3;function createUploadProgressHandler$1(o,i){function s({total:a,loaded:c,lengthComputable:d}){return i({total:a,loaded:c,lengthComputable:d,url:o})}return s}async function add$3({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=c instanceof Uint8Array?c:new Uint8Array(await c.arrayBuffer()),g=await link$2(f),y=d.connection??connection,b=await pRetry(async()=>await add$a.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:{link:g,size:f.length},proofs:s,nonce:d.nonce}).execute(y),{onFailedAttempt:console.warn,retries:d.retries??REQUEST_RETRIES});if(!b.out.ok)throw new Error(`failed ${add$a.can} invocation`,{cause:b.out.error});if(b.out.ok.status==="done")return g;const $=b.out.ok,x=d.fetchWithUploadProgress||d.fetch||globalThis.fetch.bind(globalThis);let T=!1;const A=await pRetry(async()=>{var E;try{const S=await x($.url,{method:"PUT",body:c,headers:$.headers,signal:d.signal,onUploadProgress:_=>{T=!0,d.onUploadProgress&&createUploadProgressHandler$1($.url,d.onUploadProgress)(_)},duplex:"half"});if(S.status>=400&&S.status<500)throw new AbortError(`upload failed: ${S.status}`);return S}catch(S){throw((E=d.signal)==null?void 0:E.aborted)===!0?new AbortError("upload aborted"):S}},{retries:d.retries??REQUEST_RETRIES});if(!T&&d.onUploadProgress){const E=new Blob([c]);d.onUploadProgress({total:E.size,loaded:E.size,lengthComputable:!1})}if(!A.ok)throw new Error(`upload failed: ${A.status}`);return g}async function get$a({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await pRetry(async()=>await get$h.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:{link:c},proofs:s,nonce:d.nonce}).execute(f),{onFailedAttempt:console.warn,retries:d.retries??REQUEST_RETRIES});if(!g.out.ok)throw new Error(`failed ${get$h.can} invocation`,{cause:g.out.error});return g.out.ok}async function list$4({issuer:o,with:i,proofs:s,audience:a},c={}){const d=c.connection??connection,f=await list$9.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),proofs:s,nb:{cursor:c.cursor,size:c.size,pre:c.pre},nonce:c.nonce}).execute(d);if(!f.out.ok)throw new Error(`failed ${list$9.can} invocation`,{cause:f.out.error});return f.out.ok}async function remove$4({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await remove$8.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:{link:c},proofs:s,nonce:d.nonce}).execute(f);if(!g.out.ok)throw new Error(`failed ${remove$8.can} invocation`,{cause:g.out.error});return g.out}class ReceiptNotFound extends Error{constructor(i){super(),this.taskCid=i}get reason(){return`receipt not found for task ${this.taskCid} in the indexed workflow`}get name(){return"ReceiptNotFound"}}class ReceiptMissing extends Error{constructor(i){super(),this.taskCid=i}get reason(){return`receipt missing for task ${this.taskCid}`}get name(){return"ReceiptMissing"}}async function poll(o,i={}){return await pRetry(async()=>{const s=await get$9(o,i);if(s.error)throw s.error.name==="ReceiptNotFound"?s.error:new AbortError(new Error("failed to fetch blob/accept receipt",{cause:s.error}));return s.ok},{onFailedAttempt:console.warn,retries:i.retries??REQUEST_RETRIES})}async function get$9(o,i={}){const s=new URL(o.toString(),i.receiptsEndpoint??receiptsEndpoint),c=await(i.fetch??globalThis.fetch.bind(globalThis))(s);if(c.status===404)return{error:new ReceiptNotFound(o)};const d=new Uint8Array(await c.arrayBuffer()),g=(await decode$K({body:d,headers:{}})).receipts.get(o.toString());return g?{ok:g}:{error:new ReceiptMissing(o)}}function createUploadProgressHandler(o,i){return({total:a,loaded:c,lengthComputable:d})=>i({total:a,loaded:c,lengthComputable:d,url:o})}function getConcludeReceipt(o){const i=new Map;for(const s of o.iterateIPLDBlocks())i.set(`${s.cid}`,s);return view$1({root:o.capabilities[0].nb.receipt,blocks:i})}function parseBlobAddReceiptNext(o){const i=o.fx.fork,s=i.find($=>$.capabilities[0].can===allocate.can),a=i.filter($=>$.capabilities[0].can===conclude$1.can),c=i.find($=>$.capabilities[0].can===put.can),d=i.find($=>$.capabilities[0].can===accept.can);if(!s||!a.length||!c||!d)throw new Error("mandatory effects not received");const f=a.map($=>getConcludeReceipt($)),g=f.find($=>$.ran.link().equals(s.cid)),y=f.find($=>$.ran.link().equals(c.cid)),b=f.find($=>$.ran.link().equals(d.cid));if(!g)throw new Error("mandatory effects not received");return{allocate:{task:s,receipt:g},put:{task:c,receipt:y},accept:{task:d,receipt:b}}}function createConcludeInvocation(o,i,s){const a=[],c=[];for(const f of s.iterateIPLDBlocks())a.push(f),c.push(f.cid);const d=conclude$1.invoke({issuer:o,audience:i,with:o.toDIDKey(),nb:{receipt:s.link()},expiration:1/0,facts:[{...c}]});for(const f of a)d.attach(f);return d}async function add$2({issuer:o,with:i,proofs:s,audience:a},c,d,f={}){var B;const g=d instanceof Uint8Array?d:new Uint8Array(await d.arrayBuffer()),y=g.length,b=f.connection??connection,$=await pRetry(async()=>await add$4.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input$8(c,y),proofs:s,nonce:f.nonce}).execute(b),{onFailedAttempt:console.warn,retries:f.retries??REQUEST_RETRIES});if(!$.out.ok)throw new Error(`failed ${add$4.can} invocation`,{cause:$.out.error});const x=parseBlobAddReceiptNext($),{receipt:T}=x.allocate;if(!T.out.ok)throw new Error(`failed ${add$4.can} invocation`,{cause:T.out.error});const{address:A}=T.out.ok;if(A){const D=f.fetchWithUploadProgress||f.fetch||globalThis.fetch.bind(globalThis);let I=!1;const{status:O}=await pRetry(async()=>{var N;try{const L=await D(A.url,{method:"PUT",mode:"cors",body:g,headers:A.headers,signal:f.signal,onUploadProgress:R=>{I=!0,f.onUploadProgress&&createUploadProgressHandler(A.url,f.onUploadProgress)(R)},duplex:"half"});if(L.status>=400&&L.status<500)throw new AbortError(`upload failed: ${L.status}`);return L}catch(L){throw((N=f.signal)==null?void 0:N.aborted)===!0?new AbortError("upload aborted"):L}},{retries:f.retries??REQUEST_RETRIES});if(O!==200)throw new Error(`upload failed: ${O}`);if(!I&&f.onUploadProgress){const N=new Blob([g]);f.onUploadProgress({total:N.size,loaded:N.size,lengthComputable:!1})}}let{receipt:E}=x.put;if(!(E!=null&&E.out.ok)){const D=from$h(x.put.task.facts[0].keys);if(E=await issue$1({issuer:D,ran:x.put.task.cid,result:{ok:{}}}),!(await createConcludeInvocation(o,a??servicePrincipal,E).execute(b)).out.ok)throw new Error(`failed ${add$4.can} invocation`,{cause:$.out.error})}let{receipt:S}=x.accept;S!=null&&S.out.ok||(S=await poll(x.accept.task.link(),f));const _=new Map([...S.iterateIPLDBlocks()].map(D=>[`${D.cid}`,D]));return{site:view$3({root:(B=S.out.ok)==null?void 0:B.site,blocks:_})}}const ability$2=add$4.can,input$8=(o,i)=>({blob:{digest:o.bytes,size:i}});async function get$8({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await get$b.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input$7(c),proofs:s,nonce:d.nonce}).execute(f);if(!g.out.ok)throw new Error(`failed ${get$b.can} invocation`,{cause:g.out.error});return g.out}get$b.can;const input$7=o=>({digest:o.bytes});async function list$3({issuer:o,with:i,proofs:s,audience:a},c={}){const d=c.connection??connection,f=await list$5.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),proofs:s,nb:input$6(c.cursor,c.size),nonce:c.nonce}).execute(d);if(!f.out.ok)throw new Error(`failed ${list$5.can} invocation`,{cause:f.out.error});return f.out.ok}list$5.can;const input$6=(o,i)=>({cursor:o,size:i});async function remove$3({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await remove$5.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input$5(c),proofs:s,nonce:d.nonce}).execute(f);if(!g.out.ok)throw new Error(`failed ${remove$5.can} invocation`,{cause:g.out.error});return g.out}remove$5.can;const input$5=o=>({digest:o.bytes});async function add$1({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await pRetry(async()=>await add$5.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input$4(c),proofs:s}).execute(f),{onFailedAttempt:console.warn,retries:d.retries??REQUEST_RETRIES});if(!g.out.ok)throw new Error(`failed ${add$5.can} invocation`,{cause:g.out.error});return g.out.ok}const ability$1=add$5.can,input$4=o=>({index:o});async function add({issuer:o,with:i,proofs:s,audience:a},c,d,f={}){const g=f.connection??connection,y=await pRetry(async()=>await add$9.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input$3(c,d),proofs:s,nonce:f.nonce}).execute(g),{onFailedAttempt:console.warn,retries:f.retries??REQUEST_RETRIES});if(!y.out.ok)throw new Error(`failed ${add$9.can} invocation`,{cause:y.out.error});return y.out.ok}const ability=add$9.can,input$3=(o,i)=>({root:o,shards:i});async function get$7({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await pRetry(async()=>await get$g.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input$2(c),proofs:s,nonce:d.nonce}).execute(f),{onFailedAttempt:console.warn,retries:d.retries??REQUEST_RETRIES});if(!g.out.ok)throw new Error(`failed ${get$g.can} invocation`,{cause:g.out.error});return g.out.ok}get$g.can;const input$2=o=>({root:o});async function list$2({issuer:o,with:i,proofs:s,audience:a},c={}){const d=c.connection??connection,f=await list$8.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),proofs:s,nb:input$1(c.cursor,c.size,c.pre),nonce:c.nonce}).execute(d);if(!f.out.ok)throw new Error(`failed ${list$8.can} invocation`,{cause:f.out.error});return f.out.ok}list$8.can;const input$1=(o,i,s)=>({cursor:o,size:i,pre:s});async function remove$2({issuer:o,with:i,proofs:s,audience:a},c,d={}){const f=d.connection??connection,g=await remove$7.invoke({issuer:o,audience:a??servicePrincipal,with:SpaceDID$1.from(i),nb:input(c),proofs:s,nonce:d.nonce}).execute(f);if(!g.out.ok)throw new Error(`failed ${remove$7.can} invocation`,{cause:g.out.error});return g.out.ok}remove$7.can;const input=o=>({root:o});function equals$8(o,i){if(o===i)return!0;if(o.byteLength!==i.byteLength)return!1;for(let s=0;s=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src$4=base$4,_brrp__multiformats_scope_baseX$4=src$4;let Encoder$4=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseEncode");this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}},Decoder$4=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseDecode");U(this,"prefixCodePoint");this.name=i,this.prefix=s;const c=s.codePointAt(0);if(c===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=c,this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or$6(this,i)}},ComposedDecoder$4=class{constructor(i){U(this,"decoders");this.decoders=i}or(i){return or$6(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a!=null)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$6(o,i){return new ComposedDecoder$4({...o.decoders??{[o.prefix]:o},...i.decoders??{[i.prefix]:i}})}let Codec$4=class{constructor(i,s,a,c){U(this,"name");U(this,"prefix");U(this,"baseEncode");U(this,"baseDecode");U(this,"encoder");U(this,"decoder");this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder$4(i,s,a),this.decoder=new Decoder$4(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}};function from$b({name:o,prefix:i,encode:s,decode:a}){return new Codec$4(o,i,s,a)}function baseX$4({name:o,prefix:i,alphabet:s}){const{encode:a,decode:c}=_brrp__multiformats_scope_baseX$4(s,o);return from$b({prefix:i,name:o,encode:a,decode:d=>coerce$4(c(d))})}function decode$l(o,i,s,a){const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f}function encode$e(o,i,s){const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f!==0&&(d+=i[c&g<=INT$5;)i[s++]=o&255|MSB$5,o/=128;for(;o&MSBALL$5;)i[s++]=o&255|MSB$5,o>>>=7;return i[s]=o|0,encode$d.bytes=s-a+1,i}var decode$k=read$5,MSB$1$5=128,REST$1$5=127;function read$5(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$5.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$5)<=MSB$1$5);return read$5.bytes=d-a,s}var N1$4=Math.pow(2,7),N2$4=Math.pow(2,14),N3$4=Math.pow(2,21),N4$4=Math.pow(2,28),N5$4=Math.pow(2,35),N6$4=Math.pow(2,42),N7$4=Math.pow(2,49),N8$4=Math.pow(2,56),N9$4=Math.pow(2,63),length$4=function(o){return o{const[x,T]=decode$j(i.subarray(s));return s+=T,x};let c=a(),d=DAG_PB_CODE$4;if(c===18?(c=0,s=0):d=a(),c!==0&&c!==1)throw new RangeError(`Invalid CID version ${c}`);const f=s,g=a(),y=a(),b=s+y,$=b-f;return{version:c,codec:d,multihashCode:g,digestSize:y,multihashSize:$,size:b}}static parse(i,s){const[a,c]=parseCIDtoBytes$3(i,s),d=me.decode(c);if(d.version===0&&i[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache$3(d).set(a,i),d}};function parseCIDtoBytes$3(o,i){switch(o[0]){case"Q":{const s=i??base58btc$3;return[base58btc$3.prefix,s.decode(`${base58btc$3.prefix}${o}`)]}case base58btc$3.prefix:{const s=i??base58btc$3;return[base58btc$3.prefix,s.decode(o)]}case base32$3.prefix:{const s=i??base32$3;return[base32$3.prefix,s.decode(o)]}case base36$2.prefix:{const s=i??base36$2;return[base36$2.prefix,s.decode(o)]}default:{if(i==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[o[0],i.decode(o)]}}}function toStringV0$3(o,i,s){const{prefix:a}=s;if(a!==base58btc$3.prefix)throw Error(`Cannot string encode V0 in ${s.name} encoding`);const c=i.get(a);if(c==null){const d=s.encode(o).slice(1);return i.set(a,d),d}else return c}function toStringV1$3(o,i,s){const{prefix:a}=s,c=i.get(a);if(c==null){const d=s.encode(o);return i.set(a,d),d}else return c}const DAG_PB_CODE$4=112,SHA_256_CODE$3=18;function encodeCID$3(o,i,s){const a=encodingLength$4(o),c=a+encodingLength$4(i),d=new Uint8Array(c+s.byteLength);return encodeTo$4(o,d,0),encodeTo$4(i,d,a),d.set(s,c),d}const cidSymbol$3=Symbol.for("@ipld/js-cid/CID"),textDecoder=new TextDecoder;function decodeVarint(o,i){let s=0;for(let a=0;;a+=7){if(a>=64)throw new Error("protobuf: varint overflow");if(i>=o.length)throw new Error("protobuf: unexpected end of data");const c=o[i++];if(s+=a<28?(c&127)<o.length)throw new Error("protobuf: unexpected end of data");return[o.subarray(i,a),a]}function decodeKey(o,i){let s;return[s,i]=decodeVarint(o,i),[s&7,s>>3,i]}function decodeLink(o){const i={},s=o.length;let a=0;for(;as)throw new Error("protobuf: (PBLink) unexpected end of data");return i}function decodeNode(o){const i=o.length;let s=0,a,c=!1,d;for(;si)throw new Error("protobuf: (PBNode) unexpected end of data");const f={};return d&&(f.Data=d),f.Links=a||[],f}const textEncoder$1=new TextEncoder,maxInt32=2**32,maxUInt32=2**31;function encodeLink$1(o,i){let s=i.length;if(typeof o.Tsize=="number"){if(o.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(o.Tsize))throw new Error("Tsize too large for encoding");s=encodeVarint(i,s,o.Tsize)-1,i[s]=24}if(typeof o.Name=="string"){const a=textEncoder$1.encode(o.Name);s-=a.length,i.set(a,s),s=encodeVarint(i,s,a.length)-1,i[s]=18}return o.Hash&&(s-=o.Hash.length,i.set(o.Hash,s),s=encodeVarint(i,s,o.Hash.length)-1,i[s]=10),i.length-s}function encodeNode(o){const i=sizeNode(o),s=new Uint8Array(i);let a=i;if(o.Data&&(a-=o.Data.length,s.set(o.Data,a),a=encodeVarint(s,a,o.Data.length)-1,s[a]=10),o.Links)for(let c=o.Links.length-1;c>=0;c--){const d=encodeLink$1(o.Links[c],s.subarray(0,a));a-=d,a=encodeVarint(s,a,d)-1,s[a]=18}return s}function sizeLink(o){let i=0;if(o.Hash){const s=o.Hash.length;i+=1+s+sov(s)}if(typeof o.Name=="string"){const s=textEncoder$1.encode(o.Name).length;i+=1+s+sov(s)}return typeof o.Tsize=="number"&&(i+=1+sov(o.Tsize)),i}function sizeNode(o){let i=0;if(o.Data){const s=o.Data.length;i+=1+s+sov(s)}if(o.Links)for(const s of o.Links){const a=sizeLink(s);i+=1+a+sov(a)}return i}function encodeVarint(o,i,s){i-=sov(s);const a=i;for(;s>=maxUInt32;)o[i++]=s&127|128,s/=128;for(;s>=128;)o[i++]=s&127|128,s>>>=7;return o[i]=s,a}function sov(o){return o%2===0&&o++,Math.floor((len64(o)+6)/7)}function len64(o){let i=0;return o>=maxInt32&&(o=Math.floor(o/maxInt32),i=32),o>=65536&&(o>>>=16,i+=16),o>=256&&(o>>>=8,i+=8),i+len8tab[o]}const len8tab=[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],pbNodeProperties=["Data","Links"],pbLinkProperties=["Hash","Name","Tsize"],textEncoder=new TextEncoder;function linkComparator(o,i){if(o===i)return 0;const s=o.Name?textEncoder.encode(o.Name):[],a=i.Name?textEncoder.encode(i.Name):[];let c=s.length,d=a.length;for(let f=0,g=Math.min(c,d);f!i.includes(s))}function asLink(o){if(typeof o.asCID=="object"){const s=CID$3.asCID(o);if(!s)throw new TypeError("Invalid DAG-PB form");return{Hash:s}}if(typeof o!="object"||Array.isArray(o))throw new TypeError("Invalid DAG-PB form");const i={};if(o.Hash){let s=CID$3.asCID(o.Hash);try{s||(typeof o.Hash=="string"?s=CID$3.parse(o.Hash):o.Hash instanceof Uint8Array&&(s=CID$3.decode(o.Hash)))}catch(a){throw new TypeError(`Invalid DAG-PB form: ${a.message}`)}s&&(i.Hash=s)}if(!i.Hash)throw new TypeError("Invalid DAG-PB form");return typeof o.Name=="string"&&(i.Name=o.Name),typeof o.Tsize=="number"&&(i.Tsize=o.Tsize),i}function prepare(o){if((o instanceof Uint8Array||typeof o=="string")&&(o={Data:o}),typeof o!="object"||Array.isArray(o))throw new TypeError("Invalid DAG-PB form");const i={};if(o.Data!==void 0)if(typeof o.Data=="string")i.Data=textEncoder.encode(o.Data);else if(o.Data instanceof Uint8Array)i.Data=o.Data;else throw new TypeError("Invalid DAG-PB form");if(o.Links!==void 0)if(Array.isArray(o.Links))i.Links=o.Links.map(asLink),i.Links.sort(linkComparator);else throw new TypeError("Invalid DAG-PB form");else i.Links=[];return i}function validate(o){if(!o||typeof o!="object"||Array.isArray(o)||o instanceof Uint8Array||o["/"]&&o["/"]===o.bytes)throw new TypeError("Invalid DAG-PB form");if(!hasOnlyProperties(o,pbNodeProperties))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(o.Data!==void 0&&!(o.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(o.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let i=0;i0&&linkComparator(s,o.Links[i-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function toByteView(o){return o instanceof ArrayBuffer?new Uint8Array(o,0,o.byteLength):o}const code$2=112;function encode$c(o){validate(o);const i={};return o.Links&&(i.Links=o.Links.map(s=>{const a={};return s.Hash&&(a.Hash=s.Hash.bytes),s.Name!==void 0&&(a.Name=s.Name),s.Tsize!==void 0&&(a.Tsize=s.Tsize),a})),o.Data&&(i.Data=o.Data),encodeNode(i)}function decode$h(o){const i=toByteView(o),s=decodeNode(i),a={};return s.Data&&(a.Data=s.Data),s.Links&&(a.Links=s.Links.map(c=>{const d={};try{d.Hash=CID$3.decode(c.Hash)}catch{}if(!d.Hash)throw new Error("Invalid Hash field found in link, expected CID");return c.Name!==void 0&&(d.Name=c.Name),c.Tsize!==void 0&&(d.Tsize=c.Tsize),d})),a}var indexMinimal={},minimal$1={},aspromise=asPromise;function asPromise(o,i){for(var s=new Array(arguments.length-1),a=0,c=2,d=!0;c1&&g.charAt(y)==="=";)++b;return Math.ceil(g.length*3)/4-b};for(var s=new Array(64),a=new Array(123),c=0;c<64;)a[s[c]=c<26?c+65:c<52?c+71:c<62?c-4:c-59|43]=c++;i.encode=function(g,y,b){for(var $=null,x=[],T=0,A=0,E;y>2],E=(S&3)<<4,A=1;break;case 1:x[T++]=s[E|S>>4],E=(S&15)<<2,A=2;break;case 2:x[T++]=s[E|S>>6],x[T++]=s[S&63],A=0;break}T>8191&&(($||($=[])).push(String.fromCharCode.apply(String,x)),T=0)}return A&&(x[T++]=s[E],x[T++]=61,A===1&&(x[T++]=61)),$?(T&&$.push(String.fromCharCode.apply(String,x.slice(0,T))),$.join("")):String.fromCharCode.apply(String,x.slice(0,T))};var d="invalid encoding";i.decode=function(g,y,b){for(var $=b,x=0,T,A=0;A1)break;if((E=a[E])===void 0)throw Error(d);switch(x){case 0:T=E,x=1;break;case 1:y[b++]=T<<2|(E&48)>>4,T=E,x=2;break;case 2:y[b++]=(T&15)<<4|(E&60)>>2,T=E,x=3;break;case 3:y[b++]=(T&3)<<6|E,x=0;break}}if(x===1)throw Error(d);return b-$},i.test=function(g){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(g)}})(base64$1);var eventemitter=EventEmitter;function EventEmitter(){this._listeners={}}EventEmitter.prototype.on=function(i,s,a){return(this._listeners[i]||(this._listeners[i]=[])).push({fn:s,ctx:a||this}),this};EventEmitter.prototype.off=function(i,s){if(i===void 0)this._listeners={};else if(s===void 0)this._listeners[i]=[];else for(var a=this._listeners[i],c=0;c0?0:2147483648,d,f);else if(isNaN(c))a(2143289344,d,f);else if(c>34028234663852886e22)a((g<<31|2139095040)>>>0,d,f);else if(c<11754943508222875e-54)a((g<<31|Math.round(c/1401298464324817e-60))>>>0,d,f);else{var y=Math.floor(Math.log(c)/Math.LN2),b=Math.round(c*Math.pow(2,-y)*8388608)&8388607;a((g<<31|y+127<<23|b)>>>0,d,f)}}o.writeFloatLE=i.bind(null,writeUintLE),o.writeFloatBE=i.bind(null,writeUintBE);function s(a,c,d){var f=a(c,d),g=(f>>31)*2+1,y=f>>>23&255,b=f&8388607;return y===255?b?NaN:g*(1/0):y===0?g*1401298464324817e-60*b:g*Math.pow(2,y-150)*(b+8388608)}o.readFloatLE=s.bind(null,readUintLE),o.readFloatBE=s.bind(null,readUintBE)}(),typeof Float64Array<"u"?function(){var i=new Float64Array([-0]),s=new Uint8Array(i.buffer),a=s[7]===128;function c(y,b,$){i[0]=y,b[$]=s[0],b[$+1]=s[1],b[$+2]=s[2],b[$+3]=s[3],b[$+4]=s[4],b[$+5]=s[5],b[$+6]=s[6],b[$+7]=s[7]}function d(y,b,$){i[0]=y,b[$]=s[7],b[$+1]=s[6],b[$+2]=s[5],b[$+3]=s[4],b[$+4]=s[3],b[$+5]=s[2],b[$+6]=s[1],b[$+7]=s[0]}o.writeDoubleLE=a?c:d,o.writeDoubleBE=a?d:c;function f(y,b){return s[0]=y[b],s[1]=y[b+1],s[2]=y[b+2],s[3]=y[b+3],s[4]=y[b+4],s[5]=y[b+5],s[6]=y[b+6],s[7]=y[b+7],i[0]}function g(y,b){return s[7]=y[b],s[6]=y[b+1],s[5]=y[b+2],s[4]=y[b+3],s[3]=y[b+4],s[2]=y[b+5],s[1]=y[b+6],s[0]=y[b+7],i[0]}o.readDoubleLE=a?f:g,o.readDoubleBE=a?g:f}():function(){function i(a,c,d,f,g,y){var b=f<0?1:0;if(b&&(f=-f),f===0)a(0,g,y+c),a(1/f>0?0:2147483648,g,y+d);else if(isNaN(f))a(0,g,y+c),a(2146959360,g,y+d);else if(f>17976931348623157e292)a(0,g,y+c),a((b<<31|2146435072)>>>0,g,y+d);else{var $;if(f<22250738585072014e-324)$=f/5e-324,a($>>>0,g,y+c),a((b<<31|$/4294967296)>>>0,g,y+d);else{var x=Math.floor(Math.log(f)/Math.LN2);x===1024&&(x=1023),$=f*Math.pow(2,-x),a($*4503599627370496>>>0,g,y+c),a((b<<31|x+1023<<20|$*1048576&1048575)>>>0,g,y+d)}}}o.writeDoubleLE=i.bind(null,writeUintLE,0,4),o.writeDoubleBE=i.bind(null,writeUintBE,4,0);function s(a,c,d,f,g){var y=a(f,g+c),b=a(f,g+d),$=(b>>31)*2+1,x=b>>>20&2047,T=4294967296*(b&1048575)+y;return x===2047?T?NaN:$*(1/0):x===0?$*5e-324*T:$*Math.pow(2,x-1075)*(T+4503599627370496)}o.readDoubleLE=s.bind(null,readUintLE,0,4),o.readDoubleBE=s.bind(null,readUintBE,4,0)}(),o}function writeUintLE(o,i,s){i[s]=o&255,i[s+1]=o>>>8&255,i[s+2]=o>>>16&255,i[s+3]=o>>>24}function writeUintBE(o,i,s){i[s]=o>>>24,i[s+1]=o>>>16&255,i[s+2]=o>>>8&255,i[s+3]=o&255}function readUintLE(o,i){return(o[i]|o[i+1]<<8|o[i+2]<<16|o[i+3]<<24)>>>0}function readUintBE(o,i){return(o[i]<<24|o[i+1]<<16|o[i+2]<<8|o[i+3])>>>0}var inquire_1=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(o){}return null}var utf8$5={};(function(o){var i=o;i.length=function(a){for(var c=0,d=0,f=0;f191&&$<224?y[b++]=($&31)<<6|a[c++]&63:$>239&&$<365?($=(($&7)<<18|(a[c++]&63)<<12|(a[c++]&63)<<6|a[c++]&63)-65536,y[b++]=55296+($>>10),y[b++]=56320+($&1023)):y[b++]=($&15)<<12|(a[c++]&63)<<6|a[c++]&63,b>8191&&((g||(g=[])).push(String.fromCharCode.apply(String,y)),b=0);return g?(b&&g.push(String.fromCharCode.apply(String,y.slice(0,b))),g.join("")):String.fromCharCode.apply(String,y.slice(0,b))},i.write=function(a,c,d){for(var f=d,g,y,b=0;b>6|192,c[d++]=g&63|128):(g&64512)===55296&&((y=a.charCodeAt(b+1))&64512)===56320?(g=65536+((g&1023)<<10)+(y&1023),++b,c[d++]=g>>18|240,c[d++]=g>>12&63|128,c[d++]=g>>6&63|128,c[d++]=g&63|128):(c[d++]=g>>12|224,c[d++]=g>>6&63|128,c[d++]=g&63|128);return d-f}})(utf8$5);var pool_1=pool;function pool(o,i,s){var a=s||8192,c=a>>>1,d=null,f=a;return function(y){if(y<1||y>c)return o(y);f+y>a&&(d=o(a),f=0);var b=i.call(d,f,f+=y);return f&7&&(f=(f|7)+1),b}}var longbits,hasRequiredLongbits;function requireLongbits(){if(hasRequiredLongbits)return longbits;hasRequiredLongbits=1,longbits=i;var o=requireMinimal();function i(d,f){this.lo=d>>>0,this.hi=f>>>0}var s=i.zero=new i(0,0);s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1};var a=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(f){if(f===0)return s;var g=f<0;g&&(f=-f);var y=f>>>0,b=(f-y)/4294967296>>>0;return g&&(b=~b>>>0,y=~y>>>0,++y>4294967295&&(y=0,++b>4294967295&&(b=0))),new i(y,b)},i.from=function(f){if(typeof f=="number")return i.fromNumber(f);if(o.isString(f))if(o.Long)f=o.Long.fromString(f);else return i.fromNumber(parseInt(f,10));return f.low||f.high?new i(f.low>>>0,f.high>>>0):s},i.prototype.toNumber=function(f){if(!f&&this.hi>>>31){var g=~this.lo+1>>>0,y=~this.hi>>>0;return g||(y=y+1>>>0),-(g+y*4294967296)}return this.lo+this.hi*4294967296},i.prototype.toLong=function(f){return o.Long?new o.Long(this.lo|0,this.hi|0,!!f):{low:this.lo|0,high:this.hi|0,unsigned:!!f}};var c=String.prototype.charCodeAt;return i.fromHash=function(f){return f===a?s:new i((c.call(f,0)|c.call(f,1)<<8|c.call(f,2)<<16|c.call(f,3)<<24)>>>0,(c.call(f,4)|c.call(f,5)<<8|c.call(f,6)<<16|c.call(f,7)<<24)>>>0)},i.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)},i.prototype.zzEncode=function(){var f=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^f)>>>0,this.lo=(this.lo<<1^f)>>>0,this},i.prototype.zzDecode=function(){var f=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^f)>>>0,this.hi=(this.hi>>>1^f)>>>0,this},i.prototype.length=function(){var f=this.lo,g=(this.lo>>>28|this.hi<<4)>>>0,y=this.hi>>>24;return y===0?g===0?f<16384?f<128?1:2:f<2097152?3:4:g<16384?g<128?5:6:g<2097152?7:8:y<128?9:10},longbits}var hasRequiredMinimal;function requireMinimal(){return hasRequiredMinimal||(hasRequiredMinimal=1,function(o){var i=o;i.asPromise=aspromise,i.base64=base64$1,i.EventEmitter=eventemitter,i.float=float,i.inquire=inquire_1,i.utf8=utf8$5,i.pool=pool_1,i.LongBits=requireLongbits(),i.isNode=!!(typeof commonjsGlobal<"u"&&commonjsGlobal&&commonjsGlobal.process&&commonjsGlobal.process.versions&&commonjsGlobal.process.versions.node),i.global=i.isNode&&commonjsGlobal||typeof window<"u"&&window||typeof self<"u"&&self||commonjsGlobal,i.emptyArray=Object.freeze?Object.freeze([]):[],i.emptyObject=Object.freeze?Object.freeze({}):{},i.isInteger=Number.isInteger||function(d){return typeof d=="number"&&isFinite(d)&&Math.floor(d)===d},i.isString=function(d){return typeof d=="string"||d instanceof String},i.isObject=function(d){return d&&typeof d=="object"},i.isset=i.isSet=function(d,f){var g=d[f];return g!=null&&d.hasOwnProperty(f)?typeof g!="object"||(Array.isArray(g)?g.length:Object.keys(g).length)>0:!1},i.Buffer=function(){try{var c=i.inquire("buffer").Buffer;return c.prototype.utf8Write?c:null}catch{return null}}(),i._Buffer_from=null,i._Buffer_allocUnsafe=null,i.newBuffer=function(d){return typeof d=="number"?i.Buffer?i._Buffer_allocUnsafe(d):new i.Array(d):i.Buffer?i._Buffer_from(d):typeof Uint8Array>"u"?d:new Uint8Array(d)},i.Array=typeof Uint8Array<"u"?Uint8Array:Array,i.Long=i.global.dcodeIO&&i.global.dcodeIO.Long||i.global.Long||i.inquire("long"),i.key2Re=/^true|false|0|1$/,i.key32Re=/^-?(?:0|[1-9][0-9]*)$/,i.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,i.longToHash=function(d){return d?i.LongBits.from(d).toHash():i.LongBits.zeroHash},i.longFromHash=function(d,f){var g=i.LongBits.fromHash(d);return i.Long?i.Long.fromBits(g.lo,g.hi,f):g.toNumber(!!f)};function s(c,d,f){for(var g=Object.keys(d),y=0;y-1;--b)if(f[y[b]]===1&&this[y[b]]!==void 0&&this[y[b]]!==null)return y[b]}},i.oneOfSetter=function(d){return function(f){for(var g=0;g127;)i[s++]=o&127|128,o>>>=7;i[s]=o}function VarintOp(o,i){this.len=o,this.next=void 0,this.val=i}VarintOp.prototype=Object.create(Op.prototype);VarintOp.prototype.fn=writeVarint32;Writer$1.prototype.uint32=function o(i){return this.len+=(this.tail=this.tail.next=new VarintOp((i=i>>>0)<128?1:i<16384?2:i<2097152?3:i<268435456?4:5,i)).len,this};Writer$1.prototype.int32=function o(i){return i<0?this._push(writeVarint64,10,LongBits$1.fromNumber(i)):this.uint32(i)};Writer$1.prototype.sint32=function o(i){return this.uint32((i<<1^i>>31)>>>0)};function writeVarint64(o,i,s){for(;o.hi;)i[s++]=o.lo&127|128,o.lo=(o.lo>>>7|o.hi<<25)>>>0,o.hi>>>=7;for(;o.lo>127;)i[s++]=o.lo&127|128,o.lo=o.lo>>>7;i[s++]=o.lo}Writer$1.prototype.uint64=function o(i){var s=LongBits$1.from(i);return this._push(writeVarint64,s.length(),s)};Writer$1.prototype.int64=Writer$1.prototype.uint64;Writer$1.prototype.sint64=function o(i){var s=LongBits$1.from(i).zzEncode();return this._push(writeVarint64,s.length(),s)};Writer$1.prototype.bool=function o(i){return this._push(writeByte,1,i?1:0)};function writeFixed32(o,i,s){i[s]=o&255,i[s+1]=o>>>8&255,i[s+2]=o>>>16&255,i[s+3]=o>>>24}Writer$1.prototype.fixed32=function o(i){return this._push(writeFixed32,4,i>>>0)};Writer$1.prototype.sfixed32=Writer$1.prototype.fixed32;Writer$1.prototype.fixed64=function o(i){var s=LongBits$1.from(i);return this._push(writeFixed32,4,s.lo)._push(writeFixed32,4,s.hi)};Writer$1.prototype.sfixed64=Writer$1.prototype.fixed64;Writer$1.prototype.float=function o(i){return this._push(util$4.float.writeFloatLE,4,i)};Writer$1.prototype.double=function o(i){return this._push(util$4.float.writeDoubleLE,8,i)};var writeBytes=util$4.Array.prototype.set?function o(i,s,a){s.set(i,a)}:function o(i,s,a){for(var c=0;c>>0;if(!s)return this._push(writeByte,1,0);if(util$4.isString(i)){var a=Writer$1.alloc(s=base64.length(i));base64.decode(i,a,0),i=a}return this.uint32(s)._push(writeBytes,s,i)};Writer$1.prototype.string=function o(i){var s=utf8$4.length(i);return s?this.uint32(s)._push(utf8$4.write,s,i):this._push(writeByte,1,0)};Writer$1.prototype.fork=function o(){return this.states=new State$1(this),this.head=this.tail=new Op(noop$1,0,0),this.len=0,this};Writer$1.prototype.reset=function o(){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 Op(noop$1,0,0),this.len=0),this};Writer$1.prototype.ldelim=function o(){var i=this.head,s=this.tail,a=this.len;return this.reset().uint32(a),a&&(this.tail.next=i.next,this.tail=s,this.len+=a),this};Writer$1.prototype.finish=function o(){for(var i=this.head.next,s=this.constructor.alloc(this.len),a=0;i;)i.fn(i.val,s,a),a+=i.len,i=i.next;return s};Writer$1._configure=function(o){BufferWriter$1=o,Writer$1.create=create$e(),BufferWriter$1._configure()};var writer_buffer=BufferWriter,Writer=writer;(BufferWriter.prototype=Object.create(Writer.prototype)).constructor=BufferWriter;var util$3=requireMinimal();function BufferWriter(){Writer.call(this)}BufferWriter._configure=function(){BufferWriter.alloc=util$3._Buffer_allocUnsafe,BufferWriter.writeBytesBuffer=util$3.Buffer&&util$3.Buffer.prototype instanceof Uint8Array&&util$3.Buffer.prototype.set.name==="set"?function(i,s,a){s.set(i,a)}:function(i,s,a){if(i.copy)i.copy(s,a,0,i.length);else for(var c=0;c>>0;return this.uint32(s),s&&this._push(BufferWriter.writeBytesBuffer,s,i),this};function writeStringBuffer(o,i,s){o.length<40?util$3.utf8.write(o,i,s):i.utf8Write?i.utf8Write(o,s):i.write(o,s)}BufferWriter.prototype.string=function o(i){var s=util$3.Buffer.byteLength(i);return this.uint32(s),s&&this._push(writeStringBuffer,s,i),this};BufferWriter._configure();var reader=Reader$1,util$2=requireMinimal(),BufferReader$1,LongBits=util$2.LongBits,utf8$3=util$2.utf8;function indexOutOfRange(o,i){return RangeError("index out of range: "+o.pos+" + "+(i||1)+" > "+o.len)}function Reader$1(o){this.buf=o,this.pos=0,this.len=o.length}var create_array=typeof Uint8Array<"u"?function o(i){if(i instanceof Uint8Array||Array.isArray(i))return new Reader$1(i);throw Error("illegal buffer")}:function o(i){if(Array.isArray(i))return new Reader$1(i);throw Error("illegal buffer")},create$d=function o(){return util$2.Buffer?function(s){return(Reader$1.create=function(c){return util$2.Buffer.isBuffer(c)?new BufferReader$1(c):create_array(c)})(s)}:create_array};Reader$1.create=create$d();Reader$1.prototype._slice=util$2.Array.prototype.subarray||util$2.Array.prototype.slice;Reader$1.prototype.uint32=function o(){var i=4294967295;return function(){if(i=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(i=(i|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(i=(i|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(i=(i|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(i=(i|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return i;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange(this,10);return i}}();Reader$1.prototype.int32=function o(){return this.uint32()|0};Reader$1.prototype.sint32=function o(){var i=this.uint32();return i>>>1^-(i&1)|0};function readLongVarint(){var o=new LongBits(0,0),i=0;if(this.len-this.pos>4){for(;i<4;++i)if(o.lo=(o.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return o;if(o.lo=(o.lo|(this.buf[this.pos]&127)<<28)>>>0,o.hi=(o.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return o;i=0}else{for(;i<3;++i){if(this.pos>=this.len)throw indexOutOfRange(this);if(o.lo=(o.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return o}return o.lo=(o.lo|(this.buf[this.pos++]&127)<>>0,o}if(this.len-this.pos>4){for(;i<5;++i)if(o.hi=(o.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return o}else for(;i<5;++i){if(this.pos>=this.len)throw indexOutOfRange(this);if(o.hi=(o.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return o}throw Error("invalid varint encoding")}Reader$1.prototype.bool=function o(){return this.uint32()!==0};function readFixed32_end(o,i){return(o[i-4]|o[i-3]<<8|o[i-2]<<16|o[i-1]<<24)>>>0}Reader$1.prototype.fixed32=function o(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)};Reader$1.prototype.sfixed32=function o(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)|0};function readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange(this,8);return new LongBits(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader$1.prototype.float=function o(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var i=util$2.float.readFloatLE(this.buf,this.pos);return this.pos+=4,i};Reader$1.prototype.double=function o(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var i=util$2.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,i};Reader$1.prototype.bytes=function o(){var i=this.uint32(),s=this.pos,a=this.pos+i;if(a>this.len)throw indexOutOfRange(this,i);if(this.pos+=i,Array.isArray(this.buf))return this.buf.slice(s,a);if(s===a){var c=util$2.Buffer;return c?c.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,s,a)};Reader$1.prototype.string=function o(){var i=this.bytes();return utf8$3.read(i,0,i.length)};Reader$1.prototype.skip=function o(i){if(typeof i=="number"){if(this.pos+i>this.len)throw indexOutOfRange(this,i);this.pos+=i}else do if(this.pos>=this.len)throw indexOutOfRange(this);while(this.buf[this.pos++]&128);return this};Reader$1.prototype.skipType=function(o){switch(o){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(o=this.uint32()&7)!==4;)this.skipType(o);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+o+" at offset "+this.pos)}return this};Reader$1._configure=function(o){BufferReader$1=o,Reader$1.create=create$d(),BufferReader$1._configure();var i=util$2.Long?"toLong":"toNumber";util$2.merge(Reader$1.prototype,{int64:function(){return readLongVarint.call(this)[i](!1)},uint64:function(){return readLongVarint.call(this)[i](!0)},sint64:function(){return readLongVarint.call(this).zzDecode()[i](!1)},fixed64:function(){return readFixed64.call(this)[i](!0)},sfixed64:function(){return readFixed64.call(this)[i](!1)}})};var reader_buffer=BufferReader,Reader=reader;(BufferReader.prototype=Object.create(Reader.prototype)).constructor=BufferReader;var util$1=requireMinimal();function BufferReader(o){Reader.call(this,o)}BufferReader._configure=function(){util$1.Buffer&&(BufferReader.prototype._slice=util$1.Buffer.prototype.slice)};BufferReader.prototype.string=function o(){var i=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+i,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+i,this.len))};BufferReader._configure();var rpc={},service=Service,util=requireMinimal();(Service.prototype=Object.create(util.EventEmitter.prototype)).constructor=Service;function Service(o,i,s){if(typeof o!="function")throw TypeError("rpcImpl must be a function");util.EventEmitter.call(this),this.rpcImpl=o,this.requestDelimited=!!i,this.responseDelimited=!!s}Service.prototype.rpcCall=function o(i,s,a,c,d){if(!c)throw TypeError("request must be specified");var f=this;if(!d)return util.asPromise(o,f,i,s,a,c);if(!f.rpcImpl){setTimeout(function(){d(Error("already ended"))},0);return}try{return f.rpcImpl(i,s[f.requestDelimited?"encodeDelimited":"encode"](c).finish(),function(y,b){if(y)return f.emit("error",y,i),d(y);if(b===null){f.end(!0);return}if(!(b instanceof a))try{b=a[f.responseDelimited?"decodeDelimited":"decode"](b)}catch($){return f.emit("error",$,i),d($)}return f.emit("data",b,i),d(null,b)})}catch(g){f.emit("error",g,i),setTimeout(function(){d(g)},0);return}};Service.prototype.end=function o(i){return this.rpcImpl&&(i||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this};(function(o){var i=o;i.Service=service})(rpc);var roots={};(function(o){var i=o;i.build="minimal",i.Writer=writer,i.BufferWriter=writer_buffer,i.Reader=reader,i.BufferReader=reader_buffer,i.util=requireMinimal(),i.rpc=rpc,i.roots=roots,i.configure=s;function s(){i.util._configure(),i.Writer._configure(i.BufferWriter),i.Reader._configure(i.BufferReader)}s()})(indexMinimal);var minimal=indexMinimal;const $protobuf=getDefaultExportFromCjs(minimal),$Reader=$protobuf.Reader,$Writer=$protobuf.Writer,$util=$protobuf.util,$root=$protobuf.roots.unixfs||($protobuf.roots.unixfs={}),Data=$root.Data=(()=>{function o(i){if(this.blocksizes=[],i)for(var s=Object.keys(i),a=0;a>>3){case 1:d.Type=s.int32();break;case 2:d.Data=s.bytes();break;case 3:d.filesize=s.uint64();break;case 4:if(d.blocksizes&&d.blocksizes.length||(d.blocksizes=[]),(f&7)===2)for(var g=s.uint32()+s.pos;s.pos>>0,s.filesize.high>>>0).toNumber(!0))),s.blocksizes){if(!Array.isArray(s.blocksizes))throw TypeError(".Data.blocksizes: array expected");a.blocksizes=[];for(var c=0;c>>0,s.blocksizes[c].high>>>0).toNumber(!0))}if(s.hashType!=null&&($util.Long?(a.hashType=$util.Long.fromValue(s.hashType)).unsigned=!0:typeof s.hashType=="string"?a.hashType=parseInt(s.hashType,10):typeof s.hashType=="number"?a.hashType=s.hashType:typeof s.hashType=="object"&&(a.hashType=new $util.LongBits(s.hashType.low>>>0,s.hashType.high>>>0).toNumber(!0))),s.fanout!=null&&($util.Long?(a.fanout=$util.Long.fromValue(s.fanout)).unsigned=!0:typeof s.fanout=="string"?a.fanout=parseInt(s.fanout,10):typeof s.fanout=="number"?a.fanout=s.fanout:typeof s.fanout=="object"&&(a.fanout=new $util.LongBits(s.fanout.low>>>0,s.fanout.high>>>0).toNumber(!0))),s.mode!=null&&(a.mode=s.mode>>>0),s.mtime!=null){if(typeof s.mtime!="object")throw TypeError(".Data.mtime: object expected");a.mtime=$root.UnixTime.fromObject(s.mtime)}return a},o.toObject=function(s,a){a||(a={});var c={};if((a.arrays||a.defaults)&&(c.blocksizes=[]),a.defaults){if(c.Type=a.enums===String?"Raw":0,a.bytes===String?c.Data="":(c.Data=[],a.bytes!==Array&&(c.Data=$util.newBuffer(c.Data))),$util.Long){var d=new $util.Long(0,0,!0);c.filesize=a.longs===String?d.toString():a.longs===Number?d.toNumber():d}else c.filesize=a.longs===String?"0":0;if($util.Long){var d=new $util.Long(0,0,!0);c.hashType=a.longs===String?d.toString():a.longs===Number?d.toNumber():d}else c.hashType=a.longs===String?"0":0;if($util.Long){var d=new $util.Long(0,0,!0);c.fanout=a.longs===String?d.toString():a.longs===Number?d.toNumber():d}else c.fanout=a.longs===String?"0":0;c.mode=0,c.mtime=null}if(s.Type!=null&&s.hasOwnProperty("Type")&&(c.Type=a.enums===String?$root.Data.DataType[s.Type]:s.Type),s.Data!=null&&s.hasOwnProperty("Data")&&(c.Data=a.bytes===String?$util.base64.encode(s.Data,0,s.Data.length):a.bytes===Array?Array.prototype.slice.call(s.Data):s.Data),s.filesize!=null&&s.hasOwnProperty("filesize")&&(typeof s.filesize=="number"?c.filesize=a.longs===String?String(s.filesize):s.filesize:c.filesize=a.longs===String?$util.Long.prototype.toString.call(s.filesize):a.longs===Number?new $util.LongBits(s.filesize.low>>>0,s.filesize.high>>>0).toNumber(!0):s.filesize),s.blocksizes&&s.blocksizes.length){c.blocksizes=[];for(var f=0;f>>0,s.blocksizes[f].high>>>0).toNumber(!0):s.blocksizes[f]}return s.hashType!=null&&s.hasOwnProperty("hashType")&&(typeof s.hashType=="number"?c.hashType=a.longs===String?String(s.hashType):s.hashType:c.hashType=a.longs===String?$util.Long.prototype.toString.call(s.hashType):a.longs===Number?new $util.LongBits(s.hashType.low>>>0,s.hashType.high>>>0).toNumber(!0):s.hashType),s.fanout!=null&&s.hasOwnProperty("fanout")&&(typeof s.fanout=="number"?c.fanout=a.longs===String?String(s.fanout):s.fanout:c.fanout=a.longs===String?$util.Long.prototype.toString.call(s.fanout):a.longs===Number?new $util.LongBits(s.fanout.low>>>0,s.fanout.high>>>0).toNumber(!0):s.fanout),s.mode!=null&&s.hasOwnProperty("mode")&&(c.mode=s.mode),s.mtime!=null&&s.hasOwnProperty("mtime")&&(c.mtime=$root.UnixTime.toObject(s.mtime,a)),c},o.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},o.DataType=function(){const i={},s=Object.create(i);return s[i[0]="Raw"]=0,s[i[1]="Directory"]=1,s[i[2]="File"]=2,s[i[3]="Metadata"]=3,s[i[4]="Symlink"]=4,s[i[5]="HAMTShard"]=5,s}(),o})();$root.UnixTime=(()=>{function o(i){if(i)for(var s=Object.keys(i),a=0;a>>3){case 1:d.Seconds=s.int64();break;case 2:d.FractionalNanoseconds=s.fixed32();break;default:s.skipType(f&7);break}}if(!d.hasOwnProperty("Seconds"))throw $util.ProtocolError("missing required 'Seconds'",{instance:d});return d},o.fromObject=function(s){if(s instanceof $root.UnixTime)return s;var a=new $root.UnixTime;return s.Seconds!=null&&($util.Long?(a.Seconds=$util.Long.fromValue(s.Seconds)).unsigned=!1:typeof s.Seconds=="string"?a.Seconds=parseInt(s.Seconds,10):typeof s.Seconds=="number"?a.Seconds=s.Seconds:typeof s.Seconds=="object"&&(a.Seconds=new $util.LongBits(s.Seconds.low>>>0,s.Seconds.high>>>0).toNumber())),s.FractionalNanoseconds!=null&&(a.FractionalNanoseconds=s.FractionalNanoseconds>>>0),a},o.toObject=function(s,a){a||(a={});var c={};if(a.defaults){if($util.Long){var d=new $util.Long(0,0,!1);c.Seconds=a.longs===String?d.toString():a.longs===Number?d.toNumber():d}else c.Seconds=a.longs===String?"0":0;c.FractionalNanoseconds=0}return s.Seconds!=null&&s.hasOwnProperty("Seconds")&&(typeof s.Seconds=="number"?c.Seconds=a.longs===String?String(s.Seconds):s.Seconds:c.Seconds=a.longs===String?$util.Long.prototype.toString.call(s.Seconds):a.longs===Number?new $util.LongBits(s.Seconds.low>>>0,s.Seconds.high>>>0).toNumber():s.Seconds),s.FractionalNanoseconds!=null&&s.hasOwnProperty("FractionalNanoseconds")&&(c.FractionalNanoseconds=s.FractionalNanoseconds),c},o.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},o})();$root.Metadata=(()=>{function o(i){if(i)for(var s=Object.keys(i),a=0;a>>3){case 1:d.MimeType=s.string();break;default:s.skipType(f&7);break}}return d},o.fromObject=function(s){if(s instanceof $root.Metadata)return s;var a=new $root.Metadata;return s.MimeType!=null&&(a.MimeType=String(s.MimeType)),a},o.toObject=function(s,a){a||(a={});var c={};return a.defaults&&(c.MimeType=""),s.MimeType!=null&&s.hasOwnProperty("MimeType")&&(c.MimeType=s.MimeType),c},o.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},o})();const NodeType=Data.DataType,EMPTY$3=Object.freeze([]),EMPTY_BUFFER$1=new Uint8Array(0),BLANK$2=Object.freeze({}),DEFAULT_FILE_MODE=parseInt("0644",8),DEFAULT_DIRECTORY_MODE=parseInt("0755",8),code$1=code$2,name$1="UnixFS",encodePB=(o,i)=>(Object(globalThis).debug&&console.log({data:o,links:i}),encode$c(prepare({Data:Data.encode(o).finish(),Links:i}))),createRaw=o=>({type:NodeType.Raw,content:o}),createEmptyFile=o=>createSimpleFile(EMPTY_BUFFER$1,o),createSimpleFile=(o,i)=>({type:NodeType.File,layout:"simple",content:o,metadata:decodeMetadata(i)}),createFileChunk=o=>({type:NodeType.File,layout:"simple",content:o}),createAdvancedFile=(o,i)=>({type:NodeType.File,layout:"advanced",parts:o,metadata:decodeMetadata(i)}),createFileShard=o=>({type:NodeType.File,layout:"advanced",parts:o}),createComplexFile=(o,i,s)=>({type:NodeType.File,layout:"complex",content:o,parts:i,metadata:decodeMetadata(s)}),createFlatDirectory=(o,i)=>({type:NodeType.Directory,metadata:decodeMetadata(i),entries:o}),createShardedDirectory=(o,i,s,a,c=BLANK$2)=>({type:NodeType.HAMTShard,bitfield:i,fanout:readFanout(s),hashType:readInt(a),entries:o,metadata:decodeMetadata(c)}),createDirectoryShard=(o,i,s,a)=>({type:NodeType.HAMTShard,bitfield:i,fanout:readFanout(s),hashType:readInt(a),entries:o}),encodeRaw=o=>encodePB({Type:NodeType.Raw,Data:o.byteLength>0?o:void 0,filesize:o.byteLength,blocksizes:EMPTY$3},[]),encodeFile=(o,i=!1)=>{const s=i?BLANK$2:Object(o).metadata;switch(o.layout){case"simple":return encodeSimpleFile(o.content,s);case"advanced":return encodeAdvancedFile(o.parts,s);case"complex":return encodeComplexFile(o.content,o.parts,s);default:throw new TypeError(`File with unknown layout "${Object(o).layout}" was passed`)}},encodeFileChunk=o=>encodeSimpleFile(o,BLANK$2),encodeFileShard=o=>encodePB({Type:NodeType.File,blocksizes:o.map(contentByteLength),filesize:cumulativeContentByteLength(o)},o.map(encodeLink)),encodeAdvancedFile=(o,i=BLANK$2)=>encodePB({Type:NodeType.File,blocksizes:o.map(contentByteLength),filesize:cumulativeContentByteLength(o),...encodeMetadata(i)},o.map(encodeLink)),encodeLink=o=>({Name:"",Tsize:o.dagByteLength,Hash:o.cid}),encodeSimpleFile=(o,i=BLANK$2)=>encodePB({Type:NodeType.File,Data:o.byteLength>0?o:void 0,filesize:o.byteLength,blocksizes:[],...encodeMetadata(i)},[]),encodeComplexFile=(o,i,s=BLANK$2)=>encodePB({Type:NodeType.File,Data:o,filesize:o.byteLength+cumulativeContentByteLength(i),blocksizes:i.map(contentByteLength)},i.map(encodeLink)),encodeDirectory=o=>encodePB({Type:o.type,...encodeDirectoryMetadata(o.metadata||BLANK$2)},o.entries.map(encodeNamedLink)),encodeHAMTShard=({bitfield:o,fanout:i,hashType:s,entries:a,metadata:c=BLANK$2})=>encodePB({Type:NodeType.HAMTShard,Data:o.byteLength>0?o:void 0,fanout:readFanout(i),hashType:readInt(s),...encodeDirectoryMetadata(c)},a.map(encodeNamedLink)),readFanout=o=>{if(Math.log2(o)%1===0)return o;throw new TypeError(`Expected hamt size to be a power of two instead got ${o}`)},readInt=o=>{if(Number.isInteger(o))return o;throw new TypeError(`Expected an integer value instead got ${o}`)},createSymlink=(o,i=BLANK$2)=>({type:NodeType.Symlink,content:o,metadata:decodeMetadata(i)}),encodeSymlink=(o,i=!1)=>{const s=i?BLANK$2:Object(o).metadata;return encodePB({Type:NodeType.Symlink,Data:o.content,...encodeMetadata(s||BLANK$2)},[])},encode$b=(o,i=!0)=>{switch(o.type){case NodeType.Raw:return encodeRaw(o.content);case NodeType.File:return encodeFile(o);case NodeType.Directory:return encodeDirectory(o);case NodeType.HAMTShard:return encodeHAMTShard(o);case NodeType.Symlink:return encodeSymlink(o);default:throw new Error(`Unknown node type ${Object(o).type}`)}},decode$g=o=>{const i=decode$h(o),s=Data.decode(i.Data),{Type:a,Data:c,mtime:d,mode:f,blocksizes:g,...y}=Data.toObject(s,{defaults:!1,arrays:!0,longs:Number,objects:!1}),b={...f&&{mode:f},...decodeMtime(d)},$=i.Links;switch(s.Type){case NodeType.Raw:return createRaw(c);case NodeType.File:return $.length===0?new SimpleFileView(c,b):c.byteLength===0?new AdvancedFileView(decodeFileLinks(y.blocksizes,$),b):new ComplexFileView(c,decodeFileLinks(y.blocksizes,$),b);case NodeType.Directory:return createFlatDirectory(decodeDirectoryLinks($),b);case NodeType.HAMTShard:return createShardedDirectory(decodeDirectoryLinks($),c||EMPTY_BUFFER$1,y.fanout,y.hashType,b);case NodeType.Symlink:return createSymlink(c,b);default:throw new TypeError(`Unsupported node type ${s.Type}`)}},decodeMtime=o=>o==null?void 0:{mtime:{secs:o.Seconds,nsecs:o.FractionalNanoseconds||0}},decodeFileLinks=(o,i)=>{const s=[],a=o.length;let c=0;for(;co.map(i=>({cid:i.Hash,name:i.Name||"",dagByteLength:i.Tsize||0})),cumulativeContentByteLength=o=>o.reduce((i,s)=>i+s.contentByteLength,0),cumulativeDagByteLength=(o,i)=>i.reduce((s,a)=>s+a.dagByteLength,o.byteLength),contentByteLength=o=>o.contentByteLength,encodeNamedLink=({name:o,dagByteLength:i,cid:s})=>({Name:o,Tsize:i,Hash:s}),encodeDirectoryMetadata=o=>encodeMetadata(o,DEFAULT_DIRECTORY_MODE),encodeMetadata=({mode:o,mtime:i},s=DEFAULT_FILE_MODE)=>({mode:o!=null?encodeMode(o,s):void 0,mtime:i!=null?encodeMTime(i):void 0}),decodeMetadata=o=>o==null?BLANK$2:{...o.mode==null?void 0:{mode:decodeMode(o.mode)},...o.mtime==null?void 0:{mtime:o.mtime}},encodeMTime=o=>o==null?void 0:o.nsecs!==0?{Seconds:o.secs,FractionalNanoseconds:o.nsecs}:{Seconds:o.secs},encodeMode=(o,i)=>{const s=o==null?void 0:decodeMode(o);return s===i||s==null?void 0:s},decodeMode=o=>o&4095|o&4294963200,matchFile=({content:o=EMPTY_BUFFER$1,parts:i=EMPTY$3,metadata:s=BLANK$2,...a})=>i.length===0?new SimpleFileView(o,s):o.byteLength===0?new AdvancedFileView(i,s):new ComplexFileView(o,i,s);class SimpleFileView{constructor(i,s){this.content=i,this.metadata=s,this.layout="simple",this.type=NodeType.File}get filesize(){return this.content.byteLength}encode(){return encodeSimpleFile(this.content,this.metadata)}}class AdvancedFileView{constructor(i,s){this.parts=i,this.metadata=s}get layout(){return"advanced"}get type(){return NodeType.File}get fileSize(){return cumulativeContentByteLength(this.parts)}get blockSizes(){return this.parts.map(contentByteLength)}encode(){return encodeAdvancedFile(this.parts,this.metadata)}}class ComplexFileView{constructor(i,s,a){this.content=i,this.parts=s,this.metadata=a}get layout(){return"complex"}get type(){return NodeType.File}get fileSize(){return this.content.byteLength+cumulativeContentByteLength(this.parts)}get blockSizes(){return this.parts.map(contentByteLength)}encode(){return encodeComplexFile(this.content,this.parts,this.metadata)}}const filesize=o=>{switch(o.type){case NodeType.Raw:case NodeType.Symlink:return o.content.byteLength;case NodeType.File:switch(o.layout){case"simple":return o.content.byteLength;case"advanced":return cumulativeContentByteLength(o.parts);case"complex":return o.content.byteLength+cumulativeContentByteLength(o.parts)}default:return 0}},UnixFS=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_DIRECTORY_MODE,DEFAULT_FILE_MODE,NodeType,code:code$1,createAdvancedFile,createComplexFile,createDirectoryShard,createEmptyFile,createFileChunk,createFileShard,createFlatDirectory,createRaw,createShardedDirectory,createSimpleFile,createSymlink,cumulativeContentByteLength,cumulativeDagByteLength,decode:decode$g,decodeMetadata,encode:encode$b,encodeAdvancedFile,encodeComplexFile,encodeDirectory,encodeDirectoryMetadata,encodeFile,encodeFileChunk,encodeFileShard,encodeHAMTShard,encodeLink,encodeMetadata,encodeMode,encodeRaw,encodeSimpleFile,encodeSymlink,filesize,matchFile,name:name$1},Symbol.toStringTag,{value:"Module"})),effect=function*(o){const i=yield*o;yield*send(i)};function*current(){return yield CURRENT}const suspend=function*(){yield SUSPEND},wait=function*(o){const i=yield*current();if(isAsync(o)){let s=!1,a;if(o.then(c=>{s=!1,a=c,enqueue(i)},c=>{s=!0,a=c,enqueue(i)}),yield*suspend(),s)throw a;return a}else return main(wake(i)),yield*suspend(),o};function*wake(o){enqueue(o)}const isAsync=o=>o!=null&&typeof o.then=="function",send=function*(o){yield o},listen=function*(o){const i=[];for(const s of Object.entries(o)){const[a,c]=s;c!==NONE&&i.push(yield*fork$3(tag(c,a)))}yield*group(i)},effects=o=>o.length>0?batch(o.map(effect)):NONE;function*batch(o){const i=[];for(const s of o)i.push(yield*fork$3(s));yield*group(i)}const tag=(o,i)=>o===NONE?NONE:o instanceof Tagger?new Tagger([...o.tags,i],o.source):new Tagger([i],o);class Tagger{constructor(i,s){this.tags=i,this.source=s,this.controller}[Symbol.iterator](){return this.controller||(this.controller=this.source[Symbol.iterator]()),this}box(i){if(i.done)return i;switch(i.value){case SUSPEND:case CURRENT:return i;default:{const s=i;let{value:a}=s;for(const c of this.tags)a=withTag(c,a);return s.value=a,s}}}next(i){return this.box(this.controller.next(i))}throw(i){return this.box(this.controller.throw(i))}return(i){return this.box(this.controller.return(i))}get[Symbol.toStringTag](){return"TaggedEffect"}}const none=()=>NONE,withTag=(o,i)=>({type:o,[o]:i}),CURRENT=Symbol("current"),SUSPEND=Symbol("suspend");class Group{static of(i){return i.group||MAIN}static enqueue(i,s){i.group=s,s.stack.active.push(i)}constructor(i,s=[],a=new Set,c=new Stack(s,a)){this.driver=i,this.parent=Group.of(i),this.stack=c,this.id=++ID}}class Main{constructor(){this.status=IDLE,this.stack=new Stack,this.id=0}}class Stack{constructor(i=[],s=new Set){this.active=i,this.idle=s}static size({active:i,idle:s}){return i.length+s.size}}const main=o=>enqueue(o[Symbol.iterator]()),enqueue=o=>{let i=Group.of(o);for(i.stack.active.push(o),i.stack.idle.delete(o);i.parent;){const{idle:s,active:a}=i.parent.stack;if(s.has(i.driver))s.delete(i.driver),a.push(i.driver);else break;i=i.parent}if(MAIN.status===IDLE)for(MAIN.status=ACTIVE;;)try{for(const s of step(MAIN));MAIN.status=IDLE;break}catch{MAIN.stack.active.shift()}},resume=o=>enqueue(o),step=function*(o){const{active:i}=o.stack;let s=i[0];for(o.stack.idle.delete(s);s;){let a=INIT;e:for(;!a.done&&s===i[0];){const c=a.value;switch(c){case SUSPEND:o.stack.idle.add(s);break e;case CURRENT:a=s.next(s);break;default:a=s.next(yield c);break}}i.shift(),s=i[0],o.stack.idle.delete(s)}},fork$3=(o,i)=>new Fork(o,i),exit=(o,i)=>conclude(o,{ok:!0,value:i}),abort=(o,i)=>conclude(o,{ok:!1,error:i});function*conclude(o,i){try{const s=o,a=i.ok?s.return(i.value):s.throw(i.error);if(!a.done)if(a.value===SUSPEND){const{idle:c}=Group.of(s).stack;c.add(s)}else enqueue(s)}catch{}}function*group(o){if(o.length===0)return;const i=yield*current(),s=new Group(i);let a=null;for(const c of o){const{result:d}=c;if(d){!d.ok&&!a&&(a=d);continue}move(c,s)}try{if(a)throw a.error;for(;yield*step(s),Stack.size(s.stack)>0;)yield*suspend()}catch(c){for(const d of s.stack.active)yield*abort(d,c);for(const d of s.stack.idle)yield*abort(d,c),enqueue(d);throw c}}const move=(o,i)=>{const s=Group.of(o);if(s!==i){const{active:a,idle:c}=s.stack,d=i.stack;if(o.group=i,c.has(o))c.delete(o),d.idle.add(o);else{const f=a.indexOf(o);f>=0&&(a.splice(f,1),d.active.push(o))}}};function*join(o){o.status===IDLE&&(yield*o),o.result||(yield*group([o]));const i=o.result;if(i.ok)return i.value;throw i.error}class Future{constructor(i){this.handler=i,this.result}get promise(){const{result:i}=this,s=i==null?new Promise((a,c)=>{this.handler.onsuccess=a,this.handler.onfailure=c}):i.ok?Promise.resolve(i.value):Promise.reject(i.error);return Object.defineProperty(this,"promise",{value:s}),s}then(i,s){return this.activate().promise.then(i,s)}catch(i){return this.activate().promise.catch(i)}finally(i){return this.activate().promise.finally(i)}activate(){return this}}class Fork extends Future{constructor(i,s=BLANK$1,a={},c=INIT){super(a),this.id=++ID,this.name=s.name||"",this.task=i,this.state=c,this.status=IDLE,this.result,this.handler=a,this.controller}*resume(){resume(this)}join(){return join(this)}abort(i){return abort(this,i)}exit(i){return exit(this,i)}get[Symbol.toStringTag](){return"Fork"}*[Symbol.iterator](){return this.activate()}activate(){return this.controller=this.task[Symbol.iterator](),this.status=ACTIVE,enqueue(this),this}panic(i){this.result={ok:!1,error:i},this.status=FINISHED;const{handler:s}=this;throw s.onfailure&&s.onfailure(i),i}step(i){if(this.state=i,i.done){this.result={ok:!0,value:i.value},this.status=FINISHED;const{handler:s}=this;s.onsuccess&&s.onsuccess(i.value)}return i}next(i){try{return this.step(this.controller.next(i))}catch(s){return this.panic(s)}}return(i){try{return this.step(this.controller.return(i))}catch(s){return this.panic(s)}}throw(i){try{return this.step(this.controller.throw(i))}catch(s){return this.panic(s)}}}const loop=function*(o,i){const s=yield*current(),a=new Group(s);for(Group.enqueue(o[Symbol.iterator](),a);;){for(const c of step(a))Group.enqueue(i(c)[Symbol.iterator](),a);if(Stack.size(a.stack)>0)yield*suspend();else break}};let ID=0;const IDLE="idle",ACTIVE="active",FINISHED="finished",INIT={done:!1,value:CURRENT},BLANK$1={},NONE=function*o(){}(),MAIN=new Main;function Indexed(){}Object.defineProperties(Indexed,{prototype:{value:new Proxy(Object.prototype,{get(o,i,s){return typeof i=="symbol"?Reflect.get(o,i,s):s.get(i)}})}});const empty$3=()=>new BufferView,slice=(o,i=0,s=o.byteLength)=>{const a=[],c=i<0?o.byteLength-i:i,d=s<0?o.byteLength-s:s;if(c===0&&d>=o.byteLength)return o;if(c>d||c>o.byteLength||d<=0)return empty$3();let f=0,g=0;for(const y of o.segments){const b=g+y.byteLength;if(f===0){if(d<=b){const $=y.subarray(c-g,d-g);a.push($),f=$.byteLength;break}else if(ci.byteLength>0?(o.segments.push(i),new BufferView(o.segments,o.byteOffset,o.byteLength+i.byteLength)):o,get$6=(o,i)=>{if(i{let a=s;for(const c of o.segments)i.set(c,a),a+=c.byteLength;return i};function*iterate$1(o){for(const i of o.segments)yield*i}class BufferView extends Indexed{constructor(i=[],s=0,a=0){super(),this.segments=i,this.byteLength=a,this.length=a,this.byteOffset=s}[Symbol.iterator](){return iterate$1(this)}slice(i,s){return slice(this,i,s)}subarray(i,s){return slice(this,i,s)}push(i){return push(this,i)}get(i){return get$6(this,i)}copyTo(i,s){return copyTo(this,i,s)}}const panic=o=>{throw new Error(o)},unreachable=(o,i,...s)=>panic(String.raw(o,JSON.stringify(i),...s)),EMPTY_BUFFER=new Uint8Array(0),EMPTY$2=[],open$1=o=>({config:o,buffer:empty$3()}),write$3=(o,i)=>i.byteLength>0?split(o.config,o.buffer.push(i),!1):{...o,chunks:EMPTY$2},close$6=o=>split(o.config,o.buffer,!0),split=(o,i,s)=>{const a=o.chunker,c=[];let d=0;for(const f of a.cut(a.context,i,s))if(f>0){const g=i.subarray(d,d+f);c.push(g),d+=f}return{config:o,chunks:c,buffer:i.subarray(d)}},mutable=()=>({mutable:!0,needs:{},nodes:{},links:{},linked:EMPTY$1}),addNodes=(o,i)=>{let s=patch(i,{});for(const a of o){const{ready:c,has:d,wants:f}=collect(a.children,s.links);f.length===0?s=patch(s,{links:assign(void 0,d),linked:[{id:a.id,links:c}]}):s=patch(s,{needs:assign(a.id,f),nodes:{[a.id]:{children:a.children,count:f.length}}})}return s},addLink=(o,i,s)=>{const a=s.needs[o],c=s.nodes[a];if(c!=null)if(c.count===1){const{ready:d,has:f}=collect(c.children,{...s.links,[o]:i});return patch(s,{needs:{[o]:void 0},links:assign(void 0,f),nodes:{[a]:void 0},linked:[{id:a,links:d}]})}else return patch(s,{needs:{[o]:void 0},links:{[o]:i},nodes:{[a]:{...c,count:c.count-1}}});else return patch(s,{links:{[o]:i}})},patch=(o,{needs:i,nodes:s,links:a,linked:c})=>{const d=o.mutable?o:{...o},f=o.mutable?BLANK:void 0;return i&&(d.needs=patchDict(o.needs,i,f)),s&&(d.nodes=patchDict(o.nodes,s,f)),a&&(d.links=patchDict(o.links,a,f)),d.linked=c?append(o.linked||EMPTY$1,c,EMPTY$1):o.linked||[],d},assign=(o,i)=>{const s={};for(const a of i)s[a]=o;return s},patchDict=(o,i,s=o)=>{const a=o===s?{...o}:o;for(const c of Object.entries(i)){const[d,f]=c;f==null?delete a[d]:a[d]=f}return a},append=(o,i,s=o)=>{if(o===s)return[...o,...i];for(const a of i)o.push(a);return o},collect=(o,i)=>{const s=[],a=[],c=[];for(const d of o){const f=i[d];f?(s.push(d),c.push(f)):a.push(d)}return{has:s,wants:a,ready:c}},EMPTY$1=Object.freeze([]),BLANK=Object.freeze({}),update=(o,i)=>{switch(o.type){case"write":return write$2(i,o.bytes);case"link":return link(i,o.link);case"block":return{state:i,effect:none()};case"close":return close$5(i);case"end":return{state:i,effect:none()};default:return unreachable`File Writer got unknown message ${o}`}},init=(o,i,s)=>({status:"open",metadata:i,config:s,writer:o,chunker:open$1({chunker:s.chunker}),layout:s.fileLayout.open(),nodeQueue:mutable()}),write$2=(o,i)=>{if(o.status==="open"){const{chunks:s,...a}=write$3(o.chunker,i),{nodes:c,leaves:d,layout:f}=o.config.fileLayout.write(o.layout,s),{linked:g,...y}=addNodes(c,o.nodeQueue),b=[...encodeLeaves(d,o.config),...encodeBranches(g,o.config)];return{state:{...o,chunker:a,layout:f,nodeQueue:y},effect:listen({link:effects(b)})}}else return panic("Unable to perform write on closed file")},link=(o,{id:i,link:s,block:a})=>{let{linked:c,...d}=addLink(i,s,o.nodeQueue);const f=encodeBranches(c,o.config),g=o.status==="closed"&&i===o.rootID?{...o,status:"linked",link:s,nodeQueue:d}:{...o,nodeQueue:d},y=o.status==="closed"&&i===o.rootID&&o.end?o.end.resume():none();return{state:g,effect:listen({link:effects(f),block:writeBlock(o.writer,a),end:y})}},close$5=o=>{if(o.status==="open"){const{chunks:i}=close$6(o.chunker),{layout:s,...a}=o.config.fileLayout.write(o.layout,i),{root:c,...d}=o.config.fileLayout.close(s,o.metadata),[f,g]=isLeafNode(c)?[[...a.nodes,...d.nodes],[...a.leaves,...d.leaves,c]]:[[...a.nodes,...d.nodes,c],[...a.leaves,...d.leaves]],{linked:y,...b}=addNodes(f,o.nodeQueue),$=[...encodeLeaves(g,o.config),...encodeBranches(y,o.config)],x=fork$3(suspend());return{state:{...o,chunker:null,layout:null,rootID:c.id,status:"closed",end:x,nodeQueue:b},effect:listen({link:effects($),end:join(x)})}}else return{state:o,effect:none()}},encodeLeaves=(o,i)=>o.map(s=>encodeLeaf(i,s,i.fileChunkEncoder)),encodeLeaf=function*({hasher:o,linker:i},{id:s,content:a},c){const d=c.encode(a?asUint8Array$1(a):EMPTY_BUFFER),f=yield*wait(o.digest(d)),g=i.createLink(c.code,f),y={cid:g,bytes:d},b={cid:g,contentByteLength:a?a.byteLength:0,dagByteLength:d.byteLength};return{id:s,block:y,link:b}},encodeBranches=(o,i)=>o.map(s=>encodeBranch(i,s)),encodeBranch=function*(o,{id:i,links:s},a){const c=o.fileEncoder.encode({type:NodeType.File,layout:"advanced",parts:s,metadata:a}),d=yield*wait(Promise.resolve(o.hasher.digest(c))),f=o.linker.createLink(o.fileEncoder.code,d),g={bytes:c,cid:f},y={cid:f,contentByteLength:cumulativeContentByteLength(s),dagByteLength:cumulativeDagByteLength(c,s)};return{id:i,block:g,link:y}},writeBlock=function*(o,i){(o.desiredSize||0)<=0&&(yield*wait(o.ready)),o.write(i)},asUint8Array$1=o=>o instanceof Uint8Array?o:o.copyTo(new Uint8Array(o.byteLength),0),isLeafNode=o=>o.children==null,name="fixed",context={maxChunkSize:262144},type="Stateless",withMaxChunkSize=o=>({type:"Stateless",context:{maxChunkSize:o},name,cut}),cut=({maxChunkSize:o},{byteLength:i},s)=>{const a=i/o|0,c=new Array(a).fill(o),d=s?i-a*o:0;return d>0&&c.push(d),c},FixedSize=Object.freeze(Object.defineProperty({__proto__:null,context,cut,name,type,withMaxChunkSize},Symbol.toStringTag,{value:"Module"})),equals$6=(o,i)=>{if(o===i)return!0;if(o.byteLength!==i.byteLength)return!1;for(let s=0;s{if(o instanceof Uint8Array&&o.constructor.name==="Uint8Array")return o;if(o instanceof ArrayBuffer)return new Uint8Array(o);if(ArrayBuffer.isView(o))return new Uint8Array(o.buffer,o.byteOffset,o.byteLength);throw new Error("Unknown type, must be binary type")};var encode_1$3=encode$a,MSB$4=128,REST$4=127,MSBALL$4=~REST$4,INT$4=Math.pow(2,31);function encode$a(o,i,s){i=i||[],s=s||0;for(var a=s;o>=INT$4;)i[s++]=o&255|MSB$4,o/=128;for(;o&MSBALL$4;)i[s++]=o&255|MSB$4,o>>>=7;return i[s]=o|0,encode$a.bytes=s-a+1,i}var decode$f=read$4,MSB$1$4=128,REST$1$4=127;function read$4(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$4.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$4)<=MSB$1$4);return read$4.bytes=d-a,s}var N1$3=Math.pow(2,7),N2$3=Math.pow(2,14),N3$3=Math.pow(2,21),N4$3=Math.pow(2,28),N5$3=Math.pow(2,35),N6$3=Math.pow(2,42),N7$3=Math.pow(2,49),N8$3=Math.pow(2,56),N9$3=Math.pow(2,63),length$3=function(o){return o[_brrp_varint$3.decode(o,i),_brrp_varint$3.decode.bytes],encodeTo$3=(o,i,s=0)=>(_brrp_varint$3.encode(o,i,s),i),encodingLength$3=o=>_brrp_varint$3.encodingLength(o),create$c=(o,i)=>{const s=i.byteLength,a=encodingLength$3(o),c=a+encodingLength$3(s),d=new Uint8Array(c+s);return encodeTo$3(o,d,0),encodeTo$3(s,d,a),d.set(i,c),new Digest$3(o,s,i,d)},decode$d=o=>{const i=coerce$3(o),[s,a]=decode$e(i),[c,d]=decode$e(i.subarray(a)),f=i.subarray(a+d);if(f.byteLength!==c)throw new Error("Incorrect length");return new Digest$3(s,c,f,i)},equals$5=(o,i)=>{if(o===i)return!0;{const s=i;return o.code===s.code&&o.size===s.size&&s.bytes instanceof Uint8Array&&equals$6(o.bytes,s.bytes)}};let Digest$3=class{constructor(i,s,a,c){this.code=i,this.size=s,this.digest=a,this.bytes=c}};const from$a=({name:o,code:i,encode:s})=>new Hasher$2(o,i,s);let Hasher$2=class{constructor(i,s,a){this.name=i,this.code=s,this.encode=a}digest(i){if(i instanceof Uint8Array){const s=this.encode(i);return s instanceof Uint8Array?create$c(this.code,s):s.then(a=>create$c(this.code,a))}else throw Error("Unknown type, must be binary type")}};const sha$1=o=>async i=>new Uint8Array(await crypto.subtle.digest(o,i)),sha256$1=from$a({name:"sha2-256",code:18,encode:sha$1("SHA-256")});function base$3(o,i){if(o.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src$3=base$3,_brrp__multiformats_scope_baseX$3=src$3;let Encoder$3=class{constructor(i,s,a){this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}},Decoder$3=class{constructor(i,s,a){if(this.name=i,this.prefix=s,s.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s.codePointAt(0),this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or$5(this,i)}},ComposedDecoder$3=class{constructor(i){this.decoders=i}or(i){return or$5(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const or$5=(o,i)=>new ComposedDecoder$3({...o.decoders||{[o.prefix]:o},...i.decoders||{[i.prefix]:i}});let Codec$3=class{constructor(i,s,a,c){this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder$3(i,s,a),this.decoder=new Decoder$3(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}};const from$9=({name:o,prefix:i,encode:s,decode:a})=>new Codec$3(o,i,s,a),baseX$3=({prefix:o,name:i,alphabet:s})=>{const{encode:a,decode:c}=_brrp__multiformats_scope_baseX$3(s,i);return from$9({prefix:o,name:i,encode:a,decode:d=>coerce$3(c(d))})},decode$c=(o,i,s,a)=>{const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f},encode$9=(o,i,s)=>{const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f&&(d+=i[c&g<from$9({prefix:i,name:o,encode(c){return encode$9(c,a,s)},decode(c){return decode$c(c,a,s,o)}}),base58btc$2=baseX$3({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});baseX$3({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});const base32$2=rfc4648$3({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5});rfc4648$3({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5});rfc4648$3({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5});rfc4648$3({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5});rfc4648$3({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5});rfc4648$3({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5});rfc4648$3({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5});rfc4648$3({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5});rfc4648$3({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});const format$2=(o,i)=>{const{bytes:s,version:a}=o;switch(a){case 0:return toStringV0$2(s,baseCache$2(o),i||base58btc$2.encoder);default:return toStringV1$2(s,baseCache$2(o),i||base32$2.encoder)}},cache$3=new WeakMap,baseCache$2=o=>{const i=cache$3.get(o);if(i==null){const s=new Map;return cache$3.set(o,s),s}return i};let CID$2=class be{constructor(i,s,a,c){this.code=s,this.version=i,this.multihash=a,this.bytes=c,this["/"]=c}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:{const{code:i,multihash:s}=this;if(i!==DAG_PB_CODE$3)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(s.code!==SHA_256_CODE$2)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return be.createV0(s)}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:{const{code:i,digest:s}=this.multihash,a=create$c(i,s);return be.createV1(this.code,a)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(i){return be.equals(this,i)}static equals(i,s){const a=s;return a&&i.code===a.code&&i.version===a.version&&equals$5(i.multihash,a.multihash)}toString(i){return format$2(this,i)}toJSON(){return{"/":format$2(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(i){if(i==null)return null;const s=i;if(s instanceof be)return s;if(s["/"]!=null&&s["/"]===s.bytes||s.asCID===s){const{version:a,code:c,multihash:d,bytes:f}=s;return new be(a,c,d,f||encodeCID$2(a,c,d.bytes))}else if(s[cidSymbol$2]===!0){const{version:a,multihash:c,code:d}=s,f=decode$d(c);return be.create(a,d,f)}else return null}static create(i,s,a){if(typeof s!="number")throw new Error("String codecs are no longer supported");if(!(a.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(i){case 0:{if(s!==DAG_PB_CODE$3)throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE$3}) block encoding`);return new be(i,s,a,a.bytes)}case 1:{const c=encodeCID$2(i,s,a.bytes);return new be(i,s,a,c)}default:throw new Error("Invalid version")}}static createV0(i){return be.create(0,DAG_PB_CODE$3,i)}static createV1(i,s){return be.create(1,i,s)}static decode(i){const[s,a]=be.decodeFirst(i);if(a.length)throw new Error("Incorrect length");return s}static decodeFirst(i){const s=be.inspectBytes(i),a=s.size-s.multihashSize,c=coerce$3(i.subarray(a,a+s.multihashSize));if(c.byteLength!==s.multihashSize)throw new Error("Incorrect length");const d=c.subarray(s.multihashSize-s.digestSize),f=new Digest$3(s.multihashCode,s.digestSize,d,c);return[s.version===0?be.createV0(f):be.createV1(s.codec,f),i.subarray(s.size)]}static inspectBytes(i){let s=0;const a=()=>{const[x,T]=decode$e(i.subarray(s));return s+=T,x};let c=a(),d=DAG_PB_CODE$3;if(c===18?(c=0,s=0):d=a(),c!==0&&c!==1)throw new RangeError(`Invalid CID version ${c}`);const f=s,g=a(),y=a(),b=s+y,$=b-f;return{version:c,codec:d,multihashCode:g,digestSize:y,multihashSize:$,size:b}}static parse(i,s){const[a,c]=parseCIDtoBytes$2(i,s),d=be.decode(c);if(d.version===0&&i[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache$2(d).set(a,i),d}};const parseCIDtoBytes$2=(o,i)=>{switch(o[0]){case"Q":{const s=i||base58btc$2;return[base58btc$2.prefix,s.decode(`${base58btc$2.prefix}${o}`)]}case base58btc$2.prefix:{const s=i||base58btc$2;return[base58btc$2.prefix,s.decode(o)]}case base32$2.prefix:{const s=i||base32$2;return[base32$2.prefix,s.decode(o)]}default:{if(i==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[o[0],i.decode(o)]}}},toStringV0$2=(o,i,s)=>{const{prefix:a}=s;if(a!==base58btc$2.prefix)throw Error(`Cannot string encode V0 in ${s.name} encoding`);const c=i.get(a);if(c==null){const d=s.encode(o).slice(1);return i.set(a,d),d}else return c},toStringV1$2=(o,i,s)=>{const{prefix:a}=s,c=i.get(a);if(c==null){const d=s.encode(o);return i.set(a,d),d}else return c},DAG_PB_CODE$3=112,SHA_256_CODE$2=18,encodeCID$2=(o,i,s)=>{const a=encodingLength$3(o),c=a+encodingLength$3(i),d=new Uint8Array(c+s.byteLength);return encodeTo$3(o,d,0),encodeTo$3(i,d,a),d.set(s,c),d},cidSymbol$2=Symbol.for("@ipld/js-cid/CID");class Node{constructor(i,s,a){this.id=i,this.children=s,this.metadata=a}}const withWidth=o=>({open:()=>open({width:o}),write:write$1,close:close$4}),defaults$3={width:174},open=({width:o}=defaults$3)=>({width:o,head:null,leafIndex:[],nodeIndex:[],lastID:0}),write$1=(o,i)=>{if(i.length===0)return{layout:o,nodes:EMPTY,leaves:EMPTY};{let{lastID:s}=o;const[a,c]=o.head?[null,(i.unshift(o.head),i)]:i.length===1&&o.leafIndex.length===0?[i[0],EMPTY]:[null,i];if(c.length===0)return{layout:{...o,head:a},nodes:EMPTY,leaves:EMPTY};{const d=[...o.leafIndex],f=[];for(const g of c){const y={id:++s,content:g};f.push(y),d.push(y.id)}return d.length>o.width?flush({...o,leafIndex:d,head:a,lastID:s},f):{layout:{...o,head:a,leafIndex:d,lastID:s},leaves:f,nodes:EMPTY}}}},flush=(o,i=EMPTY,s=[],a=!1)=>{let{lastID:c}=o;const d=o.nodeIndex.map(b=>[...b]),f=[...o.leafIndex],{width:g}=o;for(;f.length>g||f.length>0&&a;){grow(d,1);const b=new Node(++c,f.splice(0,g));d[0].push(b.id),s.push(b)}let y=0;for(;yg||b.length>0&&a&&y{const s=o;if(o.head)return{root:{id:1,content:o.head,metadata:i},leaves:EMPTY,nodes:EMPTY};if(o.leafIndex.length===0)return{root:{id:1,metadata:i},leaves:EMPTY,nodes:EMPTY};{const{nodes:a,layout:c}=flush(s,EMPTY,[],!0),{nodeIndex:d}=c,f=d.length-1,g=d[f];if(g.length===1){const y=a[a.length-1];return a.length=a.length-1,{root:y,nodes:a,leaves:EMPTY}}else return{root:new Node(c.lastID+1,g,i),nodes:a,leaves:EMPTY}}},grow=(o,i)=>{for(;o.length({chunker:FixedSize,fileChunkEncoder:UnixFSLeaf,smallFileEncoder:UnixFSLeaf,fileEncoder:UnixFS,fileLayout:withWidth(174),hasher:sha256$1,linker:{createLink:CID$2.createV1}}),configure$4=o=>({...defaults$2(),...o}),UnixFSLeaf={code:code$1,name:name$1,encode:encodeFileChunk},create$b=({writer:o,metadata:i={},settings:s=defaults$2()})=>new FileWriterView(init(o,i,configure$4(s))),write=async(o,i)=>(await perform(o,send({type:"write",bytes:i})),o),close$3=async(o,{releaseLock:i=!1,closeWriter:s=!1}={})=>{await perform(o,send({type:"close"}));const{state:a}=o;if(a.status==="linked")return s?await o.state.writer.close():i&&o.state.writer.releaseLock(),a.link;panic(`Expected writer to be in 'linked' state after close, but it is in "${a.status}" instead`)},perform=(o,i)=>fork$3(loop(i,s=>{const{state:a,effect:c}=update(s,o.state);return o.state=a,c}));class FileWriterView{constructor(i){this.state=i}get writer(){return this.state.writer}get settings(){return this.state.config}write(i){return write(this,i)}close(i){return close$3(this,i)}}const defaults$1=defaults$2,create$a=({writer:o,settings:i=defaults$1(),metadata:s={}})=>new DirectoryWriter({writer:o,metadata:s,settings:i,entries:new Map,closed:!1}),set$4=(o,i,s,{overwrite:a=!1}={})=>{const c=asWritable$1(o.state);if(i.includes("/"))throw new Error(`Directory entry name "${i}" contains forbidden "/" character`);if(!a&&c.entries.has(i))throw new Error(`Directory already contains entry with name "${i}"`);return c.entries.set(i,s),o},remove$1=(o,i)=>(asWritable$1(o.state).entries.delete(i),o),asWritable$1=o=>{if(o.closed)throw new Error("Can not change written directory, but you can .fork() and make changes to it");return o},close$2=async(o,{closeWriter:i=!1,releaseLock:s=!1}={})=>{const{writer:a,settings:c,metadata:d}=asWritable$1(o.state);o.state.closed=!0;const f=[...links$1(o)],g=createFlatDirectory(f,d),y=encodeDirectory(g),b=await c.hasher.digest(y),$=c.linker.createLink(code$1,b);return(a.desiredSize||0)<=0&&await a.ready,a.write({cid:$,bytes:y}),i?await a.close():s&&a.releaseLock(),{cid:$,dagByteLength:cumulativeDagByteLength(y,f)}},links$1=function*({state:o}){for(const[i,{dagByteLength:s,cid:a}]of o.entries)yield{name:i,dagByteLength:s,cid:a}},fork$2=({state:o},{writer:i=o.writer,metadata:s=o.metadata,settings:a=o.settings}={})=>new DirectoryWriter({writer:i,metadata:s,settings:a,entries:new Map(o.entries.entries()),closed:!1});class DirectoryWriter{constructor(i){this.state=i}get writer(){return this.state.writer}get settings(){return this.state.settings}links(){return links$1(this)}set(i,s,a){return set$4(this,i,s,a)}remove(i){return remove$1(this,i)}fork(i){return fork$2(this,i)}close(i){return close$2(this,i)}entries(){return this.state.entries.entries()}has(i){return this.state.entries.has(i)}get size(){return this.state.entries.size}}const api=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),empty$2=(o=32)=>{if(o!==32)throw new Error(`Uint32 BitField does not support size: ${o}`);return 0},from$8=(o,i)=>{let s=empty$2(i);for(const a of o)s=set$3(s,a);return s},size$1=o=>32,mask=(o,i)=>o>>>i&31,offset=(o,i)=>1<bitCount(o&offset(i,0)-1),set$3=(o,i)=>o|1<o&(255^1<(o>>i&1)!==0,bitCount=o=>{const i=o-(o>>1&1431655765),s=(i&858993459)+(i>>2&858993459);return(s+(s>>4)&252645135)*16843009>>24},and$1=(o,i)=>o&i,or$4=(o,i)=>o|i,toBytes$1=o=>Uint8Array.of(o>>24&255,o>>16&255,o>>8&255,o&255),fromBytes$2=o=>{if(o.length!==4)throw new Error(`Expected 4 bytes instead got ${o.length}`);return(o[0]<<24)+(o[1]<<16)+(o[2]<<8)+o[3]},Uint32BitField=Object.freeze(Object.defineProperty({__proto__:null,API:api,and:and$1,bitCount,empty:empty$2,from:from$8,fromBytes:fromBytes$2,get:get$5,or:or$4,popcount:popcount$1,set:set$3,size:size$1,toBytes:toBytes$1,unset:unset$1},Symbol.toStringTag,{value:"Module"}));var murmurHash3js={exports:{}};(function(o,i){(function(s,a){var c={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function d(S){if(!Array.isArray(S)&&!ArrayBuffer.isView(S))return!1;for(var _=0;_255)return!1;return!0}function f(S,_){return(S&65535)*_+(((S>>>16)*_&65535)<<16)}function g(S,_){return S<<_|S>>>32-_}function y(S){return S^=S>>>16,S=f(S,2246822507),S^=S>>>13,S=f(S,3266489909),S^=S>>>16,S}function b(S,_){S=[S[0]>>>16,S[0]&65535,S[1]>>>16,S[1]&65535],_=[_[0]>>>16,_[0]&65535,_[1]>>>16,_[1]&65535];var C=[0,0,0,0];return C[3]+=S[3]+_[3],C[2]+=C[3]>>>16,C[3]&=65535,C[2]+=S[2]+_[2],C[1]+=C[2]>>>16,C[2]&=65535,C[1]+=S[1]+_[1],C[0]+=C[1]>>>16,C[1]&=65535,C[0]+=S[0]+_[0],C[0]&=65535,[C[0]<<16|C[1],C[2]<<16|C[3]]}function $(S,_){S=[S[0]>>>16,S[0]&65535,S[1]>>>16,S[1]&65535],_=[_[0]>>>16,_[0]&65535,_[1]>>>16,_[1]&65535];var C=[0,0,0,0];return C[3]+=S[3]*_[3],C[2]+=C[3]>>>16,C[3]&=65535,C[2]+=S[2]*_[3],C[1]+=C[2]>>>16,C[2]&=65535,C[2]+=S[3]*_[2],C[1]+=C[2]>>>16,C[2]&=65535,C[1]+=S[1]*_[3],C[0]+=C[1]>>>16,C[1]&=65535,C[1]+=S[2]*_[2],C[0]+=C[1]>>>16,C[1]&=65535,C[1]+=S[3]*_[1],C[0]+=C[1]>>>16,C[1]&=65535,C[0]+=S[0]*_[3]+S[1]*_[2]+S[2]*_[1]+S[3]*_[0],C[0]&=65535,[C[0]<<16|C[1],C[2]<<16|C[3]]}function x(S,_){return _%=64,_===32?[S[1],S[0]]:_<32?[S[0]<<_|S[1]>>>32-_,S[1]<<_|S[0]>>>32-_]:(_-=32,[S[1]<<_|S[0]>>>32-_,S[0]<<_|S[1]>>>32-_])}function T(S,_){return _%=64,_===0?S:_<32?[S[0]<<_|S[1]>>>32-_,S[1]<<_]:[S[1]<<_-32,0]}function A(S,_){return[S[0]^_[0],S[1]^_[1]]}function E(S){return S=A(S,[0,S[0]>>>1]),S=$(S,[4283543511,3981806797]),S=A(S,[0,S[0]>>>1]),S=$(S,[3301882366,444984403]),S=A(S,[0,S[0]>>>1]),S}c.x86.hash32=function(S,_){if(c.inputValidation&&!d(S))return a;_=_||0;for(var C=S.length%4,B=S.length-C,D=_,I=0,O=3432918353,N=461845907,L=0;L>>0},c.x86.hash128=function(S,_){if(c.inputValidation&&!d(S))return a;_=_||0;for(var C=S.length%16,B=S.length-C,D=_,I=_,O=_,N=_,L=0,R=0,z=0,K=0,G=597399067,W=2869860233,J=951274213,ie=2716044179,H=0;H>>0).toString(16)).slice(-8)+("00000000"+(I>>>0).toString(16)).slice(-8)+("00000000"+(O>>>0).toString(16)).slice(-8)+("00000000"+(N>>>0).toString(16)).slice(-8)},c.x64.hash128=function(S,_){if(c.inputValidation&&!d(S))return a;_=_||0;for(var C=S.length%16,B=S.length-C,D=[0,_],I=[0,_],O=[0,0],N=[0,0],L=[2277735313,289559509],R=[1291169091,658871167],z=0;z>>0).toString(16)).slice(-8)+("00000000"+(D[1]>>>0).toString(16)).slice(-8)+("00000000"+(I[0]>>>0).toString(16)).slice(-8)+("00000000"+(I[1]>>>0).toString(16)).slice(-8)},o.exports&&(i=o.exports=c),i.murmurHash3=c})()})(murmurHash3js,murmurHash3js.exports);var murmurHash3jsExports=murmurHash3js.exports,murmurhash3jsRevisited=murmurHash3jsExports;const mur=getDefaultExportFromCjs(murmurhash3jsRevisited),utf8$2=new TextEncoder,hash32=mur.x64.hash126,configure$3=({bitWidth:o=5,hash:i=hash32})=>{if(o>4*8)throw new RangeError(`Can not use bitWidth ${o} which exceeds the hashSize 4`);const a=4294967295>>>32-o;return{at:(f,g)=>f>>>g*o&a,from:f=>i(utf8$2.encode(f)),size:Math.ceil(4*8/o)}};class BitmapIndexedNode{constructor(i,s,a,c,d){this.edit=i,this.config=d,this.datamap=s,this.nodemap=a,this.children=c}get nodeArity(){return this.config.BitField.popcount(this.nodemap)}get dataArity(){return this.config.BitField.popcount(this.datamap)}empty(){return create$9(this.config)}lookup(i,s,a,c){return lookup(this,i,s,a,c)}associate(i,s,a,c,d,f){return associate(this,i,s,a,c,d,f)}dissociate(i,s,a,c,d){return dissociate(this,i,s,a,c,d)}fork(i=null){return fork$1(this,i)}entries(){return entries(this)}keys(){return keys(this)}values(){return values(this)}}class HashCollisionNode{constructor(i,s,a,c){this.edit=i,this.count=s,this.children=a,this.config=c}get nodeArity(){return 0}get dataArity(){return this.count}lookup(i,s,a,c){return lookupCollision(this,a,c)}associate(i,s,a,c,d,f){return associateCollision(this,i,a,c,d,f)}dissociate(i,s,a,c,d){return dissociateCollision(this,i,a,c,d)}fork(i=null){return forkCollision(this,i)}entries(){return entries(this)}keys(){return keys(this)}values(){return values(this)}}const lookupCollision=(o,i,s)=>{const{children:a,count:c}=o,d=findHashCollisionNodeIndex(a,c,i);return a[d]===i?a[d+1]:s},associateCollision=(o,i,s,a,c,d)=>{const{children:f,count:g}=o,y=findHashCollisionNodeIndex(f,g,a);if(f[y]!==a){const b=o.fork(i);return d.value=!0,b.count+=1,b.children.splice(y,s,c),b}else if(f[y+1]!==c){const b=o.fork(i);return b.children[y+1]=c,b}else return o},dissociateCollision=(o,i,s,a,c)=>{const{children:d,count:f,config:g}=o,y=findHashCollisionNodeIndex(d,f,a);if(d[y]!==a)return o;if(c.value=!0,f===2){const b=y===0?2:0;return associate(create$9(g),i,0,s,d[b],d[b+1],c)}else{const b=o.fork(i);return b.children.splice(y,2),b.count-=1,b}},forkCollision=(o,i=null)=>canEdit(o.edit,i)?o:new HashCollisionNode(i,o.count,o.children.slice(),o.config),findHashCollisionNodeIndex=(o,i,s)=>{let a=0;for(;as;)a+=2;return a},create$9=(o,i=null)=>new BitmapIndexedNode(i,o.BitField.empty(Math.pow(2,o.bitWidth)),o.BitField.empty(Math.pow(2,o.bitWidth)),[],o),get$4=(o,i,s)=>lookup(o,0,o.config.Path.from(i),i,s),lookup=(o,i,s,a,c)=>{const{datamap:d,nodemap:f,config:g}=o,{Path:y,BitField:b}=g,$=y.at(s,i);if(b.get(d,$)){const x=b.popcount(d,$);return keyAt(o,x)===a?valueAt(o,x):c}else return b.get(f,$)?resolveNode(o,$).lookup(i+1,s,a,c):c},set$2=(o,i,s,a,c)=>associate(o,i,0,o.config.Path.from(s),s,a,c),associate=(o,i,s,a,c,d,f)=>{const{datamap:g,nodemap:y,config:b}=o,{Path:$,BitField:x}=b,T=$.at(a,s);if(x.get(g,T)){const A=x.popcount(g,T),E=keyAt(o,A);if(c===E)return valueAt(o,A)===d?o:forkAndSet(o,i,A,d);{const S=mergeTwoLeaves(b,i,s+1,$.from(E),E,valueAt(o,A),a,c,d);return f.value=!0,migrateLeafToBranch(o,i,T,S)}}else if(x.get(y,T)){const A=resolveNode(o,T),E=A.associate(i,s+1,a,c,d,f);return A===E?o:copyAndSetChild(o,i,T,E)}else{const A=x.popcount(g,T);f.value=!0;const E=o.fork(i);return E.datamap=x.set(g,T),E.children.splice(keyPosition(A),0,c,d),E}},remove=(o,i,s,a)=>dissociate(o,i,0,o.config.Path.from(s),s,a),dissociate=(o,i,s,a,c,d)=>{const{datamap:f,nodemap:g,config:y}=o,{BitField:b,Path:$}=y,x=$.at(a,s);if(b.get(f,x)){const T=b.popcount(f,x);if(c===keyAt(o,T)){d.value=!0;const A=fork$1(o,i);return A.datamap=b.unset(o.datamap,x),A.children.splice(keyPosition(T),2),A}else return o}else if(b.get(g,x)){const T=resolveNode(o,x),A=T.dissociate(i,s+1,a,c,d);return hasSingleLeaf(A)?hasSingleNode(o)?A:inlineChild(o,i,x,A):T===A?o:copyAndSetChild(o,i,x,A)}else return o},entries=function*({children:o}){let i=0;const s=o.length;for(;icanEdit(o.edit,i)?o:new BitmapIndexedNode(i,o.datamap,o.nodemap,o.children.slice(),o.config),keys=function*({children:o}){let i=0;const s=o.length;for(;i{const c=o.fork(i);return c.children[valuePosition(s)]=a,c},inlineChild=(o,i,s,a)=>{const{datamap:c,nodemap:d,config:f}=o,{BitField:g}=f,y=fork$1(o,i);return y.children.splice(nodePosition(o,s),1),y.children.splice(keyPosition(g.popcount(c,s)),0,a.children[0],a.children[1]),y.datamap=g.set(c,s),y.nodemap=g.unset(d,s),y},copyAndSetChild=(o,i,s,a)=>{const c=fork$1(o,i);return c.children[nodePosition(o,s)]=a,c},migrateLeafToBranch=(o,i,s,a)=>{const{nodemap:c,datamap:d,config:f}=o,{BitField:g}=f,y=g.popcount(d,s),b=keyPosition(y),$=nodePosition(o,s),x=fork$1(o,i);return x.datamap=g.unset(d,s),x.children.splice(b,2),x.nodemap=g.set(c,s),x.children.splice($-1,0,a),x},mergeTwoLeaves=(o,i,s,a,c,d,f,g,y)=>{const{BitField:b,Path:$}=o;if($.sizeo[keyPosition(i)],keyPosition=o=>o*2,valueAt=({children:o},i)=>o[valuePosition(i)],valuePosition=o=>o*2+1,resolveNode=(o,i)=>o.children[nodePosition(o,i)],nodePosition=({children:o,nodemap:i,config:s},a)=>o.length-1-s.BitField.popcount(i,a),canEdit=(o,i)=>o!=null&&o===i,hasSingleLeaf=o=>o.nodeArity===0&&o.dataArity===1,hasSingleNode=({config:{BitField:o},datamap:i,nodemap:s})=>o.popcount(i)===0&&o.popcount(s)===1,empty$1=new Uint8Array(0);function fromHex(o){const i=o.match(/../g);return i!=null?new Uint8Array(i.map(s=>parseInt(s,16))):empty$1}function coerce$2(o){if(o instanceof Uint8Array&&o.constructor.name==="Uint8Array")return o;if(o instanceof ArrayBuffer)return new Uint8Array(o);if(ArrayBuffer.isView(o))return new Uint8Array(o.buffer,o.byteOffset,o.byteLength);throw new Error("Unknown type, must be binary type")}function base$2(o,i){if(o.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src$2=base$2,_brrp__multiformats_scope_baseX$2=src$2;let Encoder$2=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseEncode");this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}},Decoder$2=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseDecode");U(this,"prefixCodePoint");this.name=i,this.prefix=s;const c=s.codePointAt(0);if(c===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=c,this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or$3(this,i)}},ComposedDecoder$2=class{constructor(i){U(this,"decoders");this.decoders=i}or(i){return or$3(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a!=null)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$3(o,i){return new ComposedDecoder$2({...o.decoders??{[o.prefix]:o},...i.decoders??{[i.prefix]:i}})}let Codec$2=class{constructor(i,s,a,c){U(this,"name");U(this,"prefix");U(this,"baseEncode");U(this,"baseDecode");U(this,"encoder");U(this,"decoder");this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder$2(i,s,a),this.decoder=new Decoder$2(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}};function from$7({name:o,prefix:i,encode:s,decode:a}){return new Codec$2(o,i,s,a)}function baseX$2({name:o,prefix:i,alphabet:s}){const{encode:a,decode:c}=_brrp__multiformats_scope_baseX$2(s,o);return from$7({prefix:i,name:o,encode:a,decode:d=>coerce$2(c(d))})}function decode$b(o,i,s,a){const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f}function encode$8(o,i,s){const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f!==0&&(d+=i[c&g<=INT$3;)i[s++]=o&255|MSB$3,o/=128;for(;o&MSBALL$3;)i[s++]=o&255|MSB$3,o>>>=7;return i[s]=o|0,encode$7.bytes=s-a+1,i}var decode$a=read$3,MSB$1$3=128,REST$1$3=127;function read$3(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$3.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$3)<=MSB$1$3);return read$3.bytes=d-a,s}var N1$2=Math.pow(2,7),N2$2=Math.pow(2,14),N3$2=Math.pow(2,21),N4$2=Math.pow(2,28),N5$2=Math.pow(2,35),N6$2=Math.pow(2,42),N7$2=Math.pow(2,49),N8$2=Math.pow(2,56),N9$2=Math.pow(2,63),length$2=function(o){return ocreate$8(this.code,a))}else throw Error("Unknown type, must be binary type")}};const murmur364=from$6({name:"murmur3-x64-64",code:34,encode:o=>fromHex(mur.x64.hash128(o)).subarray(0,8)}),utf8$1=new TextEncoder,hash64$1=o=>murmur364.encode(o),configure$2=({bitWidth:o=8,hash:i=hash64$1}={})=>{const s=i(new Uint8Array).byteLength;return{from:d=>i(utf8$1.encode(d)),at:(d,f)=>{const g=f*o;if(g>s)throw new RangeError("Out of bounds");return toInt(d,g,o)},size:Math.ceil(s*8/o)}},toInt=(o,i,s)=>{let a=i/8|0,c=i%8,d=s,f=0;for(;d>0&&a>c&g)>>$;f=(f<{if(o%8!==0)throw new Error("Must be multiple of 8");return new Uint8Array(o/8)},from$5=(o,i)=>{let s=empty(i);for(const a of o){const{byte:c,byteOffset:d,bitOffset:f}=at(s,a);s[d]=c|1<o.byteLength*8,at=(o,i)=>{const s=o.byteLength-1-(i/8|0),a=i%8;return{byte:o[s],byteOffset:s,bitOffset:a}},setByte=(o,i,s)=>{if(o[i]!==s){const a=o.slice(0);return a[i]=s,a}return o},set$1=(o,i)=>{const{byte:s,byteOffset:a,bitOffset:c}=at(o,i);return setByte(o,a,s|1<{const{byte:s,byteOffset:a,bitOffset:c}=at(o,i);return setByte(o,a,s&(255^1<{var{byte:s,bitOffset:a}=at(o,i);return(s>>a&1)!==0},toBytes=o=>o,fromBytes$1=o=>o,popcount=(o,i=o.byteLength*8)=>{const{byteOffset:s,bitOffset:a,byte:c}=at(o,i);let d=popcount$1(c,a),f=o.byteLength-1;for(;f>s;){const g=o[f];d+=bitCount(g),f--}return d},or$2=(o,i)=>{const s=o.slice();let a=0;for(;a{const s=o.slice();let a=0;for(;a({bitWidth:o,BitField:i,Path:s}),from$4=(o,i)=>{const s=builder$1(i);for(const[a,c]of o)s.set(a,c);return s.build()},has=(o,i)=>get$4(o.root,i,NOT_FOUND)!==NOT_FOUND,get$2=(o,i,s=void 0)=>get$4(o.root,i,s),builder$1=o=>{const i={},s=configure$1(o);return new HashMapBuilder(i,0,create$9(s,i),s)};class PersistentHashMap{constructor(i=0,s,a){this.count=i,this.root=s,this.config=a}get size(){return this.count}clone(){return new PersistentHashMap(this.count,this.root,this.config)}empty(){return new PersistentHashMap(0,create$9(this.config,null),this.config)}has(i){return has(this,i)}get(i){return get$4(this.root,i,void 0)}set(i,s){const a={value:!1},c=set$2(this.root,null,i,s,a);return c===this.root?this:new PersistentHashMap(a.value?this.count+1:this.count,c,this.config)}delete(i){const s=remove(this.root,null,i,{value:!1});return s===this.root?this:new PersistentHashMap(this.count-1,s,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 HashMapBuilder({},this.count,this.root,this.config)}}class HashMapBuilder{constructor(i,s,a,c){this.edit=i,this.count=s,this.root=a,this.config=c}get size(){if(this.edit)return this.count;throw new Error(".size was accessed on the finalized builder")}set(i,s){if(this.edit){const a={value:!1},c=set$2(this.root,this.edit,i,s,a);return this.root!==c&&(this.root=c),a.value&&(this.count+=1),this}else throw new Error(".set was called on the finalized builder")}delete(i){if(this.edit){if(this.count===0)return this;const s={value:!1},a=remove(this.root,this.edit,i,s);return a!==this.root&&(this.root=a),s.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 PersistentHashMap(this.count,this.root,this.config);throw new Error(".build was called on the finalized builder")}}const utf8=new TextEncoder,hash64=o=>murmur364.encode(o),configure=({bitWidth:o=8,hash:i=hash64})=>{const s=i(new Uint8Array).byteLength,a={bitWidth:o,hash:i,hashSize:s};return{at:(f,g)=>read$2(f,g,a),from:f=>utf8.encode(f),size:1/0}},read$2=(o,i=0,{bitWidth:s=8,hash:a,hashSize:c})=>{const d=c*8;let f=0,g=s,y=s*i;for(;g>0;){const b=y/d>>0,$=a(b===0?o:appendByte(o,b)),x=d<=y?y%d:y,T=d-x,A=T{const s=new Uint8Array(o.byteLength+1).fill(i,o.byteLength);return s.set(o),s},bitWidth=8,config={bitWidth,Path:configure({bitWidth})},tableSize=o=>Math.pow(2,o.config.bitWidth),builder=(o=config)=>builder$1(o),from$3=(o,i=config)=>from$4(o,i),bitField=({datamap:o,nodemap:i,config:{BitField:s}})=>withoutLeadingZeros(s.toBytes(s.or(o,i))),withoutLeadingZeros=o=>{let i=0;for(;i`[${JSON.stringify(f)}]`).join("")}`);const d=CID$2.asCID(s);if(d)return{value:d,remaining:i.slice(a+1).join("/")}}return{value:s}}class Block{constructor({cid:i,bytes:s,value:a}){if(!i||!s||typeof a>"u")throw new Error("Missing required argument");this.cid=i,this.bytes=s,this.value=a,this.asBlock=this,Object.defineProperties(this,{cid:readonly(),bytes:readonly(),value:readonly(),asBlock:readonly()})}links(){return links(this.value,[])}tree(){return tree(this.value,[])}get(i="/"){return get$1(this.value,i.split("/").filter(Boolean))}}const defaults=defaults$2,create$7=({writer:o,settings:i=defaults(),metadata:s={}})=>new HAMTDirectoryWriter({writer:o,metadata:s,settings:i,entries:new HashMap,closed:!1}),asWritable=o=>{if(o.closed)throw new Error("Can not change written HAMT directory, but you can .fork() and make changes to it");return o},close$1=async(o,{closeWriter:i=!1,releaseLock:s=!1}={})=>{const{writer:a,settings:c,metadata:d}=asWritable(o.state);o.state.closed=!0;const{entries:f}=o.state;if(!(f instanceof HashMap))throw new Error(`not a HAMT: ${f}`);const g=f.builder.build(),y=iterateBlocks(g,g.root,c);let b=null;for await(const $ of y)b=$,(a.desiredSize||0)<=0&&await a.ready,a.write($);if(b==null)throw new Error("no root block yielded");return i?await a.close():s&&a.releaseLock(),{cid:b.cid,dagByteLength:cumulativeDagByteLength(b.bytes,b.value.entries)}},iterateBlocks=async function*(o,i,s){const a=[];for(const d of iterate(i))if("key"in d)a.push({name:`${d.prefix??""}${d.key??""}`,dagByteLength:d.value.dagByteLength,cid:d.value.cid});else{let f=null;for await(const g of iterateBlocks(o,d.node,s))yield g,f=g;if(f==null)throw new Error("no root block yielded");a.push({name:d.prefix,dagByteLength:cumulativeDagByteLength(f.bytes,f.value.entries),cid:f.cid})}const c=createDirectoryShard(a,bitField(i),tableSize(o),murmur364.code);yield await encodeHAMTShardBlock(c,s)};async function encodeHAMTShardBlock(o,i){const s=encodeHAMTShard(o),a=await i.hasher.digest(s),c=i.linker.createLink(code$2,a);return new Block({cid:c,bytes:s,value:o})}const fork=({state:o},{writer:i=o.writer,metadata:s=o.metadata,settings:a=o.settings}={})=>new HAMTDirectoryWriter({writer:i,metadata:s,settings:a,entries:new HashMap(from$3(o.entries.entries()).createBuilder()),closed:!1});class HAMTDirectoryWriter{constructor(i){this.state=i}get writer(){return this.state.writer}get settings(){return this.state.settings}set(i,s,a){return set$4(this,i,s,a)}remove(i){return remove$1(this,i)}fork(i){return fork(this,i)}close(i){return close$1(this,i)}entries(){return this.state.entries.entries()}has(i){return this.state.entries.has(i)}get size(){return this.state.entries.size}}class HashMap extends Map{constructor(i=builder()){super(),this.builder=i}clear(){this.builder=builder()}delete(i){const{root:s}=this.builder;return this.builder.delete(i),this.builder.root!==s}forEach(i,s=this){for(const[a,c]of this.builder.root.entries())i.call(s,c,a,this)}get(i){return get$2(this.builder,i)}has(i){return has(this.builder,i)}set(i,s){return this.builder.set(i,s),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()}}const createWriter=({writable:o,settings:i=defaults$2()})=>new FileSystemWriter({writer:o.getWriter(),settings:i}),close=async(o,{releaseLock:i=!0,closeWriter:s=!0}={})=>(s?await o.writer.close():i&&o.writer.releaseLock(),o);class FileSystemWriter{constructor({writer:i,settings:s}){this.writer=i,this.settings=configure$4(s)}createFileWriter({settings:i=this.settings,metadata:s}={}){return create$b({writer:this.writer,settings:i,metadata:s})}createDirectoryWriter({settings:i=this.settings,metadata:s}={}){return create$a({writer:this.writer,settings:i,metadata:s})}close(i){return close(this,i)}}const BLOCK_SIZE_LIMIT=1048576,defaultCapacity=BLOCK_SIZE_LIMIT*100,withCapacity=(o=defaultCapacity)=>({highWaterMark:o,size:i=>i.bytes.length}),SHARD_THRESHOLD=1e3,queuingStrategy=withCapacity(),defaultSettings=configure$4({fileChunkEncoder:raw,smallFileEncoder:raw,chunker:withMaxChunkSize(1024*1024),fileLayout:withWidth(1024)});function createFileEncoderStream(o,i){const{readable:s,writable:a}=new TransformStream({},queuingStrategy),c=(i==null?void 0:i.settings)??defaultSettings,d=createWriter({writable:a,settings:c}),f=new UnixFSFileBuilder("",o);return(async()=>(await f.finalize(d),await d.close()))(),s}var wt;class UnixFSFileBuilder{constructor(i,s){Y(this,wt);this.name=i,Q(this,wt,s)}async finalize(i){const s=create$b(i);return await F(this,wt).stream().pipeTo(new WritableStream({async write(a){await s.write(a)}})),await s.close()}}wt=new WeakMap;var ot;class UnixFSDirectoryBuilder{constructor(i,s){Y(this,ot);U(this,"entries",new Map);this.name=i,Q(this,ot,s)}async finalize(i){var a;const s=this.entries.size<=SHARD_THRESHOLD?create$a(i):create$7(i);for(const[c,d]of this.entries){const f=await d.finalize(i);(a=F(this,ot))!=null&&a.onDirectoryEntryLink&&F(this,ot).onDirectoryEntryLink({name:d.name,...f}),s.set(c,f)}return await s.close()}}ot=new WeakMap;function createDirectoryEncoderStream(o,i){const s=new UnixFSDirectoryBuilder("",i);for(const g of o){const y=g.name.split("/");(y[0]===""||y[0]===".")&&y.shift();let b=s;for(const[$,x]of y.entries()){if($===y.length-1){b.entries.set(x,new UnixFSFileBuilder(y.join("/"),g));break}let T=b.entries.get(x);if(T==null){const A=b===s?x:`${b.name}/${x}`;T=new UnixFSDirectoryBuilder(A,i),b.entries.set(x,T)}if(!(T instanceof UnixFSDirectoryBuilder))throw new Error(`"${g.name}" cannot be a file and a directory`);b=T}}const{readable:a,writable:c}=new TransformStream({},queuingStrategy),d=(i==null?void 0:i.settings)??defaultSettings,f=createWriter({writable:c,settings:d});return(async()=>{const g=await s.finalize(f);i!=null&&i.onDirectoryEntryLink&&i.onDirectoryEntryLink({name:"",...g}),await f.close()})(),a}async function readHeader(o,i){const s=decodeVarint$1(await o.upTo(8),o);if(s===0)throw new Error("Invalid CAR header (zero length)");const a=await o.exactly(s,!0),c=decode$1a(a);if(CarV1HeaderOrV2Pragma.toTyped(c)===void 0)throw new Error("Invalid CAR header format");if(c.version!==1&&c.version!==2||i!==void 0&&c.version!==i)throw new Error(`Invalid CAR version: ${c.version}${i!==void 0?` (expected ${i})`:""}`);if(c.version===1){if(!Array.isArray(c.roots))throw new Error("Invalid CAR header format");return c}if(c.roots!==void 0)throw new Error("Invalid CAR header format");const d=decodeV2Header(await o.exactly(V2_HEADER_LENGTH,!0));o.seek(d.dataOffset-o.pos);const f=await readHeader(o,1);return Object.assign(f,d)}async function readCid(o){const i=await o.exactly(2,!1);if(i[0]===CIDV0_BYTES$1.SHA2_256&&i[1]===CIDV0_BYTES$1.LENGTH){const f=await o.exactly(34,!0),g=decode$O(f);return CID$6.create(0,CIDV0_BYTES$1.DAG_PB,g)}const s=decodeVarint$1(await o.upTo(8),o);if(s!==1)throw new Error(`Unexpected CID version (${s})`);const a=decodeVarint$1(await o.upTo(8),o),c=await o.exactly(getMultihashLength$1(await o.upTo(8)),!0),d=decode$O(c);return CID$6.create(s,a,d)}async function readBlockHead(o){const i=o.pos;let s=decodeVarint$1(await o.upTo(8),o);if(s===0)throw new Error("Invalid CAR section (zero length)");s+=o.pos-i;const a=await readCid(o),c=s-Number(o.pos-i);return{cid:a,length:s,blockLength:c}}async function readBlock(o){const{cid:i,blockLength:s}=await readBlockHead(o);return{bytes:await o.exactly(s,!0),cid:i}}async function readBlockIndex(o){const i=o.pos,{cid:s,length:a,blockLength:c}=await readBlockHead(o),d={cid:s,length:a,blockLength:c,offset:i,blockOffset:o.pos};return o.seek(d.blockLength),d}function createDecoder(o){const i=(async()=>{const s=await readHeader(o);if(s.version===2){const a=o.pos-s.dataOffset;o=limitReader(o,s.dataSize-a)}return s})();return{header:()=>i,async*blocks(){for(await i;(await o.upTo(8)).length>0;)yield await readBlock(o)},async*blocksIndex(){for(await i;(await o.upTo(8)).length>0;)yield await readBlockIndex(o)}}}function bytesReader(o){let i=0;return{async upTo(s){return o.subarray(i,i+Math.min(s,o.length-i))},async exactly(s,a=!1){if(s>o.length-i)throw new Error("Unexpected end of data");const c=o.subarray(i,i+s);return a&&(i+=s),c},seek(s){i+=s},get pos(){return i}}}function chunkReader(o){let i=0,s=0,a=0,c=new Uint8Array(0);const d=async f=>{s=c.length-a;const g=[c.subarray(a)];for(;ss&&g.push(b.subarray(-s)):g.push(b),s+=b.length}c=new Uint8Array(g.reduce((b,$)=>b+$.length,0));let y=0;for(const b of g)c.set(b,y),y+=b.length;a=0};return{async upTo(f){return c.length-ai&&(c=c.subarray(0,i-s)),c},async exactly(a,c=!1){const d=await o.exactly(a,c);if(d.length+s>i)throw new Error("Unexpected end of data");return c&&(s+=a),d},seek(a){s+=a,o.seek(a)},get pos(){return o.pos}}}class CarIteratorBase{constructor(i,s,a){this._version=i,this._roots=s,this._iterable=a,this._decoded=!1}get version(){return this._version}async getRoots(){return this._roots}}class CarBlockIterator extends CarIteratorBase{[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(i){const{version:s,roots:a,iterator:c}=await fromBytes(i);return new CarBlockIterator(s,a,c)}static async fromIterable(i){const{version:s,roots:a,iterator:c}=await fromIterable(i);return new CarBlockIterator(s,a,c)}}async function fromBytes(o){if(!(o instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return decodeIterator(bytesReader(o))}async function fromIterable(o){if(!o||typeof o[Symbol.asyncIterator]!="function")throw new TypeError("fromIterable() requires an async iterable");return decodeIterator(asyncIterableReader(o))}async function decodeIterator(o){const i=createDecoder(o),{version:s,roots:a}=await i.header();return{version:s,roots:a,iterator:i.blocks()}}const CAR_V1_VERSION=1;function createHeader(o){const i=encode$O({version:CAR_V1_VERSION,roots:o}),s=varint$a.encode(i.length),a=new Uint8Array(s.length+i.length);return a.set(s,0),a.set(i,s.length),a}function createEncoder(o){return{async setRoots(i){const s=createHeader(i);await o.write(s)},async writeBlock(i){const{cid:s,bytes:a}=i;await o.write(new Uint8Array(varint$a.encode(s.bytes.length+a.length))),await o.write(s.bytes),a.length&&await o.write(a)},async close(){await o.end()},version(){return CAR_V1_VERSION}}}function noop(){}function create$6(){const o=[];let i=null,s=noop,a=!1,c=null,d=noop;const f=()=>(i||(i=new Promise(b=>{s=()=>{i=null,s=noop,b()}})),i),g={write(b){o.push(b);const $=f();return d(),$},async end(){a=!0;const b=f();d(),await b}},y={async next(){const b=o.shift();return b?(o.length===0&&s(),{done:!1,value:b}):a?(s(),{done:!0,value:void 0}):(c||(c=new Promise($=>{d=()=>(c=null,d=noop,$(y.next()))})),c)}};return{writer:g,iterator:y}}class CarWriter{constructor(i,s){this._encoder=s,this._mutex=s.setRoots(i),this._ended=!1}async put(i){if(!(i.bytes instanceof Uint8Array)||!i.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");const s=CID$6.asCID(i.cid);if(!s)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:s,bytes:i.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(i){i=toRoots(i);const{encoder:s,iterator:a}=encodeWriter(),c=new CarWriter(i,s),d=new CarWriterOut(a);return{writer:c,out:d}}static createAppender(){const{encoder:i,iterator:s}=encodeWriter();i.setRoots=()=>Promise.resolve();const a=new CarWriter([],i),c=new CarWriterOut(s);return{writer:a,out:c}}static async updateRootsInBytes(i,s){const a=bytesReader(i);await readHeader(a);const c=createHeader(s);if(Number(a.pos)!==c.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${a.pos} bytes, new header is ${c.length} bytes)`);return i.set(c,0),i}}class CarWriterOut{constructor(i){this._iterator=i}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}}function encodeWriter(){const o=create$6(),{writer:i,iterator:s}=o;return{encoder:createEncoder(i),iterator:s}}function toRoots(o){if(o===void 0)return[];if(!Array.isArray(o)){const s=CID$6.asCID(o);if(!s)throw new TypeError("roots must be a single CID or an array of CIDs");return[s]}const i=[];for(const s of o){const a=CID$6.asCID(s);if(!a)throw new TypeError("roots must be a single CID or an array of CIDs");i.push(a)}return i}const code=514,NO_ROOTS_HEADER_LENGTH=18;function headerEncodingLength(o){if(!o)return NO_ROOTS_HEADER_LENGTH;const i=encode$O({version:1,roots:[o]}).length;return varint$a.encodingLength(i)+i}function blockHeaderEncodingLength(o){const i=o.cid.bytes.length+o.bytes.length;return varint$a.encodingLength(i)+o.cid.bytes.length}function blockEncodingLength(o){return blockHeaderEncodingLength(o)+o.bytes.length}async function encode$6(o,i){const{writer:s,out:a}=CarWriter.create(i);let c;(async()=>{try{for await(const g of o)await s.put(g)}catch(g){c=g}finally{await s.close()}})();const d=[];for await(const g of a)d.push(g);if(c!=null)throw c;const f=i!=null?[i]:[];return Object.assign(new Blob(d),{version:1,roots:f})}class BlockStream extends ReadableStream{constructor(i){let s=null;const a=()=>s||(s=CarBlockIterator.fromIterable(toIterable(i.stream())),s);let c=null;super({async start(){c=(await a())[Symbol.asyncIterator]()},async pull(d){if(!c)throw new Error("missing blocks iterator");const{value:f,done:g}=await c.next();if(g)return d.close();d.enqueue(f)}}),this.getRoots=async()=>await(await a()).getRoots()}}function toIterable(o){return Symbol.asyncIterator in o?o:async function*(){const i=o.getReader();try{for(;;){const{done:s,value:a}=await i.read();if(s)return;yield a}}finally{i.releaseLock()}}()}function compare(o,i){for(let s=0;si[s])return 1}return o.byteLength>i.byteLength?1:o.byteLength=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src$1=base$1,_brrp__multiformats_scope_baseX$1=src$1;let Encoder$1=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseEncode");this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}},Decoder$1=class{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseDecode");U(this,"prefixCodePoint");this.name=i,this.prefix=s;const c=s.codePointAt(0);if(c===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=c,this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or$1(this,i)}},ComposedDecoder$1=class{constructor(i){U(this,"decoders");this.decoders=i}or(i){return or$1(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a!=null)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function or$1(o,i){return new ComposedDecoder$1({...o.decoders??{[o.prefix]:o},...i.decoders??{[i.prefix]:i}})}let Codec$1=class{constructor(i,s,a,c){U(this,"name");U(this,"prefix");U(this,"baseEncode");U(this,"baseDecode");U(this,"encoder");U(this,"decoder");this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder$1(i,s,a),this.decoder=new Decoder$1(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}};function from$2({name:o,prefix:i,encode:s,decode:a}){return new Codec$1(o,i,s,a)}function baseX$1({name:o,prefix:i,alphabet:s}){const{encode:a,decode:c}=_brrp__multiformats_scope_baseX$1(s,o);return from$2({prefix:i,name:o,encode:a,decode:d=>coerce$1(c(d))})}function decode$9(o,i,s,a){const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f}function encode$5(o,i,s){const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f!==0&&(d+=i[c&g<(o[s]=i,o),[]),alphabetCharsToBytes=alphabet.reduce((o,i,s)=>{const a=i.codePointAt(0);if(a==null)throw new Error(`Invalid character: ${i}`);return o[a]=s,o},[]);function encode$4(o){return o.reduce((i,s)=>(i+=alphabetBytesToChars[s],i),"")}function decode$8(o){const i=[];for(const s of o){const a=s.codePointAt(0);if(a==null)throw new Error(`Invalid character: ${s}`);const c=alphabetCharsToBytes[a];if(c==null)throw new Error(`Non-base256emoji character: ${s}`);i.push(c)}return new Uint8Array(i)}from$2({prefix:"🚀",name:"base256emoji",encode:encode$4,decode:decode$8});const base32$1=rfc4648$1({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5});rfc4648$1({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5});rfc4648$1({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5});rfc4648$1({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5});rfc4648$1({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5});rfc4648$1({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5});rfc4648$1({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5});rfc4648$1({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5});rfc4648$1({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});const base36$1=baseX$1({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"});baseX$1({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});const base58btc$1=baseX$1({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});baseX$1({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});rfc4648$1({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6});rfc4648$1({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6});rfc4648$1({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6});rfc4648$1({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});rfc4648$1({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});from$2({prefix:"\0",name:"identity",encode:o=>toString(o),decode:o=>fromString(o)});new TextEncoder;new TextDecoder;var encode_1$1=encode$3,MSB$2=128,REST$2=127,MSBALL$2=~REST$2,INT$2=Math.pow(2,31);function encode$3(o,i,s){i=i||[],s=s||0;for(var a=s;o>=INT$2;)i[s++]=o&255|MSB$2,o/=128;for(;o&MSBALL$2;)i[s++]=o&255|MSB$2,o>>>=7;return i[s]=o|0,encode$3.bytes=s-a+1,i}var decode$7=read$1,MSB$1$2=128,REST$1$2=127;function read$1(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read$1.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$2)<=MSB$1$2);return read$1.bytes=d-a,s}var N1$1=Math.pow(2,7),N2$1=Math.pow(2,14),N3$1=Math.pow(2,21),N4$1=Math.pow(2,28),N5$1=Math.pow(2,35),N6$1=Math.pow(2,42),N7$1=Math.pow(2,49),N8$1=Math.pow(2,56),N9$1=Math.pow(2,63),length$1=function(o){return ocreate$5(this.code,a))}else throw Error("Unknown type, must be binary type")}}function sha(o){return async i=>new Uint8Array(await crypto.subtle.digest(o,i))}const sha256=from$1({name:"sha2-256",code:18,encode:sha("SHA-256")});function format$1(o,i){const{bytes:s,version:a}=o;switch(a){case 0:return toStringV0$1(s,baseCache$1(o),i??base58btc$1.encoder);default:return toStringV1$1(s,baseCache$1(o),i??base32$1.encoder)}}const cache$2=new WeakMap;function baseCache$1(o){const i=cache$2.get(o);if(i==null){const s=new Map;return cache$2.set(o,s),s}return i}var Yt;let CID$1=class we{constructor(i,s,a,c){U(this,"code");U(this,"version");U(this,"multihash");U(this,"bytes");U(this,"/");U(this,Yt,"CID");this.code=s,this.version=i,this.multihash=a,this.bytes=c,this["/"]=c}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:{const{code:i,multihash:s}=this;if(i!==DAG_PB_CODE$2)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(s.code!==SHA_256_CODE$1)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return we.createV0(s)}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:{const{code:i,digest:s}=this.multihash,a=create$5(i,s);return we.createV1(this.code,a)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(i){return we.equals(this,i)}static equals(i,s){const a=s;return a!=null&&i.code===a.code&&i.version===a.version&&equals$3(i.multihash,a.multihash)}toString(i){return format$1(this,i)}toJSON(){return{"/":format$1(this)}}link(){return this}[(Yt=Symbol.toStringTag,Symbol.for("nodejs.util.inspect.custom"))](){return`CID(${this.toString()})`}static asCID(i){if(i==null)return null;const s=i;if(s instanceof we)return s;if(s["/"]!=null&&s["/"]===s.bytes||s.asCID===s){const{version:a,code:c,multihash:d,bytes:f}=s;return new we(a,c,d,f??encodeCID$1(a,c,d.bytes))}else if(s[cidSymbol$1]===!0){const{version:a,multihash:c,code:d}=s,f=decode$5(c);return we.create(a,d,f)}else return null}static create(i,s,a){if(typeof s!="number")throw new Error("String codecs are no longer supported");if(!(a.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(i){case 0:{if(s!==DAG_PB_CODE$2)throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE$2}) block encoding`);return new we(i,s,a,a.bytes)}case 1:{const c=encodeCID$1(i,s,a.bytes);return new we(i,s,a,c)}default:throw new Error("Invalid version")}}static createV0(i){return we.create(0,DAG_PB_CODE$2,i)}static createV1(i,s){return we.create(1,i,s)}static decode(i){const[s,a]=we.decodeFirst(i);if(a.length!==0)throw new Error("Incorrect length");return s}static decodeFirst(i){const s=we.inspectBytes(i),a=s.size-s.multihashSize,c=coerce$1(i.subarray(a,a+s.multihashSize));if(c.byteLength!==s.multihashSize)throw new Error("Incorrect length");const d=c.subarray(s.multihashSize-s.digestSize),f=new Digest$1(s.multihashCode,s.digestSize,d,c);return[s.version===0?we.createV0(f):we.createV1(s.codec,f),i.subarray(s.size)]}static inspectBytes(i){let s=0;const a=()=>{const[x,T]=decode$6(i.subarray(s));return s+=T,x};let c=a(),d=DAG_PB_CODE$2;if(c===18?(c=0,s=0):d=a(),c!==0&&c!==1)throw new RangeError(`Invalid CID version ${c}`);const f=s,g=a(),y=a(),b=s+y,$=b-f;return{version:c,codec:d,multihashCode:g,digestSize:y,multihashSize:$,size:b}}static parse(i,s){const[a,c]=parseCIDtoBytes$1(i,s),d=we.decode(c);if(d.version===0&&i[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache$1(d).set(a,i),d}};function parseCIDtoBytes$1(o,i){switch(o[0]){case"Q":{const s=i??base58btc$1;return[base58btc$1.prefix,s.decode(`${base58btc$1.prefix}${o}`)]}case base58btc$1.prefix:{const s=i??base58btc$1;return[base58btc$1.prefix,s.decode(o)]}case base32$1.prefix:{const s=i??base32$1;return[base32$1.prefix,s.decode(o)]}case base36$1.prefix:{const s=i??base36$1;return[base36$1.prefix,s.decode(o)]}default:{if(i==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[o[0],i.decode(o)]}}}function toStringV0$1(o,i,s){const{prefix:a}=s;if(a!==base58btc$1.prefix)throw Error(`Cannot string encode V0 in ${s.name} encoding`);const c=i.get(a);if(c==null){const d=s.encode(o).slice(1);return i.set(a,d),d}else return c}function toStringV1$1(o,i,s){const{prefix:a}=s,c=i.get(a);if(c==null){const d=s.encode(o);return i.set(a,d),d}else return c}const DAG_PB_CODE$2=112,SHA_256_CODE$1=18;function encodeCID$1(o,i,s){const a=encodingLength$1(o),c=a+encodingLength$1(i),d=new Uint8Array(c+s.byteLength);return encodeTo$1(o,d,0),encodeTo$1(i,d,a),d.set(s,c),d}const cidSymbol$1=Symbol.for("@ipld/js-cid/CID");function create$4(o,i){return CID$1.create(1,o,i)}const cache$1=new WeakMap,toBase58String=o=>{let i=cache$1.get(o.bytes);return i||(i=base58btc$1.encode(o.bytes),cache$1.set(o.bytes,i)),i};var ve;class DigestMap{constructor(i){Y(this,ve);Q(this,ve,new Map);for(const[s,a]of i??[])this.set(s,a)}get[Symbol.toStringTag](){return"DigestMap"}clear(){F(this,ve).clear()}delete(i){const s=toBase58String(i);return F(this,ve).delete(s)}forEach(i,s){for(const[a,c]of F(this,ve).values())i.call(s,c,a,this)}get(i){const s=F(this,ve).get(toBase58String(i));if(s)return s[1]}has(i){return F(this,ve).has(toBase58String(i))}set(i,s){return F(this,ve).set(toBase58String(i),[i,s]),this}get size(){return F(this,ve).size}[Symbol.iterator](){return this.entries()}*entries(){yield*F(this,ve).values()}*keys(){for(const[i]of F(this,ve).values())yield i}*values(){for(const[,i]of F(this,ve).values())yield i}}ve=new WeakMap;const version="index/sharded/dag@0.1";variant({[version]:struct({content:match$2(),shards:array(match$2())})});var $t,Ke;class ShardedDAGIndex{constructor(i){Y(this,$t);Y(this,Ke);Q(this,$t,i),Q(this,Ke,new DigestMap)}get content(){return F(this,$t)}get shards(){return F(this,Ke)}setSlice(i,s,a){let c=F(this,Ke).get(i);c||(c=new DigestMap,F(this,Ke).set(i,c)),c.set(s,a)}archive(){return archive$1(this)}}$t=new WeakMap,Ke=new WeakMap;const create$3=o=>new ShardedDAGIndex(o),archive$1=async o=>{const i=new Map,s=[...o.shards.entries()].sort((g,y)=>compare(g[0].digest,y[0].digest)),a={content:o.content,shards:[]};for(const g of s){const y=[...g[1].entries()].sort((T,A)=>compare(T[0].digest,A[0].digest)).map(T=>[T[0].bytes,T[1]]),b=encode$O([g[0].bytes,y]),$=await sha256.digest(b),x=create$4(code$h,$);i.set(x.toString(),{cid:x,bytes:b}),a.shards.push(x)}const c=encode$O({[version]:a}),d=await sha256.digest(c),f=create$4(code$h,d);return ok(encode$v({roots:[{cid:f,bytes:c}],blocks:i}))};function alloc(o=0){return new Uint8Array(o)}function allocUnsafe(o=0){return new Uint8Array(o)}function asUint8Array(o){return o}function concat(o,i){i==null&&(i=o.reduce((c,d)=>c+d.length,0));const s=allocUnsafe(i);let a=0;for(const c of o)s.set(c,a),a+=c.length;return s}function equals$2(o,i){if(o===i)return!0;if(o.byteLength!==i.byteLength)return!1;for(let s=0;s0&&this.appendAll(i)}*[(Jt=symbol,Symbol.iterator)](){yield*this.bufs}get byteLength(){return this.length}append(...i){this.appendAll(i)}appendAll(i){let s=0;for(const a of i)if(a instanceof Uint8Array)s+=a.byteLength,this.bufs.push(a);else if(isUint8ArrayList(a))s+=a.byteLength,this.bufs.push(...a.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=s}prepend(...i){this.prependAll(i)}prependAll(i){let s=0;for(const a of i.reverse())if(a instanceof Uint8Array)s+=a.byteLength,this.bufs.unshift(a);else if(isUint8ArrayList(a))s+=a.byteLength,this.bufs.unshift(...a.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=s}get(i){const s=findBufAndOffset(this.bufs,i);return s.buf[s.index]}set(i,s){const a=findBufAndOffset(this.bufs,i);a.buf[a.index]=s}write(i,s=0){if(i instanceof Uint8Array)for(let a=0;a0;)if(i>=this.bufs[0].byteLength)i-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(i),this.length-=i;break}}}slice(i,s){const{bufs:a,length:c}=this._subList(i,s);return concat(a,c)}subarray(i,s){const{bufs:a,length:c}=this._subList(i,s);return a.length===1?a[0]:concat(a,c)}sublist(i,s){const{bufs:a,length:c}=this._subList(i,s),d=new Uint8ArrayList;return d.length=c,d.bufs=[...a],d}_subList(i,s){if(i=i??0,s=s??this.length,i<0&&(i=this.length+i),s<0&&(s=this.length+s),i<0||s>this.length)throw new RangeError("index is out of bounds");if(i===s)return{bufs:[],length:0};if(i===0&&s===this.length)return{bufs:this.bufs,length:this.length};const a=[];let c=0;for(let d=0;d=y)continue;const b=i>=g&&ig&&s<=y;if(b&&$){if(i===g&&s===y){a.push(f);break}const x=i-g;a.push(f.subarray(x,x+(s-i)));break}if(b){if(i===0){a.push(f);continue}a.push(f.subarray(i-g));continue}if($){if(s===y){a.push(f);break}a.push(f.subarray(0,s-g));break}a.push(f)}return{bufs:a,length:s-i}}indexOf(i,s=0){if(!isUint8ArrayList(i)&&!(i instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const a=i instanceof Uint8Array?i:i.subarray();if(s=Number(s??0),isNaN(s)&&(s=0),s<0&&(s=this.length+s),s<0&&(s=0),i.length===0)return s>this.length?this.length:s;const c=a.byteLength;if(c===0)throw new TypeError("search must be at least 1 byte long");const d=256,f=new Int32Array(d);for(let x=0;x=0;T--){const A=this.get(x+T);if(a[T]!==A){$=Math.max(1,T-g[A]);break}}if($===0)return x}return-1}getInt8(i){const s=this.subarray(i,i+1);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt8(0)}setInt8(i,s){const a=allocUnsafe(1);new DataView(a.buffer,a.byteOffset,a.byteLength).setInt8(0,s),this.write(a,i)}getInt16(i,s){const a=this.subarray(i,i+2);return new DataView(a.buffer,a.byteOffset,a.byteLength).getInt16(0,s)}setInt16(i,s,a){const c=alloc(2);new DataView(c.buffer,c.byteOffset,c.byteLength).setInt16(0,s,a),this.write(c,i)}getInt32(i,s){const a=this.subarray(i,i+4);return new DataView(a.buffer,a.byteOffset,a.byteLength).getInt32(0,s)}setInt32(i,s,a){const c=alloc(4);new DataView(c.buffer,c.byteOffset,c.byteLength).setInt32(0,s,a),this.write(c,i)}getBigInt64(i,s){const a=this.subarray(i,i+8);return new DataView(a.buffer,a.byteOffset,a.byteLength).getBigInt64(0,s)}setBigInt64(i,s,a){const c=alloc(8);new DataView(c.buffer,c.byteOffset,c.byteLength).setBigInt64(0,s,a),this.write(c,i)}getUint8(i){const s=this.subarray(i,i+1);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint8(0)}setUint8(i,s){const a=allocUnsafe(1);new DataView(a.buffer,a.byteOffset,a.byteLength).setUint8(0,s),this.write(a,i)}getUint16(i,s){const a=this.subarray(i,i+2);return new DataView(a.buffer,a.byteOffset,a.byteLength).getUint16(0,s)}setUint16(i,s,a){const c=alloc(2);new DataView(c.buffer,c.byteOffset,c.byteLength).setUint16(0,s,a),this.write(c,i)}getUint32(i,s){const a=this.subarray(i,i+4);return new DataView(a.buffer,a.byteOffset,a.byteLength).getUint32(0,s)}setUint32(i,s,a){const c=alloc(4);new DataView(c.buffer,c.byteOffset,c.byteLength).setUint32(0,s,a),this.write(c,i)}getBigUint64(i,s){const a=this.subarray(i,i+8);return new DataView(a.buffer,a.byteOffset,a.byteLength).getBigUint64(0,s)}setBigUint64(i,s,a){const c=alloc(8);new DataView(c.buffer,c.byteOffset,c.byteLength).setBigUint64(0,s,a),this.write(c,i)}getFloat32(i,s){const a=this.subarray(i,i+4);return new DataView(a.buffer,a.byteOffset,a.byteLength).getFloat32(0,s)}setFloat32(i,s,a){const c=alloc(4);new DataView(c.buffer,c.byteOffset,c.byteLength).setFloat32(0,s,a),this.write(c,i)}getFloat64(i,s){const a=this.subarray(i,i+8);return new DataView(a.buffer,a.byteOffset,a.byteLength).getFloat64(0,s)}setFloat64(i,s,a){const c=alloc(8);new DataView(c.buffer,c.byteOffset,c.byteLength).setFloat64(0,s,a),this.write(c,i)}equals(i){if(i==null||!(i instanceof Uint8ArrayList)||i.bufs.length!==this.bufs.length)return!1;for(let s=0;sc+d.byteLength,0)),a.length=s,a}}function equals$1(o,i){if(o===i)return!0;if(o.byteLength!==i.byteLength)return!1;for(let s=0;s=INT$1;)i[s++]=o&255|MSB$1,o/=128;for(;o&MSBALL$1;)i[s++]=o&255|MSB$1,o>>>=7;return i[s]=o|0,encode$2.bytes=s-a+1,i}var decode$4=read,MSB$1$1=128,REST$1$1=127;function read(o,a){var s=0,a=a||0,c=0,d=a,f,g=o.length;do{if(d>=g)throw read.bytes=0,new RangeError("Could not decode varint");f=o[d++],s+=c<28?(f&REST$1$1)<=MSB$1$1);return read.bytes=d-a,s}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length=function(o){return o=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),a=0;a>>0,I=new Uint8Array(D);C!==B;){for(var O=E[C],N=0,L=D-1;(O!==0||N<_)&&L!==-1;L--,N++)O+=256*I[L]>>>0,I[L]=O%g>>>0,O=O/g>>>0;if(O!==0)throw new Error("Non-zero carry");_=N,C++}for(var R=D-_;R!==D&&I[R]===0;)R++;for(var z=y.repeat(S);R>>0,D=new Uint8Array(B);E[S];){var I=s[E.charCodeAt(S)];if(I===255)return;for(var O=0,N=B-1;(I!==0||O>>0,D[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");C=O,S++}if(E[S]!==" "){for(var L=B-C;L!==B&&D[L]===0;)L++;for(var R=new Uint8Array(_+(B-L)),z=_;L!==B;)R[z++]=D[L++];return R}}}function A(E){var S=T(E);if(S)return S;throw new Error(`Non-${i} character`)}return{encode:x,decodeUnsafe:T,decode:A}}var src=base,_brrp__multiformats_scope_baseX=src;class Encoder{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseEncode");this.name=i,this.prefix=s,this.baseEncode=a}encode(i){if(i instanceof Uint8Array)return`${this.prefix}${this.baseEncode(i)}`;throw Error("Unknown type, must be binary type")}}class Decoder{constructor(i,s,a){U(this,"name");U(this,"prefix");U(this,"baseDecode");U(this,"prefixCodePoint");this.name=i,this.prefix=s;const c=s.codePointAt(0);if(c===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=c,this.baseDecode=a}decode(i){if(typeof i=="string"){if(i.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(i)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(i.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(i){return or(this,i)}}class ComposedDecoder{constructor(i){U(this,"decoders");this.decoders=i}or(i){return or(this,i)}decode(i){const s=i[0],a=this.decoders[s];if(a!=null)return a.decode(i);throw RangeError(`Unable to decode multibase string ${JSON.stringify(i)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function or(o,i){return new ComposedDecoder({...o.decoders??{[o.prefix]:o},...i.decoders??{[i.prefix]:i}})}class Codec{constructor(i,s,a,c){U(this,"name");U(this,"prefix");U(this,"baseEncode");U(this,"baseDecode");U(this,"encoder");U(this,"decoder");this.name=i,this.prefix=s,this.baseEncode=a,this.baseDecode=c,this.encoder=new Encoder(i,s,a),this.decoder=new Decoder(i,s,c)}encode(i){return this.encoder.encode(i)}decode(i){return this.decoder.decode(i)}}function from({name:o,prefix:i,encode:s,decode:a}){return new Codec(o,i,s,a)}function baseX({name:o,prefix:i,alphabet:s}){const{encode:a,decode:c}=_brrp__multiformats_scope_baseX(s,o);return from({prefix:i,name:o,encode:a,decode:d=>coerce(c(d))})}function decode$1(o,i,s,a){const c={};for(let $=0;$=8&&(g-=8,f[b++]=255&y>>g)}if(g>=s||255&y<<8-g)throw new SyntaxError("Unexpected end of data");return f}function encode$1(o,i,s){const a=i[i.length-1]==="=",c=(1<s;)f-=s,d+=i[c&g>>f];if(f!==0&&(d+=i[c&g<{const[x,T]=decode$3(i.subarray(s));return s+=T,x};let c=a(),d=DAG_PB_CODE$1;if(c===18?(c=0,s=0):d=a(),c!==0&&c!==1)throw new RangeError(`Invalid CID version ${c}`);const f=s,g=a(),y=a(),b=s+y,$=b-f;return{version:c,codec:d,multihashCode:g,digestSize:y,multihashSize:$,size:b}}static parse(i,s){const[a,c]=parseCIDtoBytes(i,s),d=CID.decode(c);if(d.version===0&&i[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return baseCache(d).set(a,i),d}}function parseCIDtoBytes(o,i){switch(o[0]){case"Q":{const s=i??base58btc;return[base58btc.prefix,s.decode(`${base58btc.prefix}${o}`)]}case base58btc.prefix:{const s=i??base58btc;return[base58btc.prefix,s.decode(o)]}case base32.prefix:{const s=i??base32;return[base32.prefix,s.decode(o)]}case base36.prefix:{const s=i??base36;return[base36.prefix,s.decode(o)]}default:{if(i==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[o[0],i.decode(o)]}}}function toStringV0(o,i,s){const{prefix:a}=s;if(a!==base58btc.prefix)throw Error(`Cannot string encode V0 in ${s.name} encoding`);const c=i.get(a);if(c==null){const d=s.encode(o).slice(1);return i.set(a,d),d}else return c}function toStringV1(o,i,s){const{prefix:a}=s,c=i.get(a);if(c==null){const d=s.encode(o);return i.set(a,d),d}else return c}const DAG_PB_CODE$1=112,SHA_256_CODE=18;function encodeCID(o,i,s){const a=encodingLength(o),c=a+encodingLength(i),d=new Uint8Array(c+s.byteLength);return encodeTo(o,d,0),encodeTo(i,d,a),d.set(s,c),d}const cidSymbol=Symbol.for("@ipld/js-cid/CID"),DAG_PB_CODE=112;function createLegacy(o){return CID.create(0,DAG_PB_CODE,o)}function create$1(o,i){return CID.create(1,o,i)}const MSB=128,REST=127,MSBALL=~REST,INT=Math.pow(2,31),encode=o=>{const i=[];let s=0;for(;o>=INT;)i[s++]=o&255|MSB,o/=128;for(;o&MSBALL;)i[s++]=o&255|MSB,o>>>=7;return i[s]=o|0,i},decode=(o,i)=>{let s=0;i=i||0;let a=0,c=i,d;const f=o.length;do{if(c>=f||a>49)throw new RangeError("Could not decode varint");d=o.get(c++),s+=a<28?(d&REST)<=MSB);return[s,c-i]},State={ReadHeaderLength:0,ReadHeader:1,ReadBlockLength:2,ReadBlock:3},CIDV0_BYTES={SHA2_256:18,LENGTH:32,DAG_PB:112};var xt;class CARReaderStream extends TransformStream{constructor(s,a){const c=new Uint8ArrayList;let d=0,f=d,g=8,y=State.ReadHeaderLength,b;const $=new Promise(x=>{b=x});super({transform(x,T){for(c.append(x);!(c.length{const[,i]=decode(o),[s,a]=decode(o,i);return i+a+s},encodeHeader=o=>{const i=encode$O({version:1,roots:o}),s=encode(i.length),a=new Uint8Array(s.length+i.length);return a.set(s,0),a.set(i,s.length),a},encodeBlock=o=>{const i=encode(o.cid.bytes.length+o.bytes.length),s=new Uint8Array(i.length+o.cid.bytes.length+o.bytes.length);return s.set(i),s.set(o.cid.bytes,i.length),s.set(o.bytes,i.length+o.cid.bytes.length),s};class CARWriterStream extends TransformStream{constructor(i=[],s,a){super({start:c=>c.enqueue(encodeHeader(i)),transform:(c,d)=>d.enqueue(encodeBlock(c))},s,a)}}async function indexShardedDAG(o,i,s){const a=create$3(o);for(const[c,d]of i.entries()){const f=s[c];a.shards.set(d.multihash,f)}return await a.archive()}const SHARD_SIZE=133169152;class ShardingStream extends TransformStream{constructor(i={}){const s=i.shardSize??SHARD_SIZE,a=s-headerEncodingLength();let c=[],d=null,f=new DigestMap,g=null,y=0;super({async transform(b,$){d!=null&&g!=null&&($.enqueue(await encodeCAR(d,g)),d=null,g=null);const x=blockHeaderEncodingLength(b),T=x+b.bytes.length;if(T>a)throw new Error(`block will cause CAR to exceed shard size: ${b.cid}`);c.length&&y+T>a&&(d=c,g=f,c=[],f=new DigestMap,y=0),c.push(b),f.set(b.cid.multihash,[headerEncodingLength()+y+x,b.bytes.length]),y+=T},async flush(b){d!=null&&g!=null&&b.enqueue(await encodeCAR(d,g));const $=c.at(-1);if($==null)return;const x=i.rootCID??$.cid,T=headerEncodingLength(x);if(T+y>s){const A=T+y-s,E=[];let S=0;for(;Sa.name)=>ascending(o,i,s);function ascending(o,i,s){const a=s(o),c=s(i);return a===c?0:aObject.assign(await encode$6(o,s),{slices:i});async function uploadFile(o,i,s={}){return await uploadBlockStream(o,createFileEncoderStream(i,s),s)}async function uploadDirectory(o,i,s={}){const{customOrder:a=!1}=s,c=a?i:[...i].sort(defaultFileComparator);return await uploadBlockStream(o,createDirectoryEncoderStream(c,s),s)}async function uploadCAR(o,i,s={}){const a=new BlockStream(i);return s.rootCID=s.rootCID??(await a.getRoots())[0],await uploadBlockStream(o,a,s)}async function uploadBlockStream(o,i,{pieceHasher:s=PieceHasher,...a}={}){const c=typeof o=="function"?o:()=>o,d=[],f=[];let g=null;if(await i.pipeThrough(new ShardingStream(a)).pipeThrough(new TransformStream({async transform(E,S){const _=new Uint8Array(await E.arrayBuffer()),C=await sha256$2.digest(_),B=await c([{can:ability$2,nb:input$8(C,_.length)}]);await add$2(B,C,_,a);const D=create$g(code,C);let I;if(s){const z=await s.digest(_);I=create$g(code$3,z);const K=create$g(code$3,C),G=await filecoinOffer({issuer:B.issuer,audience:B.audience,with:B.issuer.did(),proofs:B.proofs},K,I,a);if(G.out.error)throw new Error("failed to offer piece for aggregation into filecoin deal",{cause:G.out.error})}const{version:O,roots:N,size:L,slices:R}=E;S.enqueue({version:O,roots:N,size:L,cid:D,piece:I,slices:R})}})).pipeTo(new WritableStream({write(E){g=g||E.roots[0],f.push(E.cid),E.slices.set(E.cid.multihash,[0,E.size]),d.push(E.slices),a.onShardStored&&a.onShardStored(E)}})),!g)throw new Error("missing root CID");const y=await indexShardedDAG(g,f,d);if(!y.ok)throw new Error("failed to archive DAG index",{cause:y.error});const b=await sha256$2.digest(y.ok),$=create$g(code,b),[x,T,A]=await Promise.all([c([{can:ability$2,nb:input$8(b,y.ok.length)}]),c([{can:ability$1,nb:input$4($)}]),c([{can:ability,nb:input$3(g,f)}])]);return await add$2(x,b,y.ok,a),await add$1(T,$,a),await add(A,g,f,a),g}const accessServiceURL=new URL("https://up.web3.storage"),accessServicePrincipal=parse$2("did:web:web3.storage"),accessServiceConnection=connect({id:accessServicePrincipal,codec:outbound,channel:open$2({url:accessServiceURL,method:"POST"})}),uploadServiceURL=new URL("https://up.web3.storage"),uploadServicePrincipal=parse$2("did:web:web3.storage"),uploadServiceConnection=connect({id:uploadServicePrincipal,codec:outbound,channel:open$2({url:uploadServiceURL,method:"POST"})}),filecoinServiceURL=new URL("https://up.web3.storage"),filecoinServicePrincipal=parse$2("did:web:web3.storage"),filecoinServiceConnection=connect({id:filecoinServicePrincipal,codec:outbound,channel:open$2({url:filecoinServiceURL,method:"POST"})}),serviceConf={access:accessServiceConnection,upload:uploadServiceConnection,filecoin:filecoinServiceConnection};class Base{constructor(i,s={}){U(this,"_agent");U(this,"_serviceConf");this._serviceConf=s.serviceConf??serviceConf,this._agent=new Agent(i,{servicePrincipal:this._serviceConf.access.id,url:this._serviceConf.access.channel.url,connection:this._serviceConf.access}),this._receiptsEndpoint=s.receiptsEndpoint??receiptsEndpoint}get agent(){return this._agent}async _invocationConfig(i){const s=this._agent.currentSpace();if(!s)throw new Error("missing current space: use createSpace() or setCurrentSpace()");const a=this._agent.issuer,c=await this._agent.proofs(i.map(f=>({can:f,with:s}))),d=this._serviceConf.upload.id;return{issuer:a,with:s,proofs:c,audience:d}}}const unwrap=({ok:o,error:i})=>{if(i)throw i;return o};class AccessClient extends Base{async authorize(i,s){const a=fromEmail(i),c=unwrap(await request(this,{account:a})),d=unwrap(await c.claim(s));return await unwrap(await d.save()),d.proofs}async claim(i){const s=unwrap(await claim(this,i));return await unwrap(await s.save()),s.proofs}async request(i){return await request(this,i)}async delegate(i){return await delegate(this,i)}}const claim=async({agent:o},i)=>claim$1(o,i),request=async({agent:o},i)=>request$2(o,i),delegate=async({agent:o},i)=>delegate$1(o,i),{spaceAccess,accountAccess}=access;class PlanClient extends Base{async get(i,s){const a=await get({agent:this.agent},{...s,account:i});if(!a.ok)throw new Error(`failed ${get$c.can} invocation`,{cause:a.error});return a.ok}async set(i,s,a){const c=await set({agent:this.agent},{...a,account:i,product:s});if(!c.ok)throw new Error(`failed ${set$5.can} invocation`,{cause:c.error});return c.ok}async createAdminSession(i,s,a){const c=await createAdminSession({agent:this.agent},{...a,account:i,returnURL:s});if(!c.ok)throw new Error(`failed ${createAdminSession$1.can} invocation`,{cause:c.error});return c.ok}}const get=async({agent:o},{account:i,nonce:s,proofs:a=[]})=>(await o.invokeAndExecute(get$c,{with:i,proofs:a,nonce:s})).out,set=async({agent:o},{account:i,product:s,nonce:a,proofs:c=[]})=>(await o.invokeAndExecute(set$5,{with:i,nb:{product:s},nonce:a,proofs:c})).out,createAdminSession=async({agent:o},{account:i,returnURL:s,nonce:a,proofs:c=[]})=>(await o.invokeAndExecute(createAdminSession$1,{with:i,proofs:c,nonce:a,nb:{returnURL:s}})).out;class SubscriptionClient extends Base{async list(i,s){const a=await list$1({agent:this.agent},{...s,account:i});if(!a.ok)throw new Error(`failed ${list$6.can} invocation`,{cause:a.error});return a.ok}}const list$1=async({agent:o},{account:i,nonce:s,proofs:a=[]})=>(await o.invokeAndExecute(list$6,{with:i,proofs:a,nb:{},nonce:s})).out,list=({agent:o},{account:i}={})=>{const s={with:i??/did:mailto:.*/,can:"*"},a=o.proofs([s]),c={},d={};for(const f of a){const g=allows(f);for(const[y,b]of Object.entries(g)){if(AccountDID.is(y)&&b["*"]){const $=y;(c[$]||(c[$]=new Account({id:$,agent:o,proofs:[]}))).addProof(f)}for(const $ of b["ucan/attest"]||[]){const x=$.proof;x&&(d[`${x}`]=f)}}}for(const f of Object.values(c))for(const g of f.proofs){const y=d[`${g.cid}`];y&&f.addProof(y)}return c},login=async({agent:o},i,s={})=>{const a=fromEmail(i),c=list({agent:o},{account:a})[a];if(c)return{ok:c};const d=await request({agent:o},{account:a,access:accountAccess}),{ok:f,error:g}=d;if(g)return{error:g};{const{ok:y,error:b}=await f.claim({signal:s.signal});return b?{error:b}:{ok:new Account({id:a,proofs:y.proofs,agent:o})}}};class Account{constructor(i){this.model=i,this.plan=new AccountPlan(i)}get agent(){return this.model.agent}get proofs(){return this.model.proofs}did(){return this.model.id}toEmail(){return toEmail(this.did())}addProof(i){this.proofs.push(i)}toJSON(){return{id:this.did(),proofs:this.proofs.sort((i,s)=>i.cid.toString().localeCompare(s.cid.toString())).map(i=>i.toJSON())}}provision(i,s={}){return add$7(this.agent,{...s,account:this.did(),consumer:i,proofs:this.proofs})}async save({agent:i=this.agent}={}){return await importAuthorization(i,this)}}class AccountPlan{constructor(i){this.model=i}async get(i){return await get(this.model,{...i,account:this.model.id,proofs:this.model.proofs})}async set(i,s){return await set(this.model,{...s,account:this.model.id,product:i,proofs:this.model.proofs})}async wait(i){var d;const s=Date.now(),a=(i==null?void 0:i.interval)||1e3,c=(i==null?void 0:i.timeout)||60*15*1e3;for(;;){const f=await this.get();if(f.ok)return f.ok;if(f.error)throw new Error(`Error retrieving payment plan: ${f.error}`);if(Date.now()-s>c)throw new Error("Timeout: Payment plan selection took too long.");if((d=i==null?void 0:i.signal)!=null&&d.aborted)throw new Error("Aborted: Payment plan selection was aborted.");console.log("Waiting for payment plan to be selected..."),await new Promise(g=>setTimeout(g,a))}}async createAdminSession(i,s,a){return await createAdminSession(this.model,{...a,account:i,returnURL:s})}async subscriptions(i){return await list$1(this.model,{...i,account:this.model.id,proofs:this.model.proofs})}}class UsageClient extends Base{async report(i,s,a){const c=await report({agent:this.agent},{...a,space:i,period:s});if(!c.ok)throw new Error(`failed ${report$1.can} invocation`,{cause:c.error});return c.ok}}const report=async({agent:o},{space:i,period:s,nonce:a,proofs:c=[]})=>(await o.invokeAndExecute(report$1,{with:i,proofs:c,nonce:a,nb:{period:{from:Math.floor(s.from.getTime()/1e3),to:Math.ceil(s.to.getTime()/1e3)}}})).out;var Qe;class Space{constructor(i){Y(this,Qe);Q(this,Qe,i),this.usage=new StorageUsage(i)}get name(){var i;return String(((i=F(this,Qe).meta)==null?void 0:i.name)??"")}did(){return F(this,Qe).id}meta(){return F(this,Qe).meta}}Qe=new WeakMap;var st;class StorageUsage{constructor(i){Y(this,st);Q(this,st,i)}async get(){const{agent:i}=F(this,st),s=F(this,st).id,a=new Date,c={from:startOfLastMonth(a),to:a},d=await report({agent:i},{space:s,period:c});if(d.error)return d;const f=i.connection.id.did(),g=d.ok[f];return{ok:(g==null?void 0:g.size.final)==null?void 0:BigInt(g.size.final)}}}st=new WeakMap;const startOfMonth=o=>{const i=new Date(o);return i.setUTCDate(1),i.setUTCHours(0),i.setUTCMinutes(0),i.setUTCSeconds(0),i.setUTCMilliseconds(0),i},startOfLastMonth=o=>{const i=startOfMonth(o);return i.setUTCMonth(i.getUTCMonth()-1),i};class BlobClient extends Base{async add(i,s={}){const a=await this._invocationConfig([add$4.can]);s.connection=this._serviceConf.upload;const c=new Uint8Array(await i.arrayBuffer()),d=await sha256$6.digest(c);return{digest:d,...await add$2(a,d,c,s)}}async list(i={}){const s=await this._invocationConfig([list$5.can]);return i.connection=this._serviceConf.upload,list$3(s,i)}async remove(i,s={}){const a=await this._invocationConfig([remove$5.can]);return s.connection=this._serviceConf.upload,remove$3(a,i,s)}async get(i,s={}){const a=await this._invocationConfig([get$b.can]);return s.connection=this._serviceConf.upload,get$8(a,i,s)}}class IndexClient extends Base{async add(i,s={}){const a=await this._invocationConfig([add$5.can]);return s.connection=this._serviceConf.upload,add$1(a,i,s)}}class StoreClient extends Base{async add(i,s={}){const a=await this._invocationConfig([add$a.can]);return s.connection=this._serviceConf.upload,add$3(a,i,s)}async get(i,s={}){const a=await this._invocationConfig([get$h.can]);return s.connection=this._serviceConf.upload,get$a(a,i,s)}async list(i={}){const s=await this._invocationConfig([list$9.can]);return i.connection=this._serviceConf.upload,list$4(s,i)}async remove(i,s={}){const a=await this._invocationConfig([remove$8.can]);return s.connection=this._serviceConf.upload,remove$4(a,i,s)}}class UploadClient extends Base{async add(i,s,a={}){const c=await this._invocationConfig([add$9.can]);return a.connection=this._serviceConf.upload,add(c,i,s,a)}async get(i,s={}){const a=await this._invocationConfig([get$g.can]);return s.connection=this._serviceConf.upload,get$7(a,i,s)}async list(i={}){const s=await this._invocationConfig([list$8.can]);return i.connection=this._serviceConf.upload,list$2(s,i)}async remove(i,s={}){const a=await this._invocationConfig([remove$7.can]);return s.connection=this._serviceConf.upload,remove$2(a,i,s)}}class SpaceClient extends Base{async info(i,s){return await this._agent.getSpaceInfo(i,s)}}class FilecoinClient extends Base{async offer(i,s,a){const c=await this._invocationConfig([filecoinOffer$1.can]);return filecoinOffer(c,i,s,{...a,connection:this._serviceConf.filecoin})}async info(i,s){const a=await this._invocationConfig([filecoinInfo$1.can]);return filecoinInfo(a,i,{...s,connection:this._serviceConf.filecoin})}}class CouponAPI extends Base{async redeem(i,s={}){const{agent:a}=this,c=unwrap(await extract(i));return unwrap(await redeem(c,{...s,agent:a}))}async issue({proofs:i=[],...s}){const{agent:a}=this;return await issue({...s,issuer:a.issuer,proofs:[...i,...a.proofs(s.capabilities)]})}}const extract=async o=>{const{ok:i,error:s}=await extract$1(o);return i?ok(new Coupon({proofs:[i]})):error$1(s)},archive=async o=>{const[i]=o.proofs;return await archive$2(i)},issue=async({password:o="",...i})=>{const s=await deriveSigner(o),a=await delegate$3({...i,audience:s});return new Coupon({proofs:[a]})},redeem=async(o,{agent:i,password:s=""})=>{const a=await deriveSigner(s),[c]=o.proofs;if(c.audience.did()!==a.did())return error$1(new RangeError(s===""?"Extracting account requires a password":"Provided password is invalid"));{const d=await delegate$3({issuer:a,audience:i,capabilities:c.capabilities,expiration:c.expiration,notBefore:c.notBefore,proofs:[c]});return ok(new GrantedAccess({agent:i,proofs:[d]}))}},deriveSigner=async o=>{const{digest:i}=await sha256$4.digest(new TextEncoder().encode(o));return await derive(i)};class Coupon{constructor(i){this.model=i}get proofs(){return this.model.proofs}redeem(i,s={}){return redeem(this,{...s,agent:i})}archive(){return archive(this)}}class Client extends Base{constructor(i,s){super(i,s),this.capability={access:new AccessClient(i,s),filecoin:new FilecoinClient(i,s),index:new IndexClient(i,s),plan:new PlanClient(i,s),space:new SpaceClient(i,s),blob:new BlobClient(i,s),store:new StoreClient(i,s),subscription:new SubscriptionClient(i,s),upload:new UploadClient(i,s),usage:new UsageClient(i,s)},this.coupon=new CouponAPI(i,s)}did(){return this._agent.did()}async authorize(i,s){await this.capability.access.authorize(i,s)}async login(i,s={}){const a=unwrap(await login(this,i,s));return unwrap(await a.save()),a}accounts(){return list(this)}async uploadFile(i,s={}){const a=await this._invocationConfig([add$4.can,add$5.can,filecoinOffer$1.can,add$9.can]);return s.connection=this._serviceConf.upload,uploadFile(a,i,s)}async uploadDirectory(i,s={}){const a=await this._invocationConfig([add$4.can,add$5.can,filecoinOffer$1.can,add$9.can]);return s.connection=this._serviceConf.upload,uploadDirectory(a,i,s)}async uploadCAR(i,s={}){const a=await this._invocationConfig([add$4.can,add$5.can,filecoinOffer$1.can,add$9.can]);return s.connection=this._serviceConf.upload,uploadCAR(a,i,s)}async getReceipt(i){const s=new URL(this._receiptsEndpoint).toString();return poll(i,{receiptsEndpoint:s})}defaultProvider(){return this._agent.connection.id.did()}currentSpace(){const i=this._agent,s=i.currentSpace();if(!s)return;const a=i.spaces.get(s);return new Space({id:s,meta:a,agent:i})}async setCurrentSpace(i){await this._agent.setCurrentSpace(i)}spaces(){return[...this._agent.spaces].map(([i,s])=>new Space({id:i,meta:s,agent:this._agent}))}async createSpace(i,s={}){const a=await this._agent.createSpace(i),c=s.account;if(c){const d=await c.provision(a.did());if(d.error)throw new Error(`failed to provision account: ${d.error.message}`,{cause:d.error});await a.save();const f=await a.createRecovery(c.did()),g=await this.capability.access.delegate({space:a.did(),delegations:[f]});if(g.error)throw new Error(`failed to authorize recovery account: ${g.error.message}`,{cause:g.error})}return a}async shareSpace(i,s,a={abilities:["space/*","store/*","upload/*","access/*","usage/*","filecoin/offer","filecoin/info","filecoin/accept","filecoin/submit"],expiration:1/0}){const{abilities:c,...d}=a,f=this.agent.currentSpace();try{await this.agent.setCurrentSpace(s);const{root:g,blocks:y}=await this.agent.delegate({...d,abilities:c,audience:{did:()=>fromEmail(email(i))},audienceMeta:a.audienceMeta??{}}),b=new AgentDelegation(g,y,{audience:i}),$=await this.capability.access.delegate({space:s,delegations:[b]});if($.error)throw new Error(`failed to share space with ${i}: ${$.error.message}`,{cause:$.error});return b}finally{f&&f!==s&&await this.agent.setCurrentSpace(f)}}async addSpace(i){return await this._agent.importSpaceFromDelegation(i)}proofs(i){return this._agent.proofs(i)}async addProof(i){await this._agent.addProof(i)}delegations(i){const s=[];for(const{delegation:a,meta:c}of this._agent.delegationsWithMeta(i))s.push(new AgentDelegation(a.root,a.blocks,c));return s}async createDelegation(i,s,a={}){const c=a.audienceMeta??{name:"agent",type:"device"},{root:d,blocks:f}=await this._agent.delegate({...a,abilities:s,audience:i,audienceMeta:c});return new AgentDelegation(d,f,{audience:c})}async revokeDelegation(i,s={}){return this._agent.revoke(i,{proofs:s.proofs})}async remove(i,s={}){var c;if(!s.shards){await this.capability.upload.remove(i);return}const a=await this.capability.upload.get(i);(c=a.shards)!=null&&c.length&&await Promise.allSettled(a.shards.map(async d=>{var f;try{const g=await this.capability.blob.remove(d.multihash);g.ok&&g.ok.size===0&&await this.capability.store.remove(d)}catch(g){if(((f=g==null?void 0:g.cause)==null?void 0:f.name)!=="StoreItemNotFound")throw new Error(`failed to remove shard: ${d}`,{cause:g})}})),await this.capability.upload.remove(i)}}new Set(abilitiesAsStrings);async function create(o={}){const i=o.store??new StoreIndexedDB("w3up-client"),s=await i.load();if(s){const d=AgentData.fromExport(s,{store:i});if(o.principal&&d.principal.did()!==o.principal.did())throw new Error(`store cannot be used with ${o.principal.did()}, stored principal and passed principal must match`);return new Client(d,o)}const a=o.principal??await generate(),c=await AgentData.create({principal:a},{store:i});return new Client(c,o)}const toHTTP=o=>o.replace(/^ipfs:\/\//,"https://w3s.link/ipfs/"),upload=async o=>{const i=await create();console.debug({"W3Up Client":i,accounts:i.accounts(),did:i.did()});const s=await fetch("http://localhost:3000/ucan",{method:"POST",body:JSON.stringify({did:i.did()})}),{delegation:a}=await s.json(),{ok:c,error:d}=await extract$1(new Uint8Array(a));if(!c)throw new Error("Failed to extract delegation.",{cause:d});const f=await i.addSpace(c);return i.setCurrentSpace(f.did()),(await i.uploadDirectory(o)).toString()},Reward=({image:o})=>jsxRuntimeExports.jsx("div",{id:"reward",className:"flex flex-col ml-4 mt-8 md:mt-1",children:jsxRuntimeExports.jsxs("div",{className:"card rounded-sm bg-secondary/25 h-auto max-w-md mr-4 mx-auto",children:[jsxRuntimeExports.jsx("h1",{className:"text-3xl font-bold text-center my-4 mx-2",children:"Completion NFT"}),jsxRuntimeExports.jsx("img",{src:toHTTP(o),alt:"Soulbound NFT",className:"w-full h-full object-contain pb-4 px-4"})]})}),abi=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"editor",type:"address"},{indexed:!1,internalType:"uint256[]",name:"questIdList",type:"uint256[]"},{components:[{internalType:"bool",name:"paused",type:"bool"},{internalType:"bool",name:"optional",type:"bool"},{internalType:"bool",name:"skipReview",type:"bool"}],indexed:!1,internalType:"struct IQuestChain.QuestDetails[]",name:"questDetails",type:"tuple[]"}],name:"ConfiguredQuests",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint8",name:"version",type:"uint8"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"editor",type:"address"},{indexed:!1,internalType:"string",name:"details",type:"string"}],name:"QuestChainEdited",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"details",type:"string"},{indexed:!1,internalType:"string[]",name:"quests",type:"string[]"},{indexed:!1,internalType:"bool",name:"paused",type:"bool"}],name:"QuestChainInit",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"tokenURI",type:"string"}],name:"QuestChainTokenURIUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"reviewer",type:"address"},{indexed:!1,internalType:"address[]",name:"questerList",type:"address[]"},{indexed:!1,internalType:"uint256[]",name:"questIdList",type:"uint256[]"},{indexed:!1,internalType:"bool[]",name:"successList",type:"bool[]"},{indexed:!1,internalType:"string[]",name:"detailsList",type:"string[]"}],name:"QuestProofsReviewed",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"quester",type:"address"},{indexed:!1,internalType:"uint256[]",name:"questIdList",type:"uint256[]"},{indexed:!1,internalType:"string[]",name:"proofList",type:"string[]"}],name:"QuestProofsSubmitted",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"string[]",name:"detailsList",type:"string[]"}],name:"QuestsCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"editor",type:"address"},{indexed:!1,internalType:"uint256[]",name:"questIdList",type:"uint256[]"},{indexed:!1,internalType:"string[]",name:"detailsList",type:"string[]"}],name:"QuestsEdited",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"previousAdminRole",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"newAdminRole",type:"bytes32"}],name:"RoleAdminChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleGranted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleRevoked",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"limiterContract",type:"address"}],name:"SetLimiter",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{inputs:[],name:"ADMIN_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"DEFAULT_ADMIN_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"EDITOR_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"REVIEWER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"burnToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256[]",name:"_questIdList",type:"uint256[]"},{components:[{internalType:"bool",name:"paused",type:"bool"},{internalType:"bool",name:"optional",type:"bool"},{internalType:"bool",name:"skipReview",type:"bool"}],internalType:"struct IQuestChain.QuestDetails[]",name:"_questDetails",type:"tuple[]"}],name:"configureQuests",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string[]",name:"_detailsList",type:"string[]"}],name:"createQuests",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"_details",type:"string"}],name:"edit",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256[]",name:"_questIdList",type:"uint256[]"},{internalType:"string[]",name:"_detailsList",type:"string[]"}],name:"editQuests",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"}],name:"getRoleAdmin",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getTokenURI",outputs:[{internalType:"string",name:"uri",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_role",type:"bytes32"},{internalType:"address",name:"_account",type:"address"}],name:"grantRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"hasRole",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"address[]",name:"owners",type:"address[]"},{internalType:"address[]",name:"admins",type:"address[]"},{internalType:"address[]",name:"editors",type:"address[]"},{internalType:"address[]",name:"reviewers",type:"address[]"},{internalType:"string[]",name:"quests",type:"string[]"},{internalType:"bool",name:"paused",type:"bool"},{internalType:"string",name:"details",type:"string"},{internalType:"string",name:"tokenURI",type:"string"}],internalType:"struct QuestChainCommons.QuestChainInfo",name:"_info",type:"tuple"}],name:"init",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"limiterContract",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"mintToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"premium",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"questChainFactory",outputs:[{internalType:"contract IQuestChainFactory",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"questChainId",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"questChainToken",outputs:[{internalType:"contract IQuestChainToken",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"questCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"questDetails",outputs:[{internalType:"bool",name:"paused",type:"bool"},{internalType:"bool",name:"optional",type:"bool"},{internalType:"bool",name:"skipReview",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_quester",type:"address"},{internalType:"uint256",name:"_questId",type:"uint256"}],name:"questStatus",outputs:[{internalType:"enum IQuestChain.Status",name:"status",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"renounceRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address[]",name:"_questerList",type:"address[]"},{internalType:"uint256[]",name:"_questIdList",type:"uint256[]"},{internalType:"bool[]",name:"_successList",type:"bool[]"},{internalType:"string[]",name:"_detailsList",type:"string[]"}],name:"reviewProofs",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"_role",type:"bytes32"},{internalType:"address",name:"_account",type:"address"}],name:"revokeRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_limiterContract",type:"address"}],name:"setLimiter",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"_tokenURI",type:"string"}],name:"setTokenURI",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256[]",name:"_questIdList",type:"uint256[]"},{internalType:"string[]",name:"_proofList",type:"string[]"}],name:"submitProofs",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"upgrade",outputs:[],stateMutability:"nonpayable",type:"function"}],CHAIN=10,Alert=({children:o})=>jsxRuntimeExports.jsxs("div",{role:"alert",className:"alert alert-warning flex items-center mt-10",children:[jsxRuntimeExports.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6 shrink-0 stroke-current",fill:"none",viewBox:"0 0 24 24",children:jsxRuntimeExports.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),o]}),Submission=({name:o="Submission",contract:i,index:s})=>{const{address:a}=useAccount(),c=useChainId(),d=React__default.useRef(null),[f,g]=reactExports.useState(!1),[y,b]=reactExports.useState({}),$=({type:O,error:N})=>{b(L=>({...L,[O]:N}))},{data:x,writeContract:T,isPending:A}=useWriteContract(),E=useConfig();reactExports.useEffect(()=>{if(E)return watchChainId(E,{onChange(O){O!==CHAIN&&!y.chain&&$({type:"chain",error:jsxRuntimeExports.jsx("h3",{className:"flex text-center items-center justify-center",children:"Please switch to the Optimism network to continue."})})}})},[E]),reactExports.useEffect(()=>{x&&_t.success(jsxRuntimeExports.jsxs("p",{children:["Successfully submitted transaction",jsxRuntimeExports.jsxs("a",{href:`https://optimistic.etherscan.io/tx/${x}`,className:"mx-1 whitespace-nowrap text-primary hover:text-secondary",target:"_blank",children:[x.substring(0,8),"…",x.slice(-6)]}),"to the Quest Chain contract at",jsxRuntimeExports.jsxs("a",{href:`https://optimistic.etherscan.io/address/${i}`,className:"ml-1 whitespace-nowrap text-primary hover:text-secondary",target:"_blank",children:[i.substring(0,6),"…",i.slice(-4)]}),"."]}),{duration:12e3,position:"bottom-center",style:{width:"45ch"}})},[x]);const{isLoading:S,isSuccess:_}=useWaitForTransactionReceipt({hash:x});!a&&!y.account?$({type:"account",error:jsxRuntimeExports.jsxs("h3",{className:"flex text-center items-center justify-center",children:["Please",jsxRuntimeExports.jsx("div",{className:"mx-2",children:jsxRuntimeExports.jsx("w3m-button",{size:"sm"})}),"to submit a proof."]})}):a&&y.account&&$({type:"account",error:null}),c!==CHAIN&&!y.chain?$({type:"chain",error:jsxRuntimeExports.jsx("h3",{className:"flex text-center items-center justify-center",children:"Please switch to the Optimism network to continue."})}):c===CHAIN&&y.chain&&$({type:"chain",error:null});const C=Object.values(y).filter(Boolean);if(C.length>0)return C.map((O,N)=>jsxRuntimeExports.jsx(Alert,{children:O},N));const B=React__default.lazy(()=>__vitePreload(()=>import("./MarkdownEditor-BjREHNgK.js").then(O=>O.M),__vite__mapDeps([0,1,2]))),D="Submit Proof",I=S?"Confirming…":A?"Transaction Pending…":f?"Saving to IPFS…":_?"¡Done: Submitted!":D;return jsxRuntimeExports.jsxs(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("h3",{children:"Loading Submission Editor…"}),children:[jsxRuntimeExports.jsx(B,{editorRef:d,markdown:"",className:"dark-theme dark-editor content mt-10"}),jsxRuntimeExports.jsxs("button",{onClick:async()=>{var N;const O=(N=d.current)==null?void 0:N.getMarkdown();if(!O)throw new Error(`Invalid \`markdown\`: "${O}".`);g(!0);try{const L=new Blob([JSON.stringify({name:o,description:O})],{type:"application/json"}),R=await upload([new File([L],"submission.json")]);_t.success(jsxRuntimeExports.jsxs("p",{children:["Successfully uploaded your response submission to",jsxRuntimeExports.jsx("a",{href:"https://web3.storage",target:"_blank",className:"mx-1 whitespace-nowrap text-primary hover:text-secondary",children:"Web3.Storage"}),"at",jsxRuntimeExports.jsxs("a",{href:`https://w3s.link/ipfs/${R}`,target:"_blank",className:"ml-1 whitespace-nowrap text-primary hover:text-secondary",children:["ipfs://",R.substring(0,6),"…",R.slice(-4)]}),"."]}),{duration:15e3,position:"bottom-center",style:{width:"45ch"}}),T({address:i,abi,functionName:"submitProofs",args:[[s],[R]]})}catch(L){console.error({error:L}),_t.error(L.message)}finally{g(!1)}},disabled:I!==D,className:"btn btn-wide text-primary my-6",children:[jsxRuntimeExports.jsx("span",{className:clsx(I.endsWith("…")&&"loading loading-dots loading-md")}),I]})]})},questChainQueryDocument=gql` query ChainDetails($name: String!) { questChains( where: { name_starts_with_nocase: $name, name_ends_with_nocase: $name } @@ -2182,4 +2182,4 @@ zoo`.split(` } } } -`,Route=createLazyFileRoute("/book/$slug/")({component:Book});function Book(){var o;try{const{slug:i}=Route.useParams(),s=playbooks.map(({books:O})=>O).flat().find(({title:O})=>toSlug(O)===i),{data:{questChains:[a]=[]}={},error:c,isLoading:d}=useQuery$1({queryKey:[`chain-${i}`],queryFn:async()=>request$4("https://api.studio.thegraph.com/query/71457/quest-chains-optimism/version/latest",questChainQueryDocument,{name:s==null?void 0:s.title})}),f=useAccount(),g=(o=f==null?void 0:f.address)==null?void 0:o.toLowerCase(),{data:{questStatuses:y}={},error:b,isLoading:$}=useQuery$1({enabled:!!g&&!!(a!=null&&a.id),queryKey:[`statuses-${a==null?void 0:a.id}-${g}`],queryFn:async()=>request$4("https://api.studio.thegraph.com/query/71457/quest-chains-optimism/version/latest",userChainProgressQueryDocument,{chain:a.id,user:g})}),[x,T]=reactExports.useState(0),[A,E]=reactExports.useState(null),[S,_]=reactExports.useState("Unknown"),C=O=>{switch(T(O),O){case 0:{E(a.description);break}default:E(a.quests[O-1].description)}},B=O=>{var N;C(O+1),(N=document.getElementById("root"))==null||N.scrollIntoView()};if(c)throw c;if(b)throw b;if(!s)throw new Error(`No book found for: "${i}".`);if(d)return jsxRuntimeExports.jsx("h1",{children:"Loading a Quest…"});if($)return jsxRuntimeExports.jsx("h1",{children:"Loading Statuses…"});if(!a)throw new Error(`No chain found for: "${i}" = "${s.title}".`);const D=y==null?void 0:y.find(({quest:{questId:O}})=>Number(O)===x-1),{id:I}=a.createdBy;return A||C(0),S==="Unknown"&&(_(`${I.substring(0,5)}⋯${I.slice(-3)}`),createPublicClient({chain:mainnet,transport:http()}).getEnsName({address:I}).then(N=>{N&&_(N)})),console.debug({statuses:y,active:x,status:D}),jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:jsxRuntimeExports.jsxs("div",{id:"top",className:"container mx-auto py-20 px-5",children:[jsxRuntimeExports.jsxs("h2",{title:"Click to copy the creator's contract address.",onClick:()=>{_t.success("Creator’s address copied to clipboard."),navigator.clipboard.writeText(I)},className:"text-sm text-secondary mt-5 text-left pl-1",children:["Creator: ",S]}),jsxRuntimeExports.jsx("h1",{title:"Click to copy the Quest Chain contract address.",onClick:()=>{navigator.clipboard.writeText(a.id),_t.success("Quest Chain contract address copied to clipboard.")},className:"text-4xl md:text-6xl font-bold text-left mt-2",children:s.title}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-white text-left pl-1 mt-6 mb-4",children:["Last Updated:"," ",new Date(Number(a.updatedAt)*1e3).toLocaleString(void 0,{day:"numeric",month:"long",year:"numeric"})]}),jsxRuntimeExports.jsxs("main",{className:"md:flex justify-start",children:[jsxRuntimeExports.jsx(Chapters,{active:x,statuses:y,onChange:C,chapters:a.quests.map(({name:O})=>O)}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx(Content,{content:A}),x===0?jsxRuntimeExports.jsx("button",{onClick:()=>B(x),className:"shadow-md rounded-md bg-base-300 p-4 hover:bg-yellow-300/60 text-white text-center",children:"Continue"}):D&&["pass"].includes(D==null?void 0:D.status)?jsxRuntimeExports.jsx("h2",{children:"You have already successfully completed this submission."}):jsxRuntimeExports.jsx(Submission,{contract:a.address,index:x-1})]}),jsxRuntimeExports.jsx(Reward,{image:a.token.imageUrl})]})]})})}catch(i){return jsxRuntimeExports.jsxs("h1",{children:["Error: ",i.message]})}}const index_lazy=Object.freeze(Object.defineProperty({__proto__:null,Book,Route},Symbol.toStringTag,{value:"Module"}));export{EXIT as E,VFileMessage as V,stringifyPosition as a,markdownSpace as b,classifyCharacter as c,decodeNamedCharacterReference as d,markdownLineEndingOrSpace as e,factorySpace as f,start as g,cont as h,convert as i,decodeString as j,fromMarkdown as k,index_lazy as l,markdownLineEnding as m,ok$2 as o,resolveAll as r,splice as s,toString$5 as t,unicodeWhitespace as u,visit as v}; +`,Route=createLazyFileRoute("/book/$slug/")({component:Book});function Book(){var o;try{const{slug:i}=Route.useParams(),s=playbooks.map(({books:O})=>O).flat().find(({title:O})=>toSlug(O)===i),{data:{questChains:[a]=[]}={},error:c,isLoading:d}=useQuery$1({queryKey:[`chain-${i}`],queryFn:async()=>request$4("https://api.studio.thegraph.com/query/71457/quest-chains-optimism/version/latest",questChainQueryDocument,{name:s==null?void 0:s.title})}),f=useAccount(),g=(o=f==null?void 0:f.address)==null?void 0:o.toLowerCase(),{data:{questStatuses:y}={},error:b,isLoading:$}=useQuery$1({enabled:!!g&&!!(a!=null&&a.id),queryKey:[`statuses-${a==null?void 0:a.id}-${g}`],queryFn:async()=>request$4("https://api.studio.thegraph.com/query/71457/quest-chains-optimism/version/latest",userChainProgressQueryDocument,{chain:a.id,user:g})}),[x,T]=reactExports.useState(0),[A,E]=reactExports.useState(null),[S,_]=reactExports.useState("Unknown"),C=O=>{switch(T(O),O){case 0:{E(a.description);break}default:E(a.quests[O-1].description)}},B=async O=>{document.documentElement.scrollIntoView(),C(O+1)};if(c)throw c;if(b)throw b;if(!s)throw new Error(`No book found for: "${i}".`);if(d)return jsxRuntimeExports.jsx("h1",{children:"Loading a Quest…"});if($)return jsxRuntimeExports.jsx("h1",{children:"Loading Statuses…"});if(!a)throw new Error(`No chain found for: "${i}" = "${s.title}".`);const D=y==null?void 0:y.find(({quest:{questId:O}})=>Number(O)===x-1),{id:I}=a.createdBy;return A||C(0),S==="Unknown"&&(_(`${I.substring(0,5)}⋯${I.slice(-3)}`),createPublicClient({chain:mainnet,transport:http()}).getEnsName({address:I}).then(N=>{N&&_(N)})),jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:jsxRuntimeExports.jsxs("div",{id:"top",className:"container mx-auto py-20 px-5",children:[jsxRuntimeExports.jsxs("h2",{title:"Click to copy the creator's contract address.",onClick:()=>{_t.success("Creator’s address copied to clipboard."),navigator.clipboard.writeText(I)},className:"text-sm text-secondary mt-5 text-left pl-1",children:["Creator: ",S]}),jsxRuntimeExports.jsx("h1",{title:"Click to copy the Quest Chain contract address.",onClick:()=>{navigator.clipboard.writeText(a.id),_t.success("Quest Chain contract address copied to clipboard.")},className:"text-4xl md:text-6xl font-bold text-left mt-2",children:s.title}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-white text-left pl-1 mt-6 mb-4",children:["Last Updated:"," ",new Date(Number(a.updatedAt)*1e3).toLocaleString(void 0,{day:"numeric",month:"long",year:"numeric"})]}),jsxRuntimeExports.jsxs("main",{className:"md:flex justify-start",children:[jsxRuntimeExports.jsx(Chapters,{active:x,statuses:y,onChange:C,chapters:a.quests.map(({name:O})=>O)}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx(Content,{content:A}),x===0?jsxRuntimeExports.jsx("button",{onClick:()=>B(x),className:"shadow-md rounded-md bg-base-300 p-4 hover:bg-yellow-300/60 text-white text-center",children:"Continue"}):D&&["pass"].includes(D==null?void 0:D.status)?jsxRuntimeExports.jsxs("div",{role:"alert",className:"alert alert-success flex items-center mt-10",children:[jsxRuntimeExports.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6 shrink-0 stroke-current",fill:"none",viewBox:"0 0 24 24",children:jsxRuntimeExports.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),jsxRuntimeExports.jsx("h2",{className:"grow",children:"You have already successfully completed this submission."}),xB(x),className:"btn btn-primary text-fg font-bold self-end",children:["Next ",jsxRuntimeExports.jsx("span",{className:"size-2xl",children:"→"})]})]}):jsxRuntimeExports.jsx(Submission,{contract:a.address,index:x-1})]}),jsxRuntimeExports.jsx(Reward,{image:a.token.imageUrl})]})]})})}catch(i){return jsxRuntimeExports.jsxs("h1",{children:["Error: ",i.message]})}}const index_lazy=Object.freeze(Object.defineProperty({__proto__:null,Book,Route},Symbol.toStringTag,{value:"Module"}));export{EXIT as E,VFileMessage as V,stringifyPosition as a,markdownSpace as b,classifyCharacter as c,decodeNamedCharacterReference as d,markdownLineEndingOrSpace as e,factorySpace as f,start as g,cont as h,convert as i,decodeString as j,fromMarkdown as k,index_lazy as l,markdownLineEnding as m,ok$2 as o,resolveAll as r,splice as s,toString$5 as t,unicodeWhitespace as u,visit as v}; diff --git a/assets/index.lazy-BI9rjCag.js b/assets/index.lazy-C0W667Dk.js similarity index 99% rename from assets/index.lazy-BI9rjCag.js rename to assets/index.lazy-C0W667Dk.js index a0bc270..e015cfe 100644 --- a/assets/index.lazy-BI9rjCag.js +++ b/assets/index.lazy-C0W667Dk.js @@ -1 +1 @@ -import{e as L,f as N,g as ct,j as y,l as pt,m as ft,t as rt,L as mt,n as vt}from"./index-CBwDx5gl.js";var z={},K={},m={},B={};(function(o){function i(a,s,l){var u=s.slidesToShow,h=s.currentSlide;return l.length>2*u?a+2*u:h>=l.length?l.length+a:a}function t(a,s){if(s.length>2*a){for(var l={},u=s.length-2*a,h=s.length-u,c=u,d=0;d2*a?s.slice(s.length-2*a,s.length).concat(s,s.slice(0,2*a)):s.concat(s,s)}function n(a,s){return s.length>2*a?2*a:s.length}function r(a,s,l){var u,h=a.currentSlide,c=a.slidesToShow,d=a.itemWidth,p=a.totalItems,f=0,v=0,b=h===0,C=s.length-(s.length-2*c);return s.length2*c?((u=h>=C+s.length)&&(v=-d*(f=h-s.length)),b&&(v=-d*(f=C+(s.length-2*c)))):((u=h>=2*s.length)&&(v=-d*(f=h-s.length)),b&&(v=l.showDots?-d*(f=s.length):-d*(f=p/3))),{isReachingTheEnd:u,isReachingTheStart:b,nextSlide:f,nextPosition:v}}Object.defineProperty(o,"__esModule",{value:!0}),o.getOriginalCounterPart=i,o.getOriginalIndexLookupTableByClones=t,o.getClones=e,o.getInitialSlideInInfiniteMode=n,o.checkClonesPosition=r})(B);var O={};Object.defineProperty(O,"__esModule",{value:!0});function gt(o,i,t,e){var n=0,r=e||t;return i&&r&&(n=o[r].partialVisibilityGutter||o[r].paritialVisibilityGutter),n}function St(o,i){var t;return i[o]&&(t=(100/i[o].items).toFixed(1)),t}function yt(o,i,t){return Math.round(t/(i+(o.centerMode?1:0)))}O.getPartialVisibilityGutter=gt,O.getWidthFromDeviceType=St,O.getItemClientSideWidth=yt;var T={};Object.defineProperty(T,"__esModule",{value:!0});var Y=O;function q(o){var i=o.slidesToShow;return o.totalItems=v&&window.innerWidth<=f&&(l=p)}),l}T.notEnoughChildren=q,T.getInitialState=Tt,T.getIfSlideIsVisbile=wt,T.getTransformForCenterMode=st,T.isInLeftEnd=bt,T.isInRightEnd=at,T.getTransformForPartialVsibile=lt,T.parsePosition=ut,T.getTransform=Ct,T.getSlidesToSlide=It;var J={};Object.defineProperty(J,"__esModule",{value:!0});var Mt=function(o,i,t){var e;return function(){var n=arguments;e||(o.apply(this,n),e=!0,typeof t=="function"&&t(!0),setTimeout(function(){e=!1,typeof t=="function"&&t(!1)},i))}};J.default=Mt;var ht={};(function(o){function i(t,e){var n=e.partialVisbile,r=e.partialVisible,a=e.centerMode,s=e.ssr,l=e.responsive;if((n||r)&&a)throw new Error("center mode can not be used at the same time with partialVisible");if(!l)throw s?new Error("ssr mode need to be used in conjunction with responsive prop"):new Error("Responsive prop is needed for deciding the amount of items to show on the screen");if(l&&typeof l!="object")throw new Error("responsive prop must be an object")}Object.defineProperty(o,"__esModule",{value:!0}),o.default=i})(ht);var Q={};Object.defineProperty(Q,"__esModule",{value:!0});var xt=T;function Pt(o,i,t){t===void 0&&(t=0);var e,n,r=o.slidesToShow,a=o.currentSlide,s=o.itemWidth,l=o.totalItems,u=xt.getSlidesToSlide(o,i),h=a+1+t+r+(0Math.abs(s)))return;var l=S.populateSlidesOnMouseTouchMove(this.state,this.props,this.initialX,this.lastX,n,this.transformPlaceHolder),u=l.direction,h=l.nextPosition,c=l.canContinue;u&&(this.direction=u,c&&h!==void 0&&this.setTransformDirectly(h)),this.lastX=n}}},i.prototype.handleOut=function(t){this.props.autoPlay&&!this.autoPlay&&(this.autoPlay=setInterval(this.next,this.props.autoPlaySpeed));var e=t.type==="touchend"&&!this.props.swipeable,n=(t.type==="mouseleave"||t.type==="mouseup")&&!this.props.draggable;if(!e&&!n&&this.onMove){if(this.setAnimationDirectly(!0),this.direction==="right")if(this.initialX-this.lastX>=this.props.minimumTouchDrag){var r=Math.round((this.initialX-this.lastX)/this.state.itemWidth);this.next(r)}else this.correctItemsPosition(this.state.itemWidth,!0,!0);this.direction==="left"&&(this.lastX-this.initialX>this.props.minimumTouchDrag?(r=Math.round((this.lastX-this.initialX)/this.state.itemWidth),this.previous(r)):this.correctItemsPosition(this.state.itemWidth,!0,!0)),this.resetMoveStatus()}},i.prototype.isInViewport=function(t){var e=t.getBoundingClientRect(),n=e.top,r=n===void 0?0:n,a=e.left,s=a===void 0?0:a,l=e.bottom,u=l===void 0?0:l,h=e.right,c=h===void 0?0:h;return 0<=r&&0<=s&&u<=(window.innerHeight||document.documentElement.clientHeight)&&c<=(window.innerWidth||document.documentElement.clientWidth)},i.prototype.isChildOfCarousel=function(t){return!!(t instanceof Element&&this.listRef&&this.listRef.current)&&this.listRef.current.contains(t)},i.prototype.onKeyUp=function(t){var e=t.target;switch(t.keyCode){case 37:if(this.isChildOfCarousel(e))return this.previous();break;case 39:if(this.isChildOfCarousel(e))return this.next();break;case 9:if(this.isChildOfCarousel(e)&&e instanceof HTMLInputElement&&this.isInViewport(e))return this.next()}},i.prototype.handleEnter=function(t){E.isMouseMoveEvent(t)&&this.autoPlay&&this.props.autoPlay&&this.props.pauseOnHover&&(clearInterval(this.autoPlay),this.autoPlay=void 0)},i.prototype.goToSlide=function(t,e,n){var r=this;if(n===void 0&&(n=!0),!this.isInThrottle){var a=this.state.itemWidth,s=this.props,l=s.afterChange,u=s.beforeChange,h=this.state.currentSlide;typeof u!="function"||e&&(typeof e!="object"||e.skipBeforeChange)||u(t,this.getState()),this.isAnimationAllowed=n,this.props.shouldResetAutoplay&&this.resetAutoplayInterval(),this.setState({currentSlide:t,transform:-a*t},function(){r.props.infinite&&r.correctClonesPosition({domLoaded:!0}),typeof l!="function"||e&&(typeof e!="object"||e.skipAfterChange)||(i.afterChangeTimeout3=setTimeout(function(){l(h,r.getState())},r.props.transitionDuration||P))})}},i.prototype.getState=function(){return this.state},i.prototype.renderLeftArrow=function(t){var e=this,n=this.props,r=n.customLeftArrow,a=n.rtl;return w.createElement(ot.LeftArrow,{customLeftArrow:r,getState:function(){return e.getState()},previous:this.previous,disabled:t,rtl:a})},i.prototype.renderRightArrow=function(t){var e=this,n=this.props,r=n.customRightArrow,a=n.rtl;return w.createElement(ot.RightArrow,{customRightArrow:r,getState:function(){return e.getState()},next:this.next,disabled:t,rtl:a})},i.prototype.renderButtonGroups=function(){var t=this,e=this.props.customButtonGroup;return e?w.cloneElement(e,{previous:function(){return t.previous()},next:function(){return t.next()},goToSlide:function(n,r){return t.goToSlide(n,r)},carouselState:this.getState()}):null},i.prototype.renderDotsList=function(){var t=this;return w.createElement(Qt.default,{state:this.state,props:this.props,goToSlide:this.goToSlide,getState:function(){return t.getState()}})},i.prototype.renderCarouselItems=function(){var t=[];if(this.props.infinite){var e=w.Children.toArray(this.props.children);t=S.getClones(this.state.slidesToShow,e)}return w.createElement(Zt.default,{clones:t,goToSlide:this.goToSlide,state:this.state,notEnoughChildren:S.notEnoughChildren(this.state),props:this.props})},i.prototype.render=function(){var t=this.props,e=t.deviceType,n=t.arrows,r=t.renderArrowsWhenDisabled,a=t.removeArrowOnDeviceType,s=t.infinite,l=t.containerClass,u=t.sliderClass,h=t.customTransition,c=t.additionalTransfrom,d=t.renderDotsOutside,p=t.renderButtonGroupOutside,f=t.className,v=t.rtl,b=S.getInitialState(this.state,this.props),C=b.shouldRenderOnSSR,I=b.shouldRenderAtAll,g=S.isInLeftEnd(this.state),x=S.isInRightEnd(this.state),M=n&&!(a&&(e&&-1y.jsxs("header",{className:"justify-start mb-4",children:[y.jsx("h1",{className:"text-2xl font-medium text-primary justify-left text-left text-shadow-md",children:o}),y.jsx("h2",{className:"text-xl font-medium text-accent justify-left text-left text-shadow-md",children:i})]}),le=pt("/")({component:se}),ne={superLargeDesktop:{breakpoint:{max:4e3,min:3e3},items:5},desktop:{breakpoint:{max:3e3,min:1024},items:4},tablet:{breakpoint:{max:1024,min:464},items:2},mobile:{breakpoint:{max:464,min:0},items:1}},re=({id:o,title:i,description:t,items:e})=>y.jsxs("div",{id:o,className:"container py-4 mt-30 gap-4 scroll-mt-20",children:[y.jsx(oe,{title:i,description:t}),y.jsx(ie,{responsive:ne,className:"gap-4 md:gap-6 lg:gap-8 w-full",children:e.map((n,r)=>y.jsx("div",{id:`${o}-${rt(n.title)}`,children:y.jsx(vt,{...n})},r))})]});function se(){return y.jsxs(y.Fragment,{children:[y.jsx("div",{id:"top",className:"scroll-mt-32",children:y.jsx("h2",{className:"text-accent font-light text-3xl mb-2 pt-6",children:"A de-store of knowledge. Onboard forward."})}),y.jsx("div",{className:"container p-4 mt-30 gap-4",children:ft.map((o,i)=>y.jsx(re,{id:rt(o.title),title:o.title,description:o.description,items:o.books},i))}),y.jsx("div",{className:"fixed bottom-0 right-0 p-4",children:y.jsx(mt,{to:"/#top",className:"btn btn-ghost text-xl",children:y.jsxs("div",{className:"flex flex-col justify-center items-center",children:[y.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:y.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M5 10l7-7 7 7"})}),y.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:y.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M5 10l7-7 7 7"})})]})})})]})}export{se as App,le as Route,se as default}; +import{e as L,f as N,g as ct,j as y,l as pt,m as ft,t as rt,L as mt,n as vt}from"./index-4Hagg-7l.js";var z={},K={},m={},B={};(function(o){function i(a,s,l){var u=s.slidesToShow,h=s.currentSlide;return l.length>2*u?a+2*u:h>=l.length?l.length+a:a}function t(a,s){if(s.length>2*a){for(var l={},u=s.length-2*a,h=s.length-u,c=u,d=0;d2*a?s.slice(s.length-2*a,s.length).concat(s,s.slice(0,2*a)):s.concat(s,s)}function n(a,s){return s.length>2*a?2*a:s.length}function r(a,s,l){var u,h=a.currentSlide,c=a.slidesToShow,d=a.itemWidth,p=a.totalItems,f=0,v=0,b=h===0,C=s.length-(s.length-2*c);return s.length2*c?((u=h>=C+s.length)&&(v=-d*(f=h-s.length)),b&&(v=-d*(f=C+(s.length-2*c)))):((u=h>=2*s.length)&&(v=-d*(f=h-s.length)),b&&(v=l.showDots?-d*(f=s.length):-d*(f=p/3))),{isReachingTheEnd:u,isReachingTheStart:b,nextSlide:f,nextPosition:v}}Object.defineProperty(o,"__esModule",{value:!0}),o.getOriginalCounterPart=i,o.getOriginalIndexLookupTableByClones=t,o.getClones=e,o.getInitialSlideInInfiniteMode=n,o.checkClonesPosition=r})(B);var O={};Object.defineProperty(O,"__esModule",{value:!0});function gt(o,i,t,e){var n=0,r=e||t;return i&&r&&(n=o[r].partialVisibilityGutter||o[r].paritialVisibilityGutter),n}function St(o,i){var t;return i[o]&&(t=(100/i[o].items).toFixed(1)),t}function yt(o,i,t){return Math.round(t/(i+(o.centerMode?1:0)))}O.getPartialVisibilityGutter=gt,O.getWidthFromDeviceType=St,O.getItemClientSideWidth=yt;var T={};Object.defineProperty(T,"__esModule",{value:!0});var Y=O;function q(o){var i=o.slidesToShow;return o.totalItems=v&&window.innerWidth<=f&&(l=p)}),l}T.notEnoughChildren=q,T.getInitialState=Tt,T.getIfSlideIsVisbile=wt,T.getTransformForCenterMode=st,T.isInLeftEnd=bt,T.isInRightEnd=at,T.getTransformForPartialVsibile=lt,T.parsePosition=ut,T.getTransform=Ct,T.getSlidesToSlide=It;var J={};Object.defineProperty(J,"__esModule",{value:!0});var Mt=function(o,i,t){var e;return function(){var n=arguments;e||(o.apply(this,n),e=!0,typeof t=="function"&&t(!0),setTimeout(function(){e=!1,typeof t=="function"&&t(!1)},i))}};J.default=Mt;var ht={};(function(o){function i(t,e){var n=e.partialVisbile,r=e.partialVisible,a=e.centerMode,s=e.ssr,l=e.responsive;if((n||r)&&a)throw new Error("center mode can not be used at the same time with partialVisible");if(!l)throw s?new Error("ssr mode need to be used in conjunction with responsive prop"):new Error("Responsive prop is needed for deciding the amount of items to show on the screen");if(l&&typeof l!="object")throw new Error("responsive prop must be an object")}Object.defineProperty(o,"__esModule",{value:!0}),o.default=i})(ht);var Q={};Object.defineProperty(Q,"__esModule",{value:!0});var xt=T;function Pt(o,i,t){t===void 0&&(t=0);var e,n,r=o.slidesToShow,a=o.currentSlide,s=o.itemWidth,l=o.totalItems,u=xt.getSlidesToSlide(o,i),h=a+1+t+r+(0Math.abs(s)))return;var l=S.populateSlidesOnMouseTouchMove(this.state,this.props,this.initialX,this.lastX,n,this.transformPlaceHolder),u=l.direction,h=l.nextPosition,c=l.canContinue;u&&(this.direction=u,c&&h!==void 0&&this.setTransformDirectly(h)),this.lastX=n}}},i.prototype.handleOut=function(t){this.props.autoPlay&&!this.autoPlay&&(this.autoPlay=setInterval(this.next,this.props.autoPlaySpeed));var e=t.type==="touchend"&&!this.props.swipeable,n=(t.type==="mouseleave"||t.type==="mouseup")&&!this.props.draggable;if(!e&&!n&&this.onMove){if(this.setAnimationDirectly(!0),this.direction==="right")if(this.initialX-this.lastX>=this.props.minimumTouchDrag){var r=Math.round((this.initialX-this.lastX)/this.state.itemWidth);this.next(r)}else this.correctItemsPosition(this.state.itemWidth,!0,!0);this.direction==="left"&&(this.lastX-this.initialX>this.props.minimumTouchDrag?(r=Math.round((this.lastX-this.initialX)/this.state.itemWidth),this.previous(r)):this.correctItemsPosition(this.state.itemWidth,!0,!0)),this.resetMoveStatus()}},i.prototype.isInViewport=function(t){var e=t.getBoundingClientRect(),n=e.top,r=n===void 0?0:n,a=e.left,s=a===void 0?0:a,l=e.bottom,u=l===void 0?0:l,h=e.right,c=h===void 0?0:h;return 0<=r&&0<=s&&u<=(window.innerHeight||document.documentElement.clientHeight)&&c<=(window.innerWidth||document.documentElement.clientWidth)},i.prototype.isChildOfCarousel=function(t){return!!(t instanceof Element&&this.listRef&&this.listRef.current)&&this.listRef.current.contains(t)},i.prototype.onKeyUp=function(t){var e=t.target;switch(t.keyCode){case 37:if(this.isChildOfCarousel(e))return this.previous();break;case 39:if(this.isChildOfCarousel(e))return this.next();break;case 9:if(this.isChildOfCarousel(e)&&e instanceof HTMLInputElement&&this.isInViewport(e))return this.next()}},i.prototype.handleEnter=function(t){E.isMouseMoveEvent(t)&&this.autoPlay&&this.props.autoPlay&&this.props.pauseOnHover&&(clearInterval(this.autoPlay),this.autoPlay=void 0)},i.prototype.goToSlide=function(t,e,n){var r=this;if(n===void 0&&(n=!0),!this.isInThrottle){var a=this.state.itemWidth,s=this.props,l=s.afterChange,u=s.beforeChange,h=this.state.currentSlide;typeof u!="function"||e&&(typeof e!="object"||e.skipBeforeChange)||u(t,this.getState()),this.isAnimationAllowed=n,this.props.shouldResetAutoplay&&this.resetAutoplayInterval(),this.setState({currentSlide:t,transform:-a*t},function(){r.props.infinite&&r.correctClonesPosition({domLoaded:!0}),typeof l!="function"||e&&(typeof e!="object"||e.skipAfterChange)||(i.afterChangeTimeout3=setTimeout(function(){l(h,r.getState())},r.props.transitionDuration||P))})}},i.prototype.getState=function(){return this.state},i.prototype.renderLeftArrow=function(t){var e=this,n=this.props,r=n.customLeftArrow,a=n.rtl;return w.createElement(ot.LeftArrow,{customLeftArrow:r,getState:function(){return e.getState()},previous:this.previous,disabled:t,rtl:a})},i.prototype.renderRightArrow=function(t){var e=this,n=this.props,r=n.customRightArrow,a=n.rtl;return w.createElement(ot.RightArrow,{customRightArrow:r,getState:function(){return e.getState()},next:this.next,disabled:t,rtl:a})},i.prototype.renderButtonGroups=function(){var t=this,e=this.props.customButtonGroup;return e?w.cloneElement(e,{previous:function(){return t.previous()},next:function(){return t.next()},goToSlide:function(n,r){return t.goToSlide(n,r)},carouselState:this.getState()}):null},i.prototype.renderDotsList=function(){var t=this;return w.createElement(Qt.default,{state:this.state,props:this.props,goToSlide:this.goToSlide,getState:function(){return t.getState()}})},i.prototype.renderCarouselItems=function(){var t=[];if(this.props.infinite){var e=w.Children.toArray(this.props.children);t=S.getClones(this.state.slidesToShow,e)}return w.createElement(Zt.default,{clones:t,goToSlide:this.goToSlide,state:this.state,notEnoughChildren:S.notEnoughChildren(this.state),props:this.props})},i.prototype.render=function(){var t=this.props,e=t.deviceType,n=t.arrows,r=t.renderArrowsWhenDisabled,a=t.removeArrowOnDeviceType,s=t.infinite,l=t.containerClass,u=t.sliderClass,h=t.customTransition,c=t.additionalTransfrom,d=t.renderDotsOutside,p=t.renderButtonGroupOutside,f=t.className,v=t.rtl,b=S.getInitialState(this.state,this.props),C=b.shouldRenderOnSSR,I=b.shouldRenderAtAll,g=S.isInLeftEnd(this.state),x=S.isInRightEnd(this.state),M=n&&!(a&&(e&&-1y.jsxs("header",{className:"justify-start mb-4",children:[y.jsx("h1",{className:"text-2xl font-medium text-primary justify-left text-left text-shadow-md",children:o}),y.jsx("h2",{className:"text-xl font-medium text-accent justify-left text-left text-shadow-md",children:i})]}),le=pt("/")({component:se}),ne={superLargeDesktop:{breakpoint:{max:4e3,min:3e3},items:5},desktop:{breakpoint:{max:3e3,min:1024},items:4},tablet:{breakpoint:{max:1024,min:464},items:2},mobile:{breakpoint:{max:464,min:0},items:1}},re=({id:o,title:i,description:t,items:e})=>y.jsxs("div",{id:o,className:"container py-4 mt-30 gap-4 scroll-mt-20",children:[y.jsx(oe,{title:i,description:t}),y.jsx(ie,{responsive:ne,className:"gap-4 md:gap-6 lg:gap-8 w-full",children:e.map((n,r)=>y.jsx("div",{id:`${o}-${rt(n.title)}`,children:y.jsx(vt,{...n})},r))})]});function se(){return y.jsxs(y.Fragment,{children:[y.jsx("div",{id:"top",className:"scroll-mt-32",children:y.jsx("h2",{className:"text-accent font-light text-3xl mb-2 pt-6",children:"A de-store of knowledge. Onboard forward."})}),y.jsx("div",{className:"container p-4 mt-30 gap-4",children:ft.map((o,i)=>y.jsx(re,{id:rt(o.title),title:o.title,description:o.description,items:o.books},i))}),y.jsx("div",{className:"fixed bottom-0 right-0 p-4",children:y.jsx(mt,{to:"/#top",className:"btn btn-ghost text-xl",children:y.jsxs("div",{className:"flex flex-col justify-center items-center",children:[y.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:y.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M5 10l7-7 7 7"})}),y.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:y.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M5 10l7-7 7 7"})})]})})})]})}export{se as App,le as Route,se as default}; diff --git a/assets/isAddressEqual-D9iYaUN7.js b/assets/isAddressEqual-DlPIwSPc.js similarity index 70% rename from assets/isAddressEqual-D9iYaUN7.js rename to assets/isAddressEqual-DlPIwSPc.js index f1d2bd1..c96a9e2 100644 --- a/assets/isAddressEqual-D9iYaUN7.js +++ b/assets/isAddressEqual-DlPIwSPc.js @@ -1 +1 @@ -import{ad as e,ae as d}from"./index-CBwDx5gl.js";function a(s,r){if(!e(s,{strict:!1}))throw new d({address:s});if(!e(r,{strict:!1}))throw new d({address:r});return s.toLowerCase()===r.toLowerCase()}export{a as i}; +import{ad as e,ae as d}from"./index-4Hagg-7l.js";function a(s,r){if(!e(s,{strict:!1}))throw new d({address:s});if(!e(r,{strict:!1}))throw new d({address:r});return s.toLowerCase()===r.toLowerCase()}export{a as i}; diff --git a/assets/secp256k1-B5jMENlr.js b/assets/secp256k1-CibHJEZu.js similarity index 99% rename from assets/secp256k1-B5jMENlr.js rename to assets/secp256k1-CibHJEZu.js index e3a2bef..84120ae 100644 --- a/assets/secp256k1-B5jMENlr.js +++ b/assets/secp256k1-CibHJEZu.js @@ -1 +1 @@ -import{cF as Ft,cG as Gt,cH as Wt,cI as qt,cJ as Xt,cK as Dt,cL as Qt,b5 as Jt}from"./index-CBwDx5gl.js";/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ut=BigInt(0),ht=BigInt(1),te=BigInt(2);function nt(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function lt(e){if(!nt(e))throw new Error("Uint8Array expected")}const ee=Array.from({length:256},(e,n)=>n.toString(16).padStart(2,"0"));function st(e){lt(e);let n="";for(let t=0;t=P._0&&e<=P._9)return e-P._0;if(e>=P._A&&e<=P._F)return e-(P._A-10);if(e>=P._a&&e<=P._f)return e-(P._a-10)}function ct(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);const n=e.length,t=n/2;if(n%2)throw new Error("padded hex string expected, got unpadded hex of length "+n);const r=new Uint8Array(t);for(let s=0,i=0;sUt;e>>=ht,n+=1);return n}function se(e,n){return e>>BigInt(n)&ht}function ce(e,n,t){return e|(t?ht:Ut)<(te<new Uint8Array(e),_t=e=>Uint8Array.from(e);function zt(e,n,t){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof n!="number"||n<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let r=wt(e),s=wt(e),i=0;const l=()=>{r.fill(1),s.fill(0),i=0},c=(...w)=>t(s,r,...w),o=(w=wt())=>{s=c(_t([0]),w),r=c(),w.length!==0&&(s=c(_t([1]),w),r=c())},a=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let w=0;const O=[];for(;w{l(),o(w);let T;for(;!(T=O(a()));)o();return l(),T}}const fe={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||nt(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,n)=>n.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function dt(e,n,t={}){const r=(s,i,l)=>{const c=fe[i];if(typeof c!="function")throw new Error(`Invalid validator "${i}", expected function`);const o=e[s];if(!(l&&o===void 0)&&!c(o,e))throw new Error(`Invalid param ${String(s)}=${o} (${typeof o}), expected ${i}`)};for(const[s,i]of Object.entries(n))r(s,i,!1);for(const[s,i]of Object.entries(t))r(s,i,!0);return e}const ae=Object.freeze(Object.defineProperty({__proto__:null,abytes:lt,bitGet:se,bitLen:ie,bitMask:St,bitSet:ce,bytesToHex:st,bytesToNumberBE:et,bytesToNumberLE:xt,concatBytes:ut,createHmacDrbg:zt,ensureBytes:M,equalBytes:re,hexToBytes:ct,hexToNumber:Bt,isBytes:nt,numberToBytesBE:ft,numberToBytesLE:vt,numberToHexUnpadded:Rt,numberToVarBytesBE:ne,utf8ToBytes:oe,validateObject:dt},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const L=BigInt(0),$=BigInt(1),J=BigInt(2),ue=BigInt(3),yt=BigInt(4),Tt=BigInt(5),$t=BigInt(8);BigInt(9);BigInt(16);function R(e,n){const t=e%n;return t>=L?t:n+t}function le(e,n,t){if(t<=L||n 0");if(t===$)return L;let r=$;for(;n>L;)n&$&&(r=r*e%t),e=e*e%t,n>>=$;return r}function V(e,n,t){let r=e;for(;n-- >L;)r*=r,r%=t;return r}function mt(e,n){if(e===L||n<=L)throw new Error(`invert: expected positive integers, got n=${e} mod=${n}`);let t=R(e,n),r=n,s=L,i=$;for(;t!==L;){const c=r/t,o=r%t,a=s-i*c;r=t,t=o,s=i,i=a}if(r!==$)throw new Error("invert: does not exist");return R(s,n)}function de(e){const n=(e-$)/J;let t,r,s;for(t=e-$,r=0;t%J===L;t/=J,r++);for(s=J;s(r[s]="function",r),n);return dt(e,t)}function pe(e,n,t){if(t 0");if(t===L)return e.ONE;if(t===$)return n;let r=e.ONE,s=n;for(;t>L;)t&$&&(r=e.mul(r,s)),s=e.sqr(s),t>>=$;return r}function ye(e,n){const t=new Array(n.length),r=n.reduce((i,l,c)=>e.is0(l)?i:(t[c]=i,e.mul(i,l)),e.ONE),s=e.inv(r);return n.reduceRight((i,l,c)=>e.is0(l)?i:(t[c]=e.mul(i,t[c]),e.mul(i,l)),s),t}function Ct(e,n){const t=n!==void 0?n:e.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function me(e,n,t=!1,r={}){if(e<=L)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:i}=Ct(e,n);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const l=he(e),c=Object.freeze({ORDER:e,BITS:s,BYTES:i,MASK:St(s),ZERO:L,ONE:$,create:o=>R(o,e),isValid:o=>{if(typeof o!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof o}`);return L<=o&&oo===L,isOdd:o=>(o&$)===$,neg:o=>R(-o,e),eql:(o,a)=>o===a,sqr:o=>R(o*o,e),add:(o,a)=>R(o+a,e),sub:(o,a)=>R(o-a,e),mul:(o,a)=>R(o*a,e),pow:(o,a)=>pe(c,o,a),div:(o,a)=>R(o*mt(a,e),e),sqrN:o=>o*o,addN:(o,a)=>o+a,subN:(o,a)=>o-a,mulN:(o,a)=>o*a,inv:o=>mt(o,e),sqrt:r.sqrt||(o=>l(c,o)),invertBatch:o=>ye(c,o),cmov:(o,a,y)=>y?a:o,toBytes:o=>t?vt(o,i):ft(o,i),fromBytes:o=>{if(o.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${o.length}`);return t?xt(o):et(o)}});return Object.freeze(c)}function kt(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const n=e.toString(2).length;return Math.ceil(n/8)}function Vt(e){const n=kt(e);return n+Math.ceil(n/2)}function be(e,n,t=!1){const r=e.length,s=kt(n),i=Vt(n);if(r<16||r1024)throw new Error(`expected ${i}-1024 bytes of input, got ${r}`);const l=t?et(e):xt(e),c=R(l,n-$)+$;return t?vt(c,s):ft(c,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ee=BigInt(0),pt=BigInt(1);function Be(e,n){const t=(s,i)=>{const l=i.negate();return s?l:i},r=s=>{const i=Math.ceil(n/s)+1,l=2**(s-1);return{windows:i,windowSize:l}};return{constTimeNegate:t,unsafeLadder(s,i){let l=e.ZERO,c=s;for(;i>Ee;)i&pt&&(l=l.add(c)),c=c.double(),i>>=pt;return l},precomputeWindow(s,i){const{windows:l,windowSize:c}=r(i),o=[];let a=s,y=a;for(let w=0;w>=T,d>o&&(d-=O,l+=pt);const h=f,b=f+Math.abs(d)-1,B=m%2!==0,I=d<0;d===0?y=y.add(t(B,i[h])):a=a.add(t(I,i[b]))}return{p:a,f:y}},wNAFCached(s,i,l,c){const o=s._WINDOW_SIZE||1;let a=i.get(s);return a||(a=this.precomputeWindow(s,o),o!==1&&i.set(s,c(a))),this.wNAF(o,a,l)}}}function jt(e){return we(e.Fp),dt(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ct(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function xe(e){const n=jt(e);dt(n,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:r,a:s}=n;if(t){if(!r.eql(s,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...n})}const{bytesToNumberBE:ve,hexToBytes:Se}=ae,tt={Err:class extends Error{constructor(n=""){super(n)}},_parseInt(e){const{Err:n}=tt;if(e.length<2||e[0]!==2)throw new n("Invalid signature integer tag");const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw new n("Invalid signature integer: wrong length");if(r[0]&128)throw new n("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new n("Invalid signature integer: unnecessary leading zero");return{d:ve(r),l:e.subarray(t+2)}},toSig(e){const{Err:n}=tt,t=typeof e=="string"?Se(e):e;lt(t);let r=t.length;if(r<2||t[0]!=48)throw new n("Invalid signature tag");if(t[1]!==r-2)throw new n("Invalid signature: incorrect length");const{d:s,l:i}=tt._parseInt(t.subarray(2)),{d:l,l:c}=tt._parseInt(i);if(c.length)throw new n("Invalid signature: left bytes after parsing");return{r:s,s:l}},hexFromSig(e){const n=a=>Number.parseInt(a[0],16)&8?"00"+a:a,t=a=>{const y=a.toString(16);return y.length&1?`0${y}`:y},r=n(t(e.s)),s=n(t(e.r)),i=r.length/2,l=s.length/2,c=t(i),o=t(l);return`30${t(l+i+4)}02${o}${s}02${c}${r}`}},F=BigInt(0),j=BigInt(1);BigInt(2);const Ht=BigInt(3);BigInt(4);function Ie(e){const n=xe(e),{Fp:t}=n,r=n.toBytes||((m,f,d)=>{const h=f.toAffine();return ut(Uint8Array.from([4]),t.toBytes(h.x),t.toBytes(h.y))}),s=n.fromBytes||(m=>{const f=m.subarray(1),d=t.fromBytes(f.subarray(0,t.BYTES)),h=t.fromBytes(f.subarray(t.BYTES,2*t.BYTES));return{x:d,y:h}});function i(m){const{a:f,b:d}=n,h=t.sqr(m),b=t.mul(h,m);return t.add(t.add(b,t.mul(m,f)),d)}if(!t.eql(t.sqr(n.Gy),i(n.Gx)))throw new Error("bad generator point: equation left != right");function l(m){return typeof m=="bigint"&&Ft.eql(B,t.ZERO);return b(d)&&b(h)?w.ZERO:new w(d,h,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(f){const d=t.invertBatch(f.map(h=>h.pz));return f.map((h,b)=>h.toAffine(d[b])).map(w.fromAffine)}static fromHex(f){const d=w.fromAffine(s(M("pointHex",f)));return d.assertValidity(),d}static fromPrivateKey(f){return w.BASE.multiply(o(f))}_setWindowSize(f){this._WINDOW_SIZE=f,a.delete(this)}assertValidity(){if(this.is0()){if(n.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:f,y:d}=this.toAffine();if(!t.isValid(f)||!t.isValid(d))throw new Error("bad point: x or y not FE");const h=t.sqr(d),b=i(f);if(!t.eql(h,b))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:f}=this.toAffine();if(t.isOdd)return!t.isOdd(f);throw new Error("Field doesn't support isOdd")}equals(f){y(f);const{px:d,py:h,pz:b}=this,{px:B,py:I,pz:S}=f,p=t.eql(t.mul(d,S),t.mul(B,b)),E=t.eql(t.mul(h,S),t.mul(I,b));return p&&E}negate(){return new w(this.px,t.neg(this.py),this.pz)}double(){const{a:f,b:d}=n,h=t.mul(d,Ht),{px:b,py:B,pz:I}=this;let S=t.ZERO,p=t.ZERO,E=t.ZERO,v=t.mul(b,b),k=t.mul(B,B),_=t.mul(I,I),A=t.mul(b,B);return A=t.add(A,A),E=t.mul(b,I),E=t.add(E,E),S=t.mul(f,E),p=t.mul(h,_),p=t.add(S,p),S=t.sub(k,p),p=t.add(k,p),p=t.mul(S,p),S=t.mul(A,S),E=t.mul(h,E),_=t.mul(f,_),A=t.sub(v,_),A=t.mul(f,A),A=t.add(A,E),E=t.add(v,v),v=t.add(E,v),v=t.add(v,_),v=t.mul(v,A),p=t.add(p,v),_=t.mul(B,I),_=t.add(_,_),v=t.mul(_,A),S=t.sub(S,v),E=t.mul(_,k),E=t.add(E,E),E=t.add(E,E),new w(S,p,E)}add(f){y(f);const{px:d,py:h,pz:b}=this,{px:B,py:I,pz:S}=f;let p=t.ZERO,E=t.ZERO,v=t.ZERO;const k=n.a,_=t.mul(n.b,Ht);let A=t.mul(d,B),z=t.mul(h,I),C=t.mul(b,S),G=t.add(d,h),u=t.add(B,I);G=t.mul(G,u),u=t.add(A,z),G=t.sub(G,u),u=t.add(d,b);let g=t.add(B,S);return u=t.mul(u,g),g=t.add(A,C),u=t.sub(u,g),g=t.add(h,b),p=t.add(I,S),g=t.mul(g,p),p=t.add(z,C),g=t.sub(g,p),v=t.mul(k,u),p=t.mul(_,C),v=t.add(p,v),p=t.sub(z,v),v=t.add(z,v),E=t.mul(p,v),z=t.add(A,A),z=t.add(z,A),C=t.mul(k,C),u=t.mul(_,u),z=t.add(z,C),C=t.sub(A,C),C=t.mul(k,C),u=t.add(u,C),A=t.mul(z,u),E=t.add(E,A),A=t.mul(g,u),p=t.mul(G,p),p=t.sub(p,A),A=t.mul(G,z),v=t.mul(g,v),v=t.add(v,A),new w(p,E,v)}subtract(f){return this.add(f.negate())}is0(){return this.equals(w.ZERO)}wNAF(f){return T.wNAFCached(this,a,f,d=>{const h=t.invertBatch(d.map(b=>b.pz));return d.map((b,B)=>b.toAffine(h[B])).map(w.fromAffine)})}multiplyUnsafe(f){const d=w.ZERO;if(f===F)return d;if(c(f),f===j)return this;const{endo:h}=n;if(!h)return T.unsafeLadder(this,f);let{k1neg:b,k1:B,k2neg:I,k2:S}=h.splitScalar(f),p=d,E=d,v=this;for(;B>F||S>F;)B&j&&(p=p.add(v)),S&j&&(E=E.add(v)),v=v.double(),B>>=j,S>>=j;return b&&(p=p.negate()),I&&(E=E.negate()),E=new w(t.mul(E.px,h.beta),E.py,E.pz),p.add(E)}multiply(f){c(f);let d=f,h,b;const{endo:B}=n;if(B){const{k1neg:I,k1:S,k2neg:p,k2:E}=B.splitScalar(d);let{p:v,f:k}=this.wNAF(S),{p:_,f:A}=this.wNAF(E);v=T.constTimeNegate(I,v),_=T.constTimeNegate(p,_),_=new w(t.mul(_.px,B.beta),_.py,_.pz),h=v.add(_),b=k.add(A)}else{const{p:I,f:S}=this.wNAF(d);h=I,b=S}return w.normalizeZ([h,b])[0]}multiplyAndAddUnsafe(f,d,h){const b=w.BASE,B=(S,p)=>p===F||p===j||!S.equals(b)?S.multiplyUnsafe(p):S.multiply(p),I=B(this,d).add(B(f,h));return I.is0()?void 0:I}toAffine(f){const{px:d,py:h,pz:b}=this,B=this.is0();f==null&&(f=B?t.ONE:t.inv(b));const I=t.mul(d,f),S=t.mul(h,f),p=t.mul(b,f);if(B)return{x:t.ZERO,y:t.ZERO};if(!t.eql(p,t.ONE))throw new Error("invZ was invalid");return{x:I,y:S}}isTorsionFree(){const{h:f,isTorsionFree:d}=n;if(f===j)return!0;if(d)return d(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:f,clearCofactor:d}=n;return f===j?this:d?d(w,this):this.multiplyUnsafe(n.h)}toRawBytes(f=!0){return this.assertValidity(),r(w,this,f)}toHex(f=!0){return st(this.toRawBytes(f))}}w.BASE=new w(n.Gx,n.Gy,t.ONE),w.ZERO=new w(t.ZERO,t.ONE,t.ZERO);const O=n.nBitLength,T=Be(w,n.endo?Math.ceil(O/2):O);return{CURVE:n,ProjectivePoint:w,normPrivateKeyToScalar:o,weierstrassEquation:i,isWithinCurveOrder:l}}function Ae(e){const n=jt(e);return dt(n,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...n})}function Oe(e){const n=Ae(e),{Fp:t,n:r}=n,s=t.BYTES+1,i=2*t.BYTES+1;function l(u){return Fst(ft(u,n.nByteLength));function m(u){const g=r>>j;return u>g}function f(u){return m(u)?c(-u):u}const d=(u,g,x)=>et(u.slice(g,x));class h{constructor(g,x,N){this.r=g,this.s=x,this.recovery=N,this.assertValidity()}static fromCompact(g){const x=n.nByteLength;return g=M("compactSignature",g,x*2),new h(d(g,0,x),d(g,x,2*x))}static fromDER(g){const{r:x,s:N}=tt.toSig(M("DER",g));return new h(x,N)}assertValidity(){if(!O(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!O(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(g){return new h(this.r,this.s,g)}recoverPublicKey(g){const{r:x,s:N,recovery:q}=this,H=E(M("msgHash",g));if(q==null||![0,1,2,3].includes(q))throw new Error("recovery id invalid");const Z=q===2||q===3?x+n.n:x;if(Z>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const U=q&1?"03":"02",W=a.fromHex(U+T(Z)),Y=o(Z),X=c(-H*Y),at=c(N*Y),D=a.BASE.multiplyAndAddUnsafe(W,X,at);if(!D)throw new Error("point at infinify");return D.assertValidity(),D}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ct(this.toDERHex())}toDERHex(){return tt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ct(this.toCompactHex())}toCompactHex(){return T(this.r)+T(this.s)}}const b={isValidPrivateKey(u){try{return y(u),!0}catch{return!1}},normPrivateKeyToScalar:y,randomPrivateKey:()=>{const u=Vt(n.n);return be(n.randomBytes(u),n.n)},precompute(u=8,g=a.BASE){return g._setWindowSize(u),g.multiply(BigInt(3)),g}};function B(u,g=!0){return a.fromPrivateKey(u).toRawBytes(g)}function I(u){const g=nt(u),x=typeof u=="string",N=(g||x)&&u.length;return g?N===s||N===i:x?N===2*s||N===2*i:u instanceof a}function S(u,g,x=!0){if(I(u))throw new Error("first arg must be private key");if(!I(g))throw new Error("second arg must be public key");return a.fromHex(g).multiply(y(u)).toRawBytes(x)}const p=n.bits2int||function(u){const g=et(u),x=u.length*8-n.nBitLength;return x>0?g>>BigInt(x):g},E=n.bits2int_modN||function(u){return c(p(u))},v=St(n.nBitLength);function k(u){if(typeof u!="bigint")throw new Error("bigint expected");if(!(F<=u&&uQ in x))throw new Error("sign() legacy options not supported");const{hash:N,randomBytes:q}=n;let{lowS:H,prehash:Z,extraEntropy:U}=x;H==null&&(H=!0),u=M("msgHash",u),Z&&(u=M("prehashed msgHash",N(u)));const W=E(u),Y=y(g),X=[k(Y),k(W)];if(U!=null&&U!==!1){const Q=U===!0?q(t.BYTES):U;X.push(M("extraEntropy",Q))}const at=ut(...X),D=W;function gt(Q){const rt=p(Q);if(!O(rt))return;const It=o(rt),ot=a.BASE.multiply(rt).toAffine(),K=c(ot.x);if(K===F)return;const it=c(It*c(D+K*Y));if(it===F)return;let At=(ot.x===K?0:2)|Number(ot.y&j),Ot=it;return H&&m(it)&&(Ot=f(it),At^=1),new h(K,Ot,At)}return{seed:at,k2sig:gt}}const A={lowS:n.lowS,prehash:!1},z={lowS:n.lowS,prehash:!1};function C(u,g,x=A){const{seed:N,k2sig:q}=_(u,g,x),H=n;return zt(H.hash.outputLen,H.nByteLength,H.hmac)(N,q)}a.BASE._setWindowSize(8);function G(u,g,x,N=z){var ot;const q=u;if(g=M("msgHash",g),x=M("publicKey",x),"strict"in N)throw new Error("options.strict was renamed to lowS");const{lowS:H,prehash:Z}=N;let U,W;try{if(typeof q=="string"||nt(q))try{U=h.fromDER(q)}catch(K){if(!(K instanceof tt.Err))throw K;U=h.fromCompact(q)}else if(typeof q=="object"&&typeof q.r=="bigint"&&typeof q.s=="bigint"){const{r:K,s:it}=q;U=new h(K,it)}else throw new Error("PARSE");W=a.fromHex(x)}catch(K){if(K.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(H&&U.hasHighS())return!1;Z&&(g=n.hash(g));const{r:Y,s:X}=U,at=E(g),D=o(X),gt=c(at*D),Q=c(Y*D),rt=(ot=a.BASE.multiplyAndAddUnsafe(W,gt,Q))==null?void 0:ot.toAffine();return rt?c(rt.x)===Y:!1}return{CURVE:n,getPublicKey:B,getSharedSecret:S,sign:C,verify:G,ProjectivePoint:a,Signature:h,utils:b}}class Yt extends Ft{constructor(n,t){super(),this.finished=!1,this.destroyed=!1,Gt(n);const r=Wt(t);if(this.iHash=n.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,i=new Uint8Array(s);i.set(r.length>s?n.create().update(r).digest():r);for(let l=0;lnew Yt(e,n).update(t).digest();Kt.create=(e,n)=>new Yt(e,n);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function qe(e){return{hash:e,hmac:(n,...t)=>Kt(e,n,Dt(...t)),randomBytes:Qt}}function Ne(e,n){const t=r=>Oe({...e,...qe(r)});return Object.freeze({...t(n),create:t})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Mt=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Lt=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_e=BigInt(1),bt=BigInt(2),Zt=(e,n)=>(e+n/bt)/n;function Te(e){const n=Mt,t=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),l=BigInt(23),c=BigInt(44),o=BigInt(88),a=e*e*e%n,y=a*a*e%n,w=V(y,t,n)*y%n,O=V(w,t,n)*y%n,T=V(O,bt,n)*a%n,m=V(T,s,n)*T%n,f=V(m,i,n)*m%n,d=V(f,c,n)*f%n,h=V(d,o,n)*d%n,b=V(h,c,n)*f%n,B=V(b,t,n)*y%n,I=V(B,l,n)*m%n,S=V(I,r,n)*a%n,p=V(S,bt,n);if(!Et.eql(Et.sqr(p),e))throw new Error("Cannot find square root");return p}const Et=me(Mt,void 0,void 0,{sqrt:Te}),Pt=Ne({a:BigInt(0),b:BigInt(7),Fp:Et,n:Lt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const n=Lt,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-_e*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,l=BigInt("0x100000000000000000000000000000000"),c=Zt(i*e,n),o=Zt(-r*e,n);let a=R(e-c*t-o*s,n),y=R(-c*r-o*i,n);const w=a>l,O=y>l;if(w&&(a=n-a),O&&(y=n-y),a>l||y>l)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:w,k1:a,k2neg:O,k2:y}}}},Jt);BigInt(0);Pt.ProjectivePoint;const Le=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:Pt},Symbol.toStringTag,{value:"Module"}));export{Le as a,re as e,Pt as s}; +import{cF as Ft,cG as Gt,cH as Wt,cI as qt,cJ as Xt,cK as Dt,cL as Qt,b5 as Jt}from"./index-4Hagg-7l.js";/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ut=BigInt(0),ht=BigInt(1),te=BigInt(2);function nt(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function lt(e){if(!nt(e))throw new Error("Uint8Array expected")}const ee=Array.from({length:256},(e,n)=>n.toString(16).padStart(2,"0"));function st(e){lt(e);let n="";for(let t=0;t=P._0&&e<=P._9)return e-P._0;if(e>=P._A&&e<=P._F)return e-(P._A-10);if(e>=P._a&&e<=P._f)return e-(P._a-10)}function ct(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);const n=e.length,t=n/2;if(n%2)throw new Error("padded hex string expected, got unpadded hex of length "+n);const r=new Uint8Array(t);for(let s=0,i=0;sUt;e>>=ht,n+=1);return n}function se(e,n){return e>>BigInt(n)&ht}function ce(e,n,t){return e|(t?ht:Ut)<(te<new Uint8Array(e),_t=e=>Uint8Array.from(e);function zt(e,n,t){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof n!="number"||n<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let r=wt(e),s=wt(e),i=0;const l=()=>{r.fill(1),s.fill(0),i=0},c=(...w)=>t(s,r,...w),o=(w=wt())=>{s=c(_t([0]),w),r=c(),w.length!==0&&(s=c(_t([1]),w),r=c())},a=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let w=0;const O=[];for(;w{l(),o(w);let T;for(;!(T=O(a()));)o();return l(),T}}const fe={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||nt(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,n)=>n.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function dt(e,n,t={}){const r=(s,i,l)=>{const c=fe[i];if(typeof c!="function")throw new Error(`Invalid validator "${i}", expected function`);const o=e[s];if(!(l&&o===void 0)&&!c(o,e))throw new Error(`Invalid param ${String(s)}=${o} (${typeof o}), expected ${i}`)};for(const[s,i]of Object.entries(n))r(s,i,!1);for(const[s,i]of Object.entries(t))r(s,i,!0);return e}const ae=Object.freeze(Object.defineProperty({__proto__:null,abytes:lt,bitGet:se,bitLen:ie,bitMask:St,bitSet:ce,bytesToHex:st,bytesToNumberBE:et,bytesToNumberLE:xt,concatBytes:ut,createHmacDrbg:zt,ensureBytes:M,equalBytes:re,hexToBytes:ct,hexToNumber:Bt,isBytes:nt,numberToBytesBE:ft,numberToBytesLE:vt,numberToHexUnpadded:Rt,numberToVarBytesBE:ne,utf8ToBytes:oe,validateObject:dt},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const L=BigInt(0),$=BigInt(1),J=BigInt(2),ue=BigInt(3),yt=BigInt(4),Tt=BigInt(5),$t=BigInt(8);BigInt(9);BigInt(16);function R(e,n){const t=e%n;return t>=L?t:n+t}function le(e,n,t){if(t<=L||n 0");if(t===$)return L;let r=$;for(;n>L;)n&$&&(r=r*e%t),e=e*e%t,n>>=$;return r}function V(e,n,t){let r=e;for(;n-- >L;)r*=r,r%=t;return r}function mt(e,n){if(e===L||n<=L)throw new Error(`invert: expected positive integers, got n=${e} mod=${n}`);let t=R(e,n),r=n,s=L,i=$;for(;t!==L;){const c=r/t,o=r%t,a=s-i*c;r=t,t=o,s=i,i=a}if(r!==$)throw new Error("invert: does not exist");return R(s,n)}function de(e){const n=(e-$)/J;let t,r,s;for(t=e-$,r=0;t%J===L;t/=J,r++);for(s=J;s(r[s]="function",r),n);return dt(e,t)}function pe(e,n,t){if(t 0");if(t===L)return e.ONE;if(t===$)return n;let r=e.ONE,s=n;for(;t>L;)t&$&&(r=e.mul(r,s)),s=e.sqr(s),t>>=$;return r}function ye(e,n){const t=new Array(n.length),r=n.reduce((i,l,c)=>e.is0(l)?i:(t[c]=i,e.mul(i,l)),e.ONE),s=e.inv(r);return n.reduceRight((i,l,c)=>e.is0(l)?i:(t[c]=e.mul(i,t[c]),e.mul(i,l)),s),t}function Ct(e,n){const t=n!==void 0?n:e.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function me(e,n,t=!1,r={}){if(e<=L)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:i}=Ct(e,n);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const l=he(e),c=Object.freeze({ORDER:e,BITS:s,BYTES:i,MASK:St(s),ZERO:L,ONE:$,create:o=>R(o,e),isValid:o=>{if(typeof o!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof o}`);return L<=o&&oo===L,isOdd:o=>(o&$)===$,neg:o=>R(-o,e),eql:(o,a)=>o===a,sqr:o=>R(o*o,e),add:(o,a)=>R(o+a,e),sub:(o,a)=>R(o-a,e),mul:(o,a)=>R(o*a,e),pow:(o,a)=>pe(c,o,a),div:(o,a)=>R(o*mt(a,e),e),sqrN:o=>o*o,addN:(o,a)=>o+a,subN:(o,a)=>o-a,mulN:(o,a)=>o*a,inv:o=>mt(o,e),sqrt:r.sqrt||(o=>l(c,o)),invertBatch:o=>ye(c,o),cmov:(o,a,y)=>y?a:o,toBytes:o=>t?vt(o,i):ft(o,i),fromBytes:o=>{if(o.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${o.length}`);return t?xt(o):et(o)}});return Object.freeze(c)}function kt(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const n=e.toString(2).length;return Math.ceil(n/8)}function Vt(e){const n=kt(e);return n+Math.ceil(n/2)}function be(e,n,t=!1){const r=e.length,s=kt(n),i=Vt(n);if(r<16||r1024)throw new Error(`expected ${i}-1024 bytes of input, got ${r}`);const l=t?et(e):xt(e),c=R(l,n-$)+$;return t?vt(c,s):ft(c,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ee=BigInt(0),pt=BigInt(1);function Be(e,n){const t=(s,i)=>{const l=i.negate();return s?l:i},r=s=>{const i=Math.ceil(n/s)+1,l=2**(s-1);return{windows:i,windowSize:l}};return{constTimeNegate:t,unsafeLadder(s,i){let l=e.ZERO,c=s;for(;i>Ee;)i&pt&&(l=l.add(c)),c=c.double(),i>>=pt;return l},precomputeWindow(s,i){const{windows:l,windowSize:c}=r(i),o=[];let a=s,y=a;for(let w=0;w>=T,d>o&&(d-=O,l+=pt);const h=f,b=f+Math.abs(d)-1,B=m%2!==0,I=d<0;d===0?y=y.add(t(B,i[h])):a=a.add(t(I,i[b]))}return{p:a,f:y}},wNAFCached(s,i,l,c){const o=s._WINDOW_SIZE||1;let a=i.get(s);return a||(a=this.precomputeWindow(s,o),o!==1&&i.set(s,c(a))),this.wNAF(o,a,l)}}}function jt(e){return we(e.Fp),dt(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ct(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function xe(e){const n=jt(e);dt(n,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:r,a:s}=n;if(t){if(!r.eql(s,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...n})}const{bytesToNumberBE:ve,hexToBytes:Se}=ae,tt={Err:class extends Error{constructor(n=""){super(n)}},_parseInt(e){const{Err:n}=tt;if(e.length<2||e[0]!==2)throw new n("Invalid signature integer tag");const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw new n("Invalid signature integer: wrong length");if(r[0]&128)throw new n("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new n("Invalid signature integer: unnecessary leading zero");return{d:ve(r),l:e.subarray(t+2)}},toSig(e){const{Err:n}=tt,t=typeof e=="string"?Se(e):e;lt(t);let r=t.length;if(r<2||t[0]!=48)throw new n("Invalid signature tag");if(t[1]!==r-2)throw new n("Invalid signature: incorrect length");const{d:s,l:i}=tt._parseInt(t.subarray(2)),{d:l,l:c}=tt._parseInt(i);if(c.length)throw new n("Invalid signature: left bytes after parsing");return{r:s,s:l}},hexFromSig(e){const n=a=>Number.parseInt(a[0],16)&8?"00"+a:a,t=a=>{const y=a.toString(16);return y.length&1?`0${y}`:y},r=n(t(e.s)),s=n(t(e.r)),i=r.length/2,l=s.length/2,c=t(i),o=t(l);return`30${t(l+i+4)}02${o}${s}02${c}${r}`}},F=BigInt(0),j=BigInt(1);BigInt(2);const Ht=BigInt(3);BigInt(4);function Ie(e){const n=xe(e),{Fp:t}=n,r=n.toBytes||((m,f,d)=>{const h=f.toAffine();return ut(Uint8Array.from([4]),t.toBytes(h.x),t.toBytes(h.y))}),s=n.fromBytes||(m=>{const f=m.subarray(1),d=t.fromBytes(f.subarray(0,t.BYTES)),h=t.fromBytes(f.subarray(t.BYTES,2*t.BYTES));return{x:d,y:h}});function i(m){const{a:f,b:d}=n,h=t.sqr(m),b=t.mul(h,m);return t.add(t.add(b,t.mul(m,f)),d)}if(!t.eql(t.sqr(n.Gy),i(n.Gx)))throw new Error("bad generator point: equation left != right");function l(m){return typeof m=="bigint"&&Ft.eql(B,t.ZERO);return b(d)&&b(h)?w.ZERO:new w(d,h,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(f){const d=t.invertBatch(f.map(h=>h.pz));return f.map((h,b)=>h.toAffine(d[b])).map(w.fromAffine)}static fromHex(f){const d=w.fromAffine(s(M("pointHex",f)));return d.assertValidity(),d}static fromPrivateKey(f){return w.BASE.multiply(o(f))}_setWindowSize(f){this._WINDOW_SIZE=f,a.delete(this)}assertValidity(){if(this.is0()){if(n.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:f,y:d}=this.toAffine();if(!t.isValid(f)||!t.isValid(d))throw new Error("bad point: x or y not FE");const h=t.sqr(d),b=i(f);if(!t.eql(h,b))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:f}=this.toAffine();if(t.isOdd)return!t.isOdd(f);throw new Error("Field doesn't support isOdd")}equals(f){y(f);const{px:d,py:h,pz:b}=this,{px:B,py:I,pz:S}=f,p=t.eql(t.mul(d,S),t.mul(B,b)),E=t.eql(t.mul(h,S),t.mul(I,b));return p&&E}negate(){return new w(this.px,t.neg(this.py),this.pz)}double(){const{a:f,b:d}=n,h=t.mul(d,Ht),{px:b,py:B,pz:I}=this;let S=t.ZERO,p=t.ZERO,E=t.ZERO,v=t.mul(b,b),k=t.mul(B,B),_=t.mul(I,I),A=t.mul(b,B);return A=t.add(A,A),E=t.mul(b,I),E=t.add(E,E),S=t.mul(f,E),p=t.mul(h,_),p=t.add(S,p),S=t.sub(k,p),p=t.add(k,p),p=t.mul(S,p),S=t.mul(A,S),E=t.mul(h,E),_=t.mul(f,_),A=t.sub(v,_),A=t.mul(f,A),A=t.add(A,E),E=t.add(v,v),v=t.add(E,v),v=t.add(v,_),v=t.mul(v,A),p=t.add(p,v),_=t.mul(B,I),_=t.add(_,_),v=t.mul(_,A),S=t.sub(S,v),E=t.mul(_,k),E=t.add(E,E),E=t.add(E,E),new w(S,p,E)}add(f){y(f);const{px:d,py:h,pz:b}=this,{px:B,py:I,pz:S}=f;let p=t.ZERO,E=t.ZERO,v=t.ZERO;const k=n.a,_=t.mul(n.b,Ht);let A=t.mul(d,B),z=t.mul(h,I),C=t.mul(b,S),G=t.add(d,h),u=t.add(B,I);G=t.mul(G,u),u=t.add(A,z),G=t.sub(G,u),u=t.add(d,b);let g=t.add(B,S);return u=t.mul(u,g),g=t.add(A,C),u=t.sub(u,g),g=t.add(h,b),p=t.add(I,S),g=t.mul(g,p),p=t.add(z,C),g=t.sub(g,p),v=t.mul(k,u),p=t.mul(_,C),v=t.add(p,v),p=t.sub(z,v),v=t.add(z,v),E=t.mul(p,v),z=t.add(A,A),z=t.add(z,A),C=t.mul(k,C),u=t.mul(_,u),z=t.add(z,C),C=t.sub(A,C),C=t.mul(k,C),u=t.add(u,C),A=t.mul(z,u),E=t.add(E,A),A=t.mul(g,u),p=t.mul(G,p),p=t.sub(p,A),A=t.mul(G,z),v=t.mul(g,v),v=t.add(v,A),new w(p,E,v)}subtract(f){return this.add(f.negate())}is0(){return this.equals(w.ZERO)}wNAF(f){return T.wNAFCached(this,a,f,d=>{const h=t.invertBatch(d.map(b=>b.pz));return d.map((b,B)=>b.toAffine(h[B])).map(w.fromAffine)})}multiplyUnsafe(f){const d=w.ZERO;if(f===F)return d;if(c(f),f===j)return this;const{endo:h}=n;if(!h)return T.unsafeLadder(this,f);let{k1neg:b,k1:B,k2neg:I,k2:S}=h.splitScalar(f),p=d,E=d,v=this;for(;B>F||S>F;)B&j&&(p=p.add(v)),S&j&&(E=E.add(v)),v=v.double(),B>>=j,S>>=j;return b&&(p=p.negate()),I&&(E=E.negate()),E=new w(t.mul(E.px,h.beta),E.py,E.pz),p.add(E)}multiply(f){c(f);let d=f,h,b;const{endo:B}=n;if(B){const{k1neg:I,k1:S,k2neg:p,k2:E}=B.splitScalar(d);let{p:v,f:k}=this.wNAF(S),{p:_,f:A}=this.wNAF(E);v=T.constTimeNegate(I,v),_=T.constTimeNegate(p,_),_=new w(t.mul(_.px,B.beta),_.py,_.pz),h=v.add(_),b=k.add(A)}else{const{p:I,f:S}=this.wNAF(d);h=I,b=S}return w.normalizeZ([h,b])[0]}multiplyAndAddUnsafe(f,d,h){const b=w.BASE,B=(S,p)=>p===F||p===j||!S.equals(b)?S.multiplyUnsafe(p):S.multiply(p),I=B(this,d).add(B(f,h));return I.is0()?void 0:I}toAffine(f){const{px:d,py:h,pz:b}=this,B=this.is0();f==null&&(f=B?t.ONE:t.inv(b));const I=t.mul(d,f),S=t.mul(h,f),p=t.mul(b,f);if(B)return{x:t.ZERO,y:t.ZERO};if(!t.eql(p,t.ONE))throw new Error("invZ was invalid");return{x:I,y:S}}isTorsionFree(){const{h:f,isTorsionFree:d}=n;if(f===j)return!0;if(d)return d(w,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:f,clearCofactor:d}=n;return f===j?this:d?d(w,this):this.multiplyUnsafe(n.h)}toRawBytes(f=!0){return this.assertValidity(),r(w,this,f)}toHex(f=!0){return st(this.toRawBytes(f))}}w.BASE=new w(n.Gx,n.Gy,t.ONE),w.ZERO=new w(t.ZERO,t.ONE,t.ZERO);const O=n.nBitLength,T=Be(w,n.endo?Math.ceil(O/2):O);return{CURVE:n,ProjectivePoint:w,normPrivateKeyToScalar:o,weierstrassEquation:i,isWithinCurveOrder:l}}function Ae(e){const n=jt(e);return dt(n,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...n})}function Oe(e){const n=Ae(e),{Fp:t,n:r}=n,s=t.BYTES+1,i=2*t.BYTES+1;function l(u){return Fst(ft(u,n.nByteLength));function m(u){const g=r>>j;return u>g}function f(u){return m(u)?c(-u):u}const d=(u,g,x)=>et(u.slice(g,x));class h{constructor(g,x,N){this.r=g,this.s=x,this.recovery=N,this.assertValidity()}static fromCompact(g){const x=n.nByteLength;return g=M("compactSignature",g,x*2),new h(d(g,0,x),d(g,x,2*x))}static fromDER(g){const{r:x,s:N}=tt.toSig(M("DER",g));return new h(x,N)}assertValidity(){if(!O(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!O(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(g){return new h(this.r,this.s,g)}recoverPublicKey(g){const{r:x,s:N,recovery:q}=this,H=E(M("msgHash",g));if(q==null||![0,1,2,3].includes(q))throw new Error("recovery id invalid");const Z=q===2||q===3?x+n.n:x;if(Z>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const U=q&1?"03":"02",W=a.fromHex(U+T(Z)),Y=o(Z),X=c(-H*Y),at=c(N*Y),D=a.BASE.multiplyAndAddUnsafe(W,X,at);if(!D)throw new Error("point at infinify");return D.assertValidity(),D}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ct(this.toDERHex())}toDERHex(){return tt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ct(this.toCompactHex())}toCompactHex(){return T(this.r)+T(this.s)}}const b={isValidPrivateKey(u){try{return y(u),!0}catch{return!1}},normPrivateKeyToScalar:y,randomPrivateKey:()=>{const u=Vt(n.n);return be(n.randomBytes(u),n.n)},precompute(u=8,g=a.BASE){return g._setWindowSize(u),g.multiply(BigInt(3)),g}};function B(u,g=!0){return a.fromPrivateKey(u).toRawBytes(g)}function I(u){const g=nt(u),x=typeof u=="string",N=(g||x)&&u.length;return g?N===s||N===i:x?N===2*s||N===2*i:u instanceof a}function S(u,g,x=!0){if(I(u))throw new Error("first arg must be private key");if(!I(g))throw new Error("second arg must be public key");return a.fromHex(g).multiply(y(u)).toRawBytes(x)}const p=n.bits2int||function(u){const g=et(u),x=u.length*8-n.nBitLength;return x>0?g>>BigInt(x):g},E=n.bits2int_modN||function(u){return c(p(u))},v=St(n.nBitLength);function k(u){if(typeof u!="bigint")throw new Error("bigint expected");if(!(F<=u&&uQ in x))throw new Error("sign() legacy options not supported");const{hash:N,randomBytes:q}=n;let{lowS:H,prehash:Z,extraEntropy:U}=x;H==null&&(H=!0),u=M("msgHash",u),Z&&(u=M("prehashed msgHash",N(u)));const W=E(u),Y=y(g),X=[k(Y),k(W)];if(U!=null&&U!==!1){const Q=U===!0?q(t.BYTES):U;X.push(M("extraEntropy",Q))}const at=ut(...X),D=W;function gt(Q){const rt=p(Q);if(!O(rt))return;const It=o(rt),ot=a.BASE.multiply(rt).toAffine(),K=c(ot.x);if(K===F)return;const it=c(It*c(D+K*Y));if(it===F)return;let At=(ot.x===K?0:2)|Number(ot.y&j),Ot=it;return H&&m(it)&&(Ot=f(it),At^=1),new h(K,Ot,At)}return{seed:at,k2sig:gt}}const A={lowS:n.lowS,prehash:!1},z={lowS:n.lowS,prehash:!1};function C(u,g,x=A){const{seed:N,k2sig:q}=_(u,g,x),H=n;return zt(H.hash.outputLen,H.nByteLength,H.hmac)(N,q)}a.BASE._setWindowSize(8);function G(u,g,x,N=z){var ot;const q=u;if(g=M("msgHash",g),x=M("publicKey",x),"strict"in N)throw new Error("options.strict was renamed to lowS");const{lowS:H,prehash:Z}=N;let U,W;try{if(typeof q=="string"||nt(q))try{U=h.fromDER(q)}catch(K){if(!(K instanceof tt.Err))throw K;U=h.fromCompact(q)}else if(typeof q=="object"&&typeof q.r=="bigint"&&typeof q.s=="bigint"){const{r:K,s:it}=q;U=new h(K,it)}else throw new Error("PARSE");W=a.fromHex(x)}catch(K){if(K.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(H&&U.hasHighS())return!1;Z&&(g=n.hash(g));const{r:Y,s:X}=U,at=E(g),D=o(X),gt=c(at*D),Q=c(Y*D),rt=(ot=a.BASE.multiplyAndAddUnsafe(W,gt,Q))==null?void 0:ot.toAffine();return rt?c(rt.x)===Y:!1}return{CURVE:n,getPublicKey:B,getSharedSecret:S,sign:C,verify:G,ProjectivePoint:a,Signature:h,utils:b}}class Yt extends Ft{constructor(n,t){super(),this.finished=!1,this.destroyed=!1,Gt(n);const r=Wt(t);if(this.iHash=n.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,i=new Uint8Array(s);i.set(r.length>s?n.create().update(r).digest():r);for(let l=0;lnew Yt(e,n).update(t).digest();Kt.create=(e,n)=>new Yt(e,n);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function qe(e){return{hash:e,hmac:(n,...t)=>Kt(e,n,Dt(...t)),randomBytes:Qt}}function Ne(e,n){const t=r=>Oe({...e,...qe(r)});return Object.freeze({...t(n),create:t})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Mt=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Lt=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_e=BigInt(1),bt=BigInt(2),Zt=(e,n)=>(e+n/bt)/n;function Te(e){const n=Mt,t=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),l=BigInt(23),c=BigInt(44),o=BigInt(88),a=e*e*e%n,y=a*a*e%n,w=V(y,t,n)*y%n,O=V(w,t,n)*y%n,T=V(O,bt,n)*a%n,m=V(T,s,n)*T%n,f=V(m,i,n)*m%n,d=V(f,c,n)*f%n,h=V(d,o,n)*d%n,b=V(h,c,n)*f%n,B=V(b,t,n)*y%n,I=V(B,l,n)*m%n,S=V(I,r,n)*a%n,p=V(S,bt,n);if(!Et.eql(Et.sqr(p),e))throw new Error("Cannot find square root");return p}const Et=me(Mt,void 0,void 0,{sqrt:Te}),Pt=Ne({a:BigInt(0),b:BigInt(7),Fp:Et,n:Lt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const n=Lt,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-_e*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,l=BigInt("0x100000000000000000000000000000000"),c=Zt(i*e,n),o=Zt(-r*e,n);let a=R(e-c*t-o*s,n),y=R(-c*r-o*i,n);const w=a>l,O=y>l;if(w&&(a=n-a),O&&(y=n-y),a>l||y>l)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:w,k1:a,k2neg:O,k2:y}}}},Jt);BigInt(0);Pt.ProjectivePoint;const Le=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:Pt},Symbol.toStringTag,{value:"Module"}));export{Le as a,re as e,Pt as s}; diff --git a/assets/w3m-modal-C_J1BgbU.js b/assets/w3m-modal-V5rdP7TG.js similarity index 95% rename from assets/w3m-modal-C_J1BgbU.js rename to assets/w3m-modal-V5rdP7TG.js index c139e8c..201231d 100644 --- a/assets/w3m-modal-C_J1BgbU.js +++ b/assets/w3m-modal-V5rdP7TG.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-B5R0vXrb.js","assets/index-CBwDx5gl.js","assets/index-Bx4zt1nf.css"])))=>i.map(i=>d[i]); -import{i as C,h as S,M as n,C as h,O as b,cs as k,A as p,E,k as A,R as c,b8 as f,bg as _,bd as x,S as O,ct as v,cu as L,b as w,c as N,cv as I}from"./index-CBwDx5gl.js";const T=C` +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DYSmb46M.js","assets/index-4Hagg-7l.js","assets/index-C5iV8B94.css"])))=>i.map(i=>d[i]); +import{i as C,h as S,M as n,C as h,O as b,cs as k,A as p,E,k as A,R as c,b8 as f,bg as _,bd as x,S as O,ct as v,cu as L,b as w,c as N,cv as I}from"./index-4Hagg-7l.js";const T=C` :host { z-index: var(--w3m-z-index); display: block; @@ -138,7 +138,7 @@ import{i as C,h as S,M as n,C as h,O as b,cs as k,A as p,E,k as A,R as c,b8 as f - `:null}async onOverlayClick(e){e.target===e.currentTarget&&await this.handleClose()}async handleClose(){const e=c.state.view==="ConnectingSiwe",i=c.state.view==="ApproveTransaction";if(this.isSiweEnabled){const{SIWEController:t}=await f(async()=>{const{SIWEController:o}=await import("./index-B5R0vXrb.js");return{SIWEController:o}},__vite__mapDeps([0,1,2]));t.state.status!=="success"&&(e||i)?n.shake():n.close()}else n.close()}initializeTheming(){const{themeVariables:e,themeMode:i}=I.state,t=_.getColorTheme(i);x(e,t)}onClose(){this.open=!1,this.classList.remove("open"),this.onScrollUnlock(),O.hide(),this.onRemoveKeyboardListener()}onOpen(){this.open=!0,this.classList.add("open"),this.onScrollLock(),this.onAddKeyboardListener()}onScrollLock(){const e=document.createElement("style");e.dataset.w3m=g,e.textContent=` + `:null}async onOverlayClick(e){e.target===e.currentTarget&&await this.handleClose()}async handleClose(){const e=c.state.view==="ConnectingSiwe",i=c.state.view==="ApproveTransaction";if(this.isSiweEnabled){const{SIWEController:t}=await f(async()=>{const{SIWEController:o}=await import("./index-DYSmb46M.js");return{SIWEController:o}},__vite__mapDeps([0,1,2]));t.state.status!=="success"&&(e||i)?n.shake():n.close()}else n.close()}initializeTheming(){const{themeVariables:e,themeMode:i}=I.state,t=_.getColorTheme(i);x(e,t)}onClose(){this.open=!1,this.classList.remove("open"),this.onScrollUnlock(),O.hide(),this.onRemoveKeyboardListener()}onOpen(){this.open=!0,this.classList.add("open"),this.onScrollLock(),this.onAddKeyboardListener()}onScrollLock(){const e=document.createElement("style");e.dataset.w3m=g,e.textContent=` body { touch-action: none; overflow: hidden; @@ -147,4 +147,4 @@ import{i as C,h as S,M as n,C as h,O as b,cs as k,A as p,E,k as A,R as c,b8 as f w3m-modal { pointer-events: auto; } - `,document.head.appendChild(e)}onScrollUnlock(){const e=document.head.querySelector(`style[data-w3m="${g}"]`);e&&e.remove()}onAddKeyboardListener(){var i;this.abortController=new AbortController;const e=(i=this.shadowRoot)==null?void 0:i.querySelector("wui-card");e==null||e.focus(),window.addEventListener("keydown",t=>{if(t.key==="Escape")this.handleClose();else if(t.key==="Tab"){const{tagName:s}=t.target;s&&!s.includes("W3M-")&&!s.includes("WUI-")&&(e==null||e.focus())}},this.abortController)}onRemoveKeyboardListener(){var e;(e=this.abortController)==null||e.abort(),this.abortController=void 0}onSiweStatusChange(e){e==="success"&&n.close()}async onNewAddress(e){var o;const i=this.caipAddress?v.getPlainAddress(this.caipAddress):void 0,t=e?v.getPlainAddress(e):void 0;if(t&&!(i===t)&&this.isSiweEnabled){const{SIWEController:a}=await f(async()=>{const{SIWEController:m}=await import("./index-B5R0vXrb.js");return{SIWEController:m}},__vite__mapDeps([0,1,2])),r=p.state.siweStatus==="success";!i&&t?this.onSiweNavigation():r&&i&&t&&i!==t&&(o=a.state._client)!=null&&o.options.signOutOnAccountChange&&(await a.signOut(),this.onSiweNavigation())}t||n.close(),this.caipAddress=e}async onNewNetwork(e){var s,o,a,r;if(!this.caipAddress){this.caipNetwork=e;return}const i=(o=(s=this.caipNetwork)==null?void 0:s.id)==null?void 0:o.toString(),t=(a=e==null?void 0:e.id)==null?void 0:a.toString();if(i&&t&&i!==t)if(this.isSiweEnabled){const{SIWEController:m}=await f(async()=>{const{SIWEController:y}=await import("./index-B5R0vXrb.js");return{SIWEController:y}},__vite__mapDeps([0,1,2]));(r=m.state._client)!=null&&r.options.signOutOnNetworkChange?(await m.signOut(),this.onSiweNavigation()):c.goBack()}else c.goBack();this.caipNetwork=e}onSiweNavigation(){const e=h.state.activeChain===L.CHAIN.EVM;!(p.state.siweStatus==="success")&&e?this.open?c.replace("ConnectingSiwe"):n.open({view:"ConnectingSiwe"}):c.goBack()}};l.styles=T;d([w()],l.prototype,"open",void 0);d([w()],l.prototype,"caipAddress",void 0);d([w()],l.prototype,"caipNetwork",void 0);d([w()],l.prototype,"isSiweEnabled",void 0);d([w()],l.prototype,"shake",void 0);l=d([N("w3m-modal")],l);export{l as W3mModal}; + `,document.head.appendChild(e)}onScrollUnlock(){const e=document.head.querySelector(`style[data-w3m="${g}"]`);e&&e.remove()}onAddKeyboardListener(){var i;this.abortController=new AbortController;const e=(i=this.shadowRoot)==null?void 0:i.querySelector("wui-card");e==null||e.focus(),window.addEventListener("keydown",t=>{if(t.key==="Escape")this.handleClose();else if(t.key==="Tab"){const{tagName:s}=t.target;s&&!s.includes("W3M-")&&!s.includes("WUI-")&&(e==null||e.focus())}},this.abortController)}onRemoveKeyboardListener(){var e;(e=this.abortController)==null||e.abort(),this.abortController=void 0}onSiweStatusChange(e){e==="success"&&n.close()}async onNewAddress(e){var o;const i=this.caipAddress?v.getPlainAddress(this.caipAddress):void 0,t=e?v.getPlainAddress(e):void 0;if(t&&!(i===t)&&this.isSiweEnabled){const{SIWEController:a}=await f(async()=>{const{SIWEController:m}=await import("./index-DYSmb46M.js");return{SIWEController:m}},__vite__mapDeps([0,1,2])),r=p.state.siweStatus==="success";!i&&t?this.onSiweNavigation():r&&i&&t&&i!==t&&(o=a.state._client)!=null&&o.options.signOutOnAccountChange&&(await a.signOut(),this.onSiweNavigation())}t||n.close(),this.caipAddress=e}async onNewNetwork(e){var s,o,a,r;if(!this.caipAddress){this.caipNetwork=e;return}const i=(o=(s=this.caipNetwork)==null?void 0:s.id)==null?void 0:o.toString(),t=(a=e==null?void 0:e.id)==null?void 0:a.toString();if(i&&t&&i!==t)if(this.isSiweEnabled){const{SIWEController:m}=await f(async()=>{const{SIWEController:y}=await import("./index-DYSmb46M.js");return{SIWEController:y}},__vite__mapDeps([0,1,2]));(r=m.state._client)!=null&&r.options.signOutOnNetworkChange?(await m.signOut(),this.onSiweNavigation()):c.goBack()}else c.goBack();this.caipNetwork=e}onSiweNavigation(){const e=h.state.activeChain===L.CHAIN.EVM;!(p.state.siweStatus==="success")&&e?this.open?c.replace("ConnectingSiwe"):n.open({view:"ConnectingSiwe"}):c.goBack()}};l.styles=T;d([w()],l.prototype,"open",void 0);d([w()],l.prototype,"caipAddress",void 0);d([w()],l.prototype,"caipNetwork",void 0);d([w()],l.prototype,"isSiweEnabled",void 0);d([w()],l.prototype,"shake",void 0);l=d([N("w3m-modal")],l);export{l as W3mModal}; diff --git a/index.html b/index.html index 6d828a7..6fb4dad 100644 --- a/index.html +++ b/index.html @@ -5,8 +5,8 @@ dAcademy - - + +