@optimystic/db-core 0.4.1 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +1 -1
- package/dist/index.min.js.map +2 -2
- package/dist/src/collections/tree/struct.d.ts.map +1 -1
- package/dist/src/collections/tree/struct.js +2 -1
- package/dist/src/collections/tree/struct.js.map +1 -1
- package/dist/src/log/log.d.ts.map +1 -1
- package/dist/src/log/log.js +2 -1
- package/dist/src/log/log.js.map +1 -1
- package/package.json +1 -1
- package/src/collections/tree/struct.ts +2 -1
- package/src/log/log.ts +2 -1
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.OptimysticDbCore = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var OptimysticDbCore=(()=>{var Mn=Object.defineProperty;var rf=Object.getOwnPropertyDescriptor;var nf=Object.getOwnPropertyNames;var of=Object.prototype.hasOwnProperty;var sf=(r,t)=>()=>(r&&(t=r(r=0)),t);var at=(r,t)=>{for(var e in t)Mn(r,e,{get:t[e],enumerable:!0})},af=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of nf(t))!of.call(r,o)&&o!==e&&Mn(r,o,{get:()=>t[o],enumerable:!(n=rf(t,o))||n.enumerable});return r};var cf=r=>af(Mn({},"__esModule",{value:!0}),r);var Nc={};at(Nc,{ACTIONS_ENGINE_ID:()=>$s,ActionsEngine:()=>Ur,createActionsStatements:()=>Or});function Or(r){return r.map(t=>JSON.stringify(t))}var $s,Ur,Bn=sf(()=>{"use strict";$s="actions@1.0.0",Ur=class{coordinator;constructor(t){this.coordinator=t}async execute(t){try{let e=[];for(let n of t.statements){let o=JSON.parse(n);if(!o.collectionId||typeof o.collectionId!="string")return{success:!1,error:"Invalid statement: missing collectionId"};if(!o.actions||!Array.isArray(o.actions))return{success:!1,error:`Invalid statement: collection ${o.collectionId} missing or invalid actions array`};e.push(o),await this.coordinator.applyActions([o],t.stamp.id)}return{success:!0,actions:e}}catch(e){return{success:!1,error:`Failed to execute transaction: ${e instanceof Error?e.message:String(e)}`}}}}});var mh={};at(mh,{ACTIONS_ENGINE_ID:()=>$s,ActionsEngine:()=>Ur,Atomic:()=>Ut,BTree:()=>jt,CacheSource:()=>Lr,Chain:()=>Be,Collection:()=>ve,Diary:()=>Ts,DiaryHeaderBlockType:()=>Ls,EntriesPerBlock:()=>to,KeyBound:()=>Zn,KeyRange:()=>Yn,Keyset:()=>Xn,Latches:()=>ie,Log:()=>xt,LogDataBlockType:()=>Vs,LogHeaderBlockType:()=>Fs,NetworkTransactor:()=>ei,NodeCapacity:()=>ft,Path:()=>ue,PathBranch:()=>Bt,Pending:()=>Vr,Tracker:()=>Ft,TransactionContext:()=>Cn,TransactionCoordinator:()=>kn,TransactionSession:()=>Dn,TransactionValidator:()=>Tn,TransactorSource:()=>We,Tree:()=>Os,TreeHeaderBlockType:()=>Ns,apply:()=>_,applyOperation:()=>Nt,applyOperations:()=>ai,applyTransform:()=>uf,applyTransformToStore:()=>zn,blockIdToBytes:()=>mt,blockIdsForTransforms:()=>At,concatTransform:()=>jn,concatTransforms:()=>Vn,copyTransforms:()=>qn,createActionsStatements:()=>Or,createTransactionId:()=>Qe,createTransactionStamp:()=>Je,distinctBlockActionTransforms:()=>ri,emptyTransforms:()=>sr,ensured:()=>oi,ensuredMap:()=>ph,entryAt:()=>de,get:()=>X,groupBy:()=>ni,hashString:()=>ae,isTransformsEmpty:()=>Hn,mergeTransforms:()=>ci,nameof:()=>nt,pathValid:()=>hi,priorHash$:()=>Dd,registerBlockType:()=>bt,rootId$:()=>Us,transformForBlockId:()=>Fn,transformsFromTransform:()=>$n,withOperation:()=>ff});var Kn=new Map;function bt(r,t){if(Kn.has(r))throw new Error(`Block type ${r} (${t}) already registered (${Kn.get(r)})`);return Kn.set(r,t),r}function Nt(r,[t,e,n,o]){Array.isArray(o)?r[t].splice(e,n,...structuredClone(o)):r[t]=structuredClone(o)}function ai(r,t){for(let e of t)Nt(r,e)}function ff(r,[t,e,n,o]){if(Array.isArray(o)){let s=r[t];return{...r,[t]:[...s.slice(0,e),...structuredClone(o),...s.slice(e+n)]}}else return{...r,[t]:structuredClone(o)}}function At(r){if(!r)return[];let t=Object.keys(r.inserts??{}),e=Object.keys(r.updates??{}),n=r.deletes??[];return[...new Set([...t,...e,...n])]}function sr(){return{inserts:{},updates:{},deletes:[]}}function qn(r){let t=r.updates?Object.fromEntries(Object.entries(r.updates).map(([e,n])=>[e,structuredClone(n)])):void 0;return{inserts:{...r.inserts},updates:t,deletes:r.deletes?[...r.deletes]:void 0}}function ci(r,t){return{inserts:{...r.inserts,...t.inserts},updates:{...r.updates,...t.updates},deletes:[...r.deletes??[],...t.deletes??[]]}}function Hn(r){return Object.keys(r.inserts??{}).length===0&&Object.keys(r.updates??{}).length===0&&(r.deletes?.length??0)===0}function Vn(...r){return r.reduce((t,e)=>ci(t,e),sr())}function Fn(r,t){return{...r.inserts&&t in r.inserts?{insert:r.inserts[t]}:{},...r.updates&&t in r.updates?{updates:structuredClone(r.updates[t])}:{},...r.deletes?.includes(t)?{delete:!0}:{}}}function $n(r,t){return{inserts:r.insert?{[t]:r.insert}:{},updates:r.updates?{[t]:r.updates}:{},deletes:r.delete?[t]:[]}}function zn(r,t){for(let e of r.deletes??[])t.delete(e);for(let[,e]of Object.entries(r.inserts??{}))t.insert(e);for(let[e,n]of Object.entries(r.updates??{}))for(let o of n)t.update(e,o)}function uf(r,t){if(t.insert&&(r=t.insert),r&&t.updates&&ai(r,t.updates),!t.delete)return r}function jn(r,t,e){return{inserts:{...r.inserts,...e.insert?{[t]:e.insert}:{}},updates:{...r.updates,...e.updates?{[t]:e.updates}:{}},deletes:[...r.deletes??[],...e.delete?[t]:[]]}}async function X(r,t){let e=await r.tryGet(t);if(!e)throw Error(`Missing block (${t})`);return e}function _(r,t,e){Nt(t,e),r.update(t.header.id,e)}function nt(r,t){return t??r}var fe=bt("TL","TreeLeaf"),Gn=bt("TB","TreeBranch"),yt=nt("entries"),wt=nt("partitions"),zt=nt("nodes");var ft=64,jt=class r{store;trunk;keyFromEntry;compare;_version=0;constructor(t,e,n=s=>s,o=(s,i)=>s<i?-1:s>i?1:0){this.store=t,this.trunk=e,this.keyFromEntry=n,this.compare=o}static createRoot(t){return fi(t,[])}static create(t,e,n=i=>i,o=(i,a)=>i<a?-1:i>a?1:0,s){let i=r.createRoot(t);t.insert(i);let a=e(t,i.header.id,s);return new r(t,a,n,o)}async first(){return await this.getFirst(await this.trunk.get())}async last(){return await this.getLast(await this.trunk.get())}async find(t){return await this.getPath(await this.trunk.get(),t)}async get(t){return this.at(await this.find(t))}at(t){return this.validatePath(t),t.on?this.getEntry(t):void 0}async*range(t){let e=t.first?await this.findFirst(t):t.isAscending?await this.first():await this.last(),n=t.last?await this.findLast(t):t.isAscending?await this.last():await this.first();if(!n.on)return;let o=this.keyFromPath(n),i=(t.isAscending?this.internalAscending(e):this.internalDescending(e))[Symbol.asyncIterator](),a=t.isAscending?1:-1;for await(let c of i){if(!c.on||this.compare(this.keyFromPath(c),o)*a>0)break;yield c}}isValid(t){return t.version===this._version}async insert(t){Object.freeze(t);let e=await this.internalInsert(t);return e.on&&(e.version=++this._version),e}async updateAt(t,e){this.validatePath(t),t.on&&Object.freeze(e);let n=await this.internalUpdate(t,e);return n[0].on&&(n[0].version=++this._version),n}async upsert(t){let e=await this.find(this.keyFromEntry(t));return Object.freeze(t),e.on?this.updateEntry(e,t):await this.internalInsertAt(e,t),e.version=++this._version,e}async merge(t,e){let n=await this.keyFromEntry(t),o=await this.find(n);return o.on?await this.updateAt(o,e(this.getEntry(o))):(await this.internalInsertAt(o,Object.freeze(t)),o.on=!0,o.version=++this._version,[o,!1])}async deleteAt(t){this.validatePath(t);let e=await this.internalDelete(t);return e&&++this._version,e}async drop(){let t=await this.trunk.get();for await(let e of this.nodeIds(t))this.store.delete(e)}ascending(t){return this.validatePath(t),this.internalAscending(t.clone())}descending(t){return this.validatePath(t),this.internalDescending(t.clone())}async getCount(t){let e=0,n=t?t.path.clone():await this.first();if(t?.ascending??!0)for(;n.on;)e+=n.leafNode.entries.length-n.leafIndex,n.leafIndex=n.leafNode.entries.length-1,await this.internalNext(n);else for(;n.on;)e+=n.leafIndex+1,n.leafIndex=0,await this.internalPrior(n);return e}async next(t){let e=t.clone();return await this.moveNext(e),e}async moveNext(t){this.validatePath(t),await this.internalNext(t)}async prior(t){let e=t.clone();return this.movePrior(e),e}async movePrior(t){this.validatePath(t),await this.internalPrior(t)}keyFromPath(t){return this.keyFromEntry(t.leafNode.entries[t.leafIndex])}async*internalAscending(t){for(this.validatePath(t);t.on;)yield t,await this.moveNext(t)}async*internalDescending(t){for(this.validatePath(t);t.on;)yield t,await this.movePrior(t)}async findFirst(t){let e=await this.find(t.first.key);return(!e.on||t.first&&!t.first.inclusive)&&(t.isAscending?await this.internalNext(e):await this.internalPrior(e)),e}async findLast(t){let e=await this.find(t.last.key);return(!e.on||t.last&&!t.last.inclusive)&&(t.isAscending?await this.internalPrior(e):await this.internalNext(e)),e}async getPath(t,e){if(t.header.type===fe){let n=t,[o,s]=this.indexOfEntry(n.entries,e);return new ue([],n,s,o,this._version)}else{let n=t,o=this.indexOfKey(n.partitions,e),s=await this.getPath(await X(this.store,n.nodes[o]),e);return s.branches.unshift(new Bt(n,o)),s}}indexOfEntry(t,e){let n=0,o=t.length-1,s=0,i=-1;for(;n<=o;){if(s=n+o>>>1,i=this.compare(e,this.keyFromEntry(t[s])),i===0)return[!0,s];i<0?o=s-1:n=s+1}return[!1,n]}indexOfKey(t,e){let n=0,o=t.length-1,s=0,i=-1;for(;n<=o;){if(s=n+o>>>1,i=this.compare(e,t[s]),i===0)return s+1;i<0?o=s-1:n=s+1}return n}async internalNext(t){if(t.on)if(t.leafIndex>=t.leafNode.entries.length-1){let e=0,n=!1,o=t.branches.length-1;for(;e<=o&&!n;){let s=t.branches[o-e];s.index===s.node.partitions.length?++e:n=!0}if(!n)t.leafIndex=t.leafNode.entries.length,t.on=!1;else{t.branches.splice(-e,e);let s=t.branches.at(-1);++s.index,this.moveToFirst(await X(this.store,s.node.nodes[s.index]),t)}}else++t.leafIndex,t.on=!0;else if(t.on=t.branches.every(e=>e.index>=0&&e.index<e.node.nodes.length)&&t.leafIndex>=0&&t.leafIndex<t.leafNode.entries.length,t.on)return}async internalPrior(t){if(this.validatePath(t),t.leafIndex<=0){let e=0,n=!1,o=t.branches.length-1;for(;e<=o&&!n;)t.branches[o-e].index===0?++e:n=!0;if(!n)t.leafIndex=0,t.on=!1;else{t.branches.splice(-e,e);let s=t.branches.at(-1);--s.index,await this.moveToLast(await X(this.store,s.node.nodes[s.index]),t)}}else--t.leafIndex,t.on=!0}async internalUpdate(t,e){if(t.on){let n=this.keyFromPath(t),o=this.keyFromEntry(e);if(this.compare(n,o)!==0){let s=await this.internalInsert(e);return s.on&&(this.internalDelete(await this.find(n)),s=await this.find(o)),[s,!1]}else this.updateEntry(t,e)}return[t,!0]}async internalDelete(t){if(t.on){if(_(this.store,t.leafNode,[yt,t.leafIndex,1,[]]),t.branches.length>0){if(t.leafIndex===0&&t.leafNode.entries.length>0){let n=t.branches.at(-1);this.updatePartition(n.index,t,t.branches.length-1,this.keyFromPath(t))}let e=await this.rebalanceLeaf(t,t.branches.length);e&&await this.trunk.set(e)}return t.on=!1,!0}else return!1}async internalInsert(t){let e=await this.find(this.keyFromEntry(t));return e.on?(e.on=!1,e):(await this.internalInsertAt(e,t),e.on=!0,e)}async internalInsertAt(t,e){let n=this.leafInsert(t,e),o=t.branches.length-1;for(;n&&o>=0;)n=await this.branchInsert(t,o,n),--o;if(n){let s=ui(this.store,[n.key],[await this.trunk.getId(),n.right.header.id]);await this.store.insert(s),await this.trunk.set(s),t.branches.unshift(new Bt(s,n.indexDelta))}}async moveToFirst(t,e){if(t.header.type===fe){let n=t;e.leafNode=n,e.leafIndex=0,e.on=n.entries.length>0}else e.branches.push(new Bt(t,0)),await this.moveToFirst(await X(this.store,t.nodes[0]),e)}async moveToLast(t,e){if(t.header.type===fe){let n=t,o=n.entries.length;e.leafNode=n,e.on=o>0,e.leafIndex=o>0?o-1:0}else{let n=t,o=new Bt(n,n.partitions.length);e.branches.push(o),await this.moveToLast(await X(this.store,n.nodes[o.index]),e)}}async getFirst(t){if(t.header.type===fe){let e=t;return new ue([],e,0,e.entries.length>0,this._version)}else{let e=t,n=await this.getFirst(await X(this.store,e.nodes[0]));return n.branches.unshift(new Bt(e,0)),n}}async getLast(t){if(t.header.type===fe){let e=t,n=e.entries.length;return new ue([],e,n>0?n-1:0,n>0,this._version)}else{let e=t,n=e.nodes.length-1,o=await this.getLast(await X(this.store,e.nodes[n]));return o.branches.unshift(new Bt(e,n)),o}}leafInsert(t,e){let{leafNode:n,leafIndex:o}=t;if(n.entries.length<ft){_(this.store,n,[yt,o,0,[e]]);return}let s=n.entries.length+1>>>1,i=n.entries.slice(s);o>=s&&i.splice(o-s,0,e);let a=fi(this.store,i);return this.store.insert(a),_(this.store,n,[yt,s,n.entries.length-s,[]]),o<s?_(this.store,n,[yt,o,0,[e]]):(t.leafNode=a,t.leafIndex-=s),new $r(this.keyFromEntry(i[0]),a,o<s?0:1)}async branchInsert(t,e,n){let o=t.branches[e],{index:s,node:i}=o;if(o.index+=n.indexDelta,i.nodes.length<ft){_(this.store,i,[wt,s,0,[n.key]]),_(this.store,i,[zt,s+1,0,[n.right.header.id]]);return}let a=i.nodes.length+1>>>1,c=i.partitions.slice(a),f=i.nodes.slice(a),l=o.index<a?0:1;l&&(o.index-=a,c.splice(o.index,0,n.key),f.splice(o.index+1,0,n.right.header.id));let u=ui(this.store,c,f),h=i.partitions[a-1];return _(this.store,i,[wt,a-1,c.length+1,[]]),_(this.store,i,[zt,a,f.length,[]]),o.index<a&&(_(this.store,i,[wt,s,0,[n.key]]),_(this.store,i,[zt,s+1,0,[n.right.header.id]])),new $r(h,u,l)}async rebalanceLeaf(t,e){if(e===0||t.leafNode.entries.length>=ft>>>1)return;let n=t.leafNode,o=t.branches.at(e-1),s=o.index,i=o.node,a=i.nodes[s+1],c=a?await X(this.store,a):void 0;if(c&&c.entries.length>ft>>>1){let u=c.entries[0];_(this.store,c,[yt,0,1,[]]),_(this.store,n,[yt,n.entries.length,0,[u]]),this.updatePartition(s+1,t,e-1,this.keyFromEntry(u));return}let f=i.nodes[s-1],l=f?await X(this.store,f):void 0;if(l&&l.entries.length>ft>>>1){let u=l.entries[l.entries.length-1];_(this.store,l,[yt,l.entries.length-1,1,[]]),_(this.store,n,[yt,0,0,[u]]),this.updatePartition(s,t,e-1,this.keyFromEntry(u)),t.leafIndex+=1;return}if(c&&c.entries.length+n.entries.length<=ft)return _(this.store,n,[yt,n.entries.length,0,c.entries]),this.deletePartition(i,s),s===0&&this.updatePartition(s,t,e-1,this.keyFromEntry(n.entries[0])),this.store.delete(c.header.id),await this.rebalanceBranch(t,e-1);if(l&&l.entries.length+n.entries.length<=ft)return t.leafNode=l,t.leafIndex+=l.entries.length,_(this.store,l,[yt,l.entries.length,0,n.entries]),this.deletePartition(i,s-1),this.store.delete(n.header.id),await this.rebalanceBranch(t,e-1)}async rebalanceBranch(t,e){let n=t.branches[e],o=n.node;if(e===0&&o.partitions.length===0)return t.branches[e+1]?.node??t.leafNode;if(e===0||o.nodes.length>=ft>>>1)return;let s=t.branches.at(e-1),i=s.index,a=s.node,c=a.nodes[i+1],f=c?await X(this.store,c):void 0;if(f&&f.nodes.length>ft>>>1){let h=f.nodes[0],m=f.partitions[0];this.insertPartition(o,o.partitions.length,a.partitions[i],h),this.deletePartition(f,0,0),this.updatePartition(i+1,t,e-1,m);return}let l=a.nodes[i-1],u=l?await X(this.store,l):void 0;if(u&&u.nodes.length>ft>>>1){let h=u.nodes[u.nodes.length-1],m=u.partitions[u.partitions.length-1];this.insertPartition(o,0,a.partitions[i-1],h,0),this.deletePartition(u,u.partitions.length-1),n.index+=1,this.updatePartition(i,t,e-1,m);return}if(f&&f.nodes.length+o.nodes.length<=ft){let h=a.partitions[i];return this.deletePartition(a,i),_(this.store,o,[wt,o.partitions.length,0,[h]]),_(this.store,o,[wt,o.partitions.length,0,f.partitions]),_(this.store,o,[zt,o.nodes.length,0,f.nodes]),i===0&&a.partitions.length>0&&this.updatePartition(i,t,e-1,a.partitions[0]),this.store.delete(f.header.id),this.rebalanceBranch(t,e-1)}if(u&&u.nodes.length+o.nodes.length<=ft){let h=a.partitions[i-1];return this.deletePartition(a,i-1),_(this.store,u,[wt,u.partitions.length,0,[h]]),_(this.store,u,[wt,u.partitions.length,0,o.partitions]),_(this.store,u,[zt,u.nodes.length,0,o.nodes]),n.node=u,n.index+=u.nodes.length,this.store.delete(o.header.id),this.rebalanceBranch(t,e-1)}}updatePartition(t,e,n,o){let s=e.branches[n];t>0?_(this.store,s.node,[wt,t-1,1,[o]]):n!==0&&this.updatePartition(e.branches[n-1].index,e,n-1,o)}insertPartition(t,e,n,o,s=1){_(this.store,t,[wt,e,0,[n]]),_(this.store,t,[zt,e+s,0,[o]])}deletePartition(t,e,n=1){_(this.store,t,[wt,e,1,[]]),_(this.store,t,[zt,e+n,1,[]])}validatePath(t){if(!this.isValid(t))throw new Error("Path is invalid due to mutation of the tree")}async*nodeIds(t){if(t.header.type===Gn){let e=await Promise.all(t.nodes.map(n=>X(this.store,n)));for(let n of e)yield*this.nodeIds(n)}yield t.header.id}getEntry(t){return t.leafNode.entries[t.leafIndex]}updateEntry(t,e){_(this.store,t.leafNode,[yt,t.leafIndex,1,[e]])}},$r=class{key;right;indexDelta;constructor(t,e,n){this.key=t,this.right=e,this.indexDelta=n}};function fi(r,t){return{header:r.createBlockHeader(fe),entries:t}}function ui(r,t,e){return{header:r.createBlockHeader(Gn),partitions:t,nodes:e}}var Zn=class{key;inclusive;constructor(t,e=!0){this.key=t,this.inclusive=e}},Yn=class{first;last;isAscending;constructor(t,e,n=!0){this.first=t,this.last=e,this.isAscending=n}};var Xn=class extends jt{};var Bt=class r{node;index;constructor(t,e){this.node=t,this.index=e}clone(){return new r(this.node,this.index)}},ue=class r{branches;leafNode;leafIndex;on;version;constructor(t,e,n,o,s){this.branches=t,this.leafNode=e,this.leafIndex=n,this.on=o,this.version=s}isEqual(t){return this.leafNode===t.leafNode&&this.leafIndex===t.leafIndex&&this.on===t.on&&this.version===t.version}clone(){return new r(this.branches.map(t=>t.clone()),this.leafNode,this.leafIndex,this.on,this.version)}};var le=nt("entries"),li=nt("priorId"),Wn=nt("nextId"),Jn=bt("CHD","ChainDataBlock"),Qn=nt("headId"),zr=nt("tailId"),di=bt("CHH","ChainHeaderBlock");var to=32,Be=class r{store;id;options;constructor(t,e,n){this.store=t,this.id=e,this.options=n}static async create(t,e){let n=r.createTailBlock(t,e),o={...e?.createHeaderBlock?.(e?.newId)??{header:t.createBlockHeader(di,e?.newId)},headId:n.header.id,tailId:n.header.id};return t.insert(o),t.insert(n),new r(t,o.header.id,e)}static createTailBlock(t,e){return{...e?.createDataBlock?.()??{header:t.createBlockHeader(Jn)},entries:[],priorId:void 0,nextId:void 0}}static async open(t,e,n){let o=await t.tryGet(e);if(!o)return;let s=o;if(!Object.hasOwn(s,"headId")||!Object.hasOwn(s,"tailId")){let i=r.createTailBlock(t,n);t.insert(i),_(t,o,[Qn,0,0,i.header.id]),_(t,o,[zr,0,0,i.header.id])}return new r(t,e,n)}async add(...t){let e=await this.getTail();if(!e)throw new Error("Cannot add to non-existent chain");let{headerBlock:n,block:o}=e,s=o,i=new Ut(this.store),a=t.slice(0,to-s.entries.length);for(a.length>0&&(_(i,s,[le,s.entries.length,0,a]),t=t.slice(a.length));t.length>0;){let c={...this.options?.createDataBlock?.()??{header:this.store.createBlockHeader(Jn)},entries:t.splice(0,Math.min(to,t.length)),priorId:s.header.id,nextId:void 0};await this.options?.newBlock?.(c,o),i.insert(c),_(i,s,[Wn,0,0,c.header.id]),s=c}return s!==o&&_(i,n,[zr,0,0,s.header.id]),i.commit(),{headerBlock:n,block:s,index:s.entries.length-1}}updateAt(t,e){if(!hi(t))throw new Error("Invalid path");let{index:n,block:o}=t;_(this.store,o,[le,n,1,[e]])}async pop(t=1){if(t<=0)return[];let e=await this.getTail();if(!e)return[];let{headerBlock:n,block:o}=e,s=o,i=[],a=new Ut(this.store);for(;t>0;)if(s.entries.length>t){let c=s.entries.slice(-t);i.unshift(...c),_(a,s,[le,s.entries.length-t,t,[]]);break}else if(i.unshift(...s.entries),t-=s.entries.length,s.priorId)a.delete(s.header.id),s=await a.tryGet(s.priorId),_(a,s,[Wn,0,0,void 0]);else{_(a,s,[le,0,s.entries.length,[]]);break}return s!==o&&_(a,n,[zr,0,0,s.header.id]),a.commit(),i}async dequeue(t=1){if(t<=0)return[];let e=new Ut(this.store),n=await this.getHead();if(!n)return[];let{headerBlock:o,block:s}=n,i=s,a=[];for(;t>0;)if(i.entries.length>t){a.push(...i.entries.slice(0,t)),_(e,i,[le,0,t,[]]);break}else if(a.push(...i.entries),t-=i.entries.length,i.nextId)e.delete(i.header.id),i=await e.tryGet(i.nextId),_(e,i,[li,0,0,void 0]);else{_(e,i,[le,0,i.entries.length,[]]);break}return i!==s&&_(e,o,[Qn,0,0,i.header.id]),e.commit(),a}async*select(t,e=!0){let n=t??(e?await this.getHead():await this.getTail());if(!n)return;let o=n.block,s=n.index;if(e)for(;o;){for(;s<o.entries.length;++s)yield{headerBlock:n.headerBlock,block:o,index:s};o=o.nextId?await this.store.tryGet(o.nextId):void 0,s=0}else for(;o;){for(;s>=0;--s)yield{headerBlock:n.headerBlock,block:o,index:s};o=o.priorId?await this.store.tryGet(o.priorId):void 0,s=(o?.entries.length??0)-1}}async next(t){let{headerBlock:e,block:n,index:o}=t;return o<n.entries.length-1||!n.nextId?{headerBlock:e,block:n,index:o+1}:{headerBlock:e,block:await this.store.tryGet(n.nextId),index:0}}async prev(t){let{headerBlock:e,block:n,index:o}=t;if(o>0||!n.priorId)return{headerBlock:e,block:n,index:o-1};let s=await this.store.tryGet(n.priorId);return{headerBlock:e,block:s,index:s.entries.length-1}}async getTail(t){let e=t??await this.getHeader(),n=e?await this.store.tryGet(e.tailId):void 0;for(;n?.nextId;)n=await this.store.tryGet(n.nextId);return n?{headerBlock:e,block:n,index:n.entries.length-1}:void 0}async getHead(t){let e=t??await this.getHeader(),n=e?await this.store.tryGet(e.headId):void 0;for(;n?.priorId;)n=await this.store.tryGet(n.priorId);return n?{headerBlock:e,block:n,index:0}:void 0}async getHeader(){return await this.store.tryGet(this.id)}};function hi(r){return r.block.entries.length>r.index&&r.index>=0}function de(r){return r.block.entries[r.index]}var ir=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},jr=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var pi={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new jr("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Gr=pi;var gt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Zr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Yr=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Xr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var ar=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var eo=Symbol.for("@libp2p/peer-id");var cp=new Uint8Array(0);function mi(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Gt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function lf(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,b=0,p=0,S=d.length;p!==S&&d[p]===0;)p++,g++;for(var y=(S-p)*l+1>>>0,A=new Uint8Array(y);p!==S;){for(var k=d[p],N=0,C=y-1;(k!==0||N<b)&&C!==-1;C--,N++)k+=256*A[C]>>>0,A[C]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");b=N,p++}for(var E=y-b;E!==y&&A[E]===0;)E++;for(var I=c.repeat(g);E<y;++E)I+=r.charAt(A[E]);return I}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var b=0,p=0;d[g]===c;)b++,g++;for(var S=(d.length-g)*f+1>>>0,y=new Uint8Array(S);d[g];){var A=e[d.charCodeAt(g)];if(A===255)return;for(var k=0,N=S-1;(A!==0||k<p)&&N!==-1;N--,k++)A+=a*y[N]>>>0,y[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=k,g++}if(d[g]!==" "){for(var C=S-p;C!==S&&y[C]===0;)C++;for(var E=new Uint8Array(b+(S-C)),I=b;C!==S;)E[I++]=y[C++];return E}}}function m(d){var g=h(d);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:h,decode:m}}var df=lf,hf=df,yi=hf;var ro=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},no=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return gi(this,t)}},oo=class{decoders;constructor(t){this.decoders=t}or(t){return gi(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function gi(r,t){return new oo({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var so=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new ro(t,e,n),this.decoder=new no(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function xi({name:r,prefix:t,encode:e,decode:n}){return new so(r,t,e,n)}function ke({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=yi(e,r);return xi({prefix:t,name:r,encode:n,decode:s=>Gt(o(s))})}function pf(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=t[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function mf(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function yf(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function kt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=yf(n);return xi({prefix:t,name:r,encode(s){return mf(s,n,e)},decode(s){return pf(s,o,e,r)}})}var ot=ke({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),mp=ke({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var cr=kt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),xp=kt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),bp=kt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),wp=kt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ep=kt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vp=kt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ip=kt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Sp=kt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ap=kt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Wr=ke({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Cp=ke({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gf=Ei,bi=128,xf=127,bf=~xf,wf=Math.pow(2,31);function Ei(r,t,e){t=t||[],e=e||0;for(var n=e;r>=wf;)t[e++]=r&255|bi,r/=128;for(;r&bf;)t[e++]=r&255|bi,r>>>=7;return t[e]=r|0,Ei.bytes=e-n+1,t}var Ef=io,vf=128,wi=127;function io(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw io.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&wi)<<o:(i&wi)*Math.pow(2,o),o+=7}while(i>=vf);return io.bytes=s-n,e}var If=Math.pow(2,7),Sf=Math.pow(2,14),Af=Math.pow(2,21),Bf=Math.pow(2,28),kf=Math.pow(2,35),Cf=Math.pow(2,42),Df=Math.pow(2,49),Tf=Math.pow(2,56),Lf=Math.pow(2,63),Nf=function(r){return r<If?1:r<Sf?2:r<Af?3:r<Bf?4:r<kf?5:r<Cf?6:r<Df?7:r<Tf?8:r<Lf?9:10},Uf={encode:gf,decode:Ef,encodingLength:Nf},Of=Uf,fr=Of;function ur(r,t=0){return[fr.decode(r,t),fr.decode.bytes]}function Ce(r,t,e=0){return fr.encode(r,t,e),t}function De(r){return fr.encodingLength(r)}function Le(r,t){let e=t.byteLength,n=De(r),o=n+De(e),s=new Uint8Array(o+e);return Ce(r,s,0),Ce(e,s,n),s.set(t,o),new Te(r,e,t,s)}function Ii(r){let t=Gt(r),[e,n]=ur(t),[o,s]=ur(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Te(e,o,i,t)}function Si(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&mi(r.bytes,e.bytes)}}var Te=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Ai(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return _f(e,co(r),t??ot.encoder);default:return Pf(e,co(r),t??cr.encoder)}}var Bi=new WeakMap;function co(r){let t=Bi.get(r);if(t==null){let e=new Map;return Bi.set(r,e),e}return t}var Zt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==lr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Mf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Le(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Si(t.multihash,n.multihash)}toString(t){return Ai(this,t)}toJSON(){return{"/":Ai(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??ki(n,o,s.bytes))}else if(e[Kf]===!0){let{version:n,multihash:o,code:s}=e,i=Ii(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==lr)throw new Error(`Version 0 CID must use dag-pb (code: ${lr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=ki(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,lr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Gt(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Te(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,h]=ur(t.subarray(e));return e+=h,u},o=n(),s=lr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),f=e+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(t,e){let[n,o]=Rf(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return co(s).set(n,t),s}};function Rf(r,t){switch(r[0]){case"Q":{let e=t??ot;return[ot.prefix,e.decode(`${ot.prefix}${r}`)]}case ot.prefix:{let e=t??ot;return[ot.prefix,e.decode(r)]}case cr.prefix:{let e=t??cr;return[cr.prefix,e.decode(r)]}case Wr.prefix:{let e=t??Wr;return[Wr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function _f(r,t,e){let{prefix:n}=e;if(n!==ot.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Pf(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var lr=112,Mf=18;function ki(r,t,e){let n=De(r),o=n+De(t),s=new Uint8Array(o+e.byteLength);return Ce(r,s,0),Ce(t,s,n),s.set(e,o),s}var Kf=Symbol.for("@ipld/js-cid/CID");var Ci=0,qf="identity",Di=Gt;function Hf(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Le(Ci,Di(r))}var Ne={code:Ci,name:qf,encode:Di,digest:Hf};function Et(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ot(r=0){return new Uint8Array(r)}function ut(r=0){return new Uint8Array(r)}function Jr(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=ut(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Li=Symbol.for("@achingbrain/uint8arraylist");function Ti(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Qr(r){return!!r?.[Li]}var lt=class r{bufs;length;[Li]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Qr(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Qr(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Ti(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ti(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Qr(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Jr(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Jr(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let f=t>=a&&t<c,l=e>a&&e<=c;if(f&&l){if(t===a&&e===c){n.push(i);break}let u=t-a;n.push(i.subarray(u,u+(e-t)));break}if(f){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(l){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Qr(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,l;for(let u=e;u<=c;u+=l){l=0;for(let h=f;h>=0;h--){let m=this.get(u+h);if(n[h]!==m){l=Math.max(1,h-a[m]);break}}if(l===0)return u}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=ut(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=Ot(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=Ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=Ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=ut(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=Ot(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=Ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=Ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=Ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=Ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Et(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var po={};at(po,{base10:()=>Zf});var Jp=new Uint8Array(0);function Ni(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Rt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Ui(r){return new TextEncoder().encode(r)}function Oi(r){return new TextDecoder().decode(r)}function Vf(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,b=0,p=0,S=d.length;p!==S&&d[p]===0;)p++,g++;for(var y=(S-p)*l+1>>>0,A=new Uint8Array(y);p!==S;){for(var k=d[p],N=0,C=y-1;(k!==0||N<b)&&C!==-1;C--,N++)k+=256*A[C]>>>0,A[C]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");b=N,p++}for(var E=y-b;E!==y&&A[E]===0;)E++;for(var I=c.repeat(g);E<y;++E)I+=r.charAt(A[E]);return I}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var b=0,p=0;d[g]===c;)b++,g++;for(var S=(d.length-g)*f+1>>>0,y=new Uint8Array(S);d[g];){var A=e[d.charCodeAt(g)];if(A===255)return;for(var k=0,N=S-1;(A!==0||k<p)&&N!==-1;N--,k++)A+=a*y[N]>>>0,y[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=k,g++}if(d[g]!==" "){for(var C=S-p;C!==S&&y[C]===0;)C++;for(var E=new Uint8Array(b+(S-C)),I=b;C!==S;)E[I++]=y[C++];return E}}}function m(d){var g=h(d);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:h,decode:m}}var Ff=Vf,$f=Ff,_i=$f;var fo=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},uo=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Pi(this,t)}},lo=class{decoders;constructor(t){this.decoders=t}or(t){return Pi(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Pi(r,t){return new lo({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ho=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new fo(t,e,n),this.decoder=new uo(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ue({name:r,prefix:t,encode:e,decode:n}){return new ho(r,t,e,n)}function Yt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=_i(e,r);return Ue({prefix:t,name:r,encode:n,decode:s=>Rt(o(s))})}function zf(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=t[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function jf(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function Gf(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function G({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Gf(n);return Ue({prefix:t,name:r,encode(s){return jf(s,n,e)},decode(s){return zf(s,o,e,r)}})}var Zf=Yt({prefix:"9",name:"base10",alphabet:"0123456789"});var mo={};at(mo,{base16:()=>Yf,base16upper:()=>Xf});var Yf=G({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xf=G({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var yo={};at(yo,{base2:()=>Wf});var Wf=G({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var go={};at(go,{base256emoji:()=>ru});var Mi=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Jf=Mi.reduce((r,t,e)=>(r[e]=t,r),[]),Qf=Mi.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function tu(r){return r.reduce((t,e)=>(t+=Jf[e],t),"")}function eu(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Qf[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var ru=Ue({prefix:"\u{1F680}",name:"base256emoji",encode:tu,decode:eu});var xo={};at(xo,{base32:()=>Oe,base32hex:()=>iu,base32hexpad:()=>cu,base32hexpadupper:()=>fu,base32hexupper:()=>au,base32pad:()=>ou,base32padupper:()=>su,base32upper:()=>nu,base32z:()=>uu});var Oe=G({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),nu=G({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ou=G({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),su=G({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),iu=G({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),au=G({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cu=G({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),fu=G({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),uu=G({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var bo={};at(bo,{base36:()=>dr,base36upper:()=>lu});var dr=Yt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),lu=Yt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var wo={};at(wo,{base58btc:()=>Ct,base58flickr:()=>du});var Ct=Yt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),du=Yt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Eo={};at(Eo,{base64:()=>hu,base64pad:()=>pu,base64url:()=>mu,base64urlpad:()=>yu});var hu=G({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),pu=G({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),mu=G({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),yu=G({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var vo={};at(vo,{base8:()=>gu});var gu=G({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Io={};at(Io,{identity:()=>xu});var xu=Ue({prefix:"\0",name:"identity",encode:r=>Oi(r),decode:r=>Ui(r)});var p0=new TextEncoder,m0=new TextDecoder;var Ao={};at(Ao,{identity:()=>Hu});var Eu=Hi,Ki=128,vu=127,Iu=~vu,Su=Math.pow(2,31);function Hi(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Su;)t[e++]=r&255|Ki,r/=128;for(;r&Iu;)t[e++]=r&255|Ki,r>>>=7;return t[e]=r|0,Hi.bytes=e-n+1,t}var Au=So,Bu=128,qi=127;function So(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw So.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&qi)<<o:(i&qi)*Math.pow(2,o),o+=7}while(i>=Bu);return So.bytes=s-n,e}var ku=Math.pow(2,7),Cu=Math.pow(2,14),Du=Math.pow(2,21),Tu=Math.pow(2,28),Lu=Math.pow(2,35),Nu=Math.pow(2,42),Uu=Math.pow(2,49),Ou=Math.pow(2,56),Ru=Math.pow(2,63),_u=function(r){return r<ku?1:r<Cu?2:r<Du?3:r<Tu?4:r<Lu?5:r<Nu?6:r<Uu?7:r<Ou?8:r<Ru?9:10},Pu={encode:Eu,decode:Au,encodingLength:_u},Mu=Pu,hr=Mu;function pr(r,t=0){return[hr.decode(r,t),hr.decode.bytes]}function Re(r,t,e=0){return hr.encode(r,t,e),t}function _e(r){return hr.encodingLength(r)}function Me(r,t){let e=t.byteLength,n=_e(r),o=n+_e(e),s=new Uint8Array(o+e);return Re(r,s,0),Re(e,s,n),s.set(t,o),new Pe(r,e,t,s)}function Vi(r){let t=Rt(r),[e,n]=pr(t),[o,s]=pr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Pe(e,o,i,t)}function Fi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Ni(r.bytes,e.bytes)}}var Pe=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var $i=0,Ku="identity",zi=Rt;function qu(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Me($i,zi(r))}var Hu={code:$i,name:Ku,encode:zi,digest:qu};var Co={};at(Co,{sha256:()=>Fu,sha512:()=>$u});var Vu=20;function ko({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new Bo(r,t,e,n,o)}var Bo=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??Vu,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?ji(n,this.code,e?.truncate):n.then(o=>ji(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function ji(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Me(t,r)}function Zi(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Fu=ko({name:"sha2-256",code:18,encode:Zi("SHA-256")}),$u=ko({name:"sha2-512",code:19,encode:Zi("SHA-512")});function Yi(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return ju(e,Do(r),t??Ct.encoder);default:return Gu(e,Do(r),t??Oe.encoder)}}var Xi=new WeakMap;function Do(r){let t=Xi.get(r);if(t==null){let e=new Map;return Xi.set(r,e),e}return t}var en=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==yr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Zu)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Me(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Fi(t.multihash,n.multihash)}toString(t){return Yi(this,t)}toJSON(){return{"/":Yi(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Wi(n,o,s.bytes))}else if(e[Yu]===!0){let{version:n,multihash:o,code:s}=e,i=Vi(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==yr)throw new Error(`Version 0 CID must use dag-pb (code: ${yr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Wi(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,yr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Rt(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Pe(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,h]=pr(t.subarray(e));return e+=h,u},o=n(),s=yr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),f=e+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(t,e){let[n,o]=zu(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Do(s).set(n,t),s}};function zu(r,t){switch(r[0]){case"Q":{let e=t??Ct;return[Ct.prefix,e.decode(`${Ct.prefix}${r}`)]}case Ct.prefix:{let e=t??Ct;return[Ct.prefix,e.decode(r)]}case Oe.prefix:{let e=t??Oe;return[Oe.prefix,e.decode(r)]}case dr.prefix:{let e=t??dr;return[dr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function ju(r,t,e){let{prefix:n}=e;if(n!==Ct.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Gu(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var yr=112,Zu=18;function Wi(r,t,e){let n=_e(r),o=n+_e(t),s=new Uint8Array(o+e.byteLength);return Re(r,s,0),Re(t,s,n),s.set(e,o),s}var Yu=Symbol.for("@ipld/js-cid/CID");var To={...Io,...yo,...vo,...po,...mo,...xo,...bo,...wo,...Eo,...go},P0={...Co,...Ao};function Qi(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ji=Qi("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Lo=Qi("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=ut(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Xu={utf8:Ji,"utf-8":Ji,hex:To.base16,latin1:Lo,ascii:Lo,binary:Lo,...To},rn=Xu;function Xt(r,t="utf8"){let e=rn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Y(r,t="utf8"){let e=rn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Wu=parseInt("11111",2),No=parseInt("10000000",2),Ju=parseInt("01111111",2),ta={0:gr,1:gr,2:Qu,3:rl,4:nl,5:el,6:tl,16:gr,22:gr,48:gr};function Uo(r,t={offset:0}){let e=r[t.offset]&Wu;if(t.offset++,ta[e]!=null)return ta[e](r,t);throw new Error("No decoder for tag "+e)}function xr(r,t){let e=0;if((r[t.offset]&No)===No){let n=r[t.offset]&Ju,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function gr(r,t){xr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=Uo(r,t);if(n===null)break;e.push(n)}return e}function Qu(r,t){let e=xr(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function tl(r,t){let e=xr(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let f=r[t.offset];if(t.offset++,c.push(f&127),f<128){c.reverse();let l=0;for(let u=0;u<c.length;u++)l+=c[u]<<u*7;a+=`.${l}`,c=[]}}return a}function el(r,t){return t.offset++,null}function rl(r,t){let e=xr(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function nl(r,t){let e=xr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function ol(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new lt;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Oo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=ol(r.byteLength);return new lt(Uint8Array.from([t.byteLength|No]),t)}function ea(r){let t=new lt,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new lt(Uint8Array.from([2]),Oo(t),t)}function ra(r){let t=Uint8Array.from([0]),e=new lt(t,r);return new lt(Uint8Array.from([3]),Oo(e),e)}function nn(r,t=48){let e=new lt;for(let n of r)e.append(n);return new lt(Uint8Array.from([t]),Oo(e),e)}async function na(r,t,e,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,e.subarray());return n?.signal?.throwIfAborted(),s}var sl=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),il=Uint8Array.from([6,5,43,129,4,0,34]),al=Uint8Array.from([6,5,43,129,4,0,35]),cl={ext:!0,kty:"EC",crv:"P-256"},fl={ext:!0,kty:"EC",crv:"P-384"},ul={ext:!0,kty:"EC",crv:"P-521"},Ro=32,_o=48,Po=66;function oa(r){let t=Uo(r);return sa(t)}function sa(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Ro*2+1)return n=Y(t.subarray(e,e+Ro),"base64url"),o=Y(t.subarray(e+Ro),"base64url"),new Ke({...cl,key_ops:["verify"],x:n,y:o});if(t.byteLength===_o*2+1)return n=Y(t.subarray(e,e+_o),"base64url"),o=Y(t.subarray(e+_o),"base64url"),new Ke({...fl,key_ops:["verify"],x:n,y:o});if(t.byteLength===Po*2+1)return n=Y(t.subarray(e,e+Po),"base64url"),o=Y(t.subarray(e+Po),"base64url"),new Ke({...ul,key_ops:["verify"],x:n,y:o});throw new gt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function ia(r){return nn([ea(Uint8Array.from([1])),nn([ll(r.crv)],160),nn([ra(new lt(Uint8Array.from([4]),Xt(r.x??"","base64url"),Xt(r.y??"","base64url")))],161)]).subarray()}function ll(r){if(r==="P-256")return sl;if(r==="P-384")return il;if(r==="P-521")return al;throw new gt(`Invalid curve ${r}`)}var Ke=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=ia(this.jwk)),this._raw}toMultihash(){return Ne.digest(qe(this))}toCID(){return Zt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}async verify(t,e,n){return na(this.jwk,e,t,n)}};function he(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Dt(r,t=""){if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new Error(`${e}expected integer >= 0, got ${r}`)}}function K(r,t,e=""){let n=he(r),o=r?.length,s=t!==void 0;if(!n||s&&o!==t){let i=e&&`"${e}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function on(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Dt(r.outputLen),Dt(r.blockLen)}function He(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function ca(r,t){K(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new Error('"digestInto() output" expected to be of length >='+e)}function Pt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function sn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function vt(r,t){return r<<32-t|r>>>t}var fa=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",dl=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Mt(r){if(K(r),fa)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=dl[r[e]];return t}var _t={_0:48,_9:57,A:65,F:70,a:97,f:102};function aa(r){if(r>=_t._0&&r<=_t._9)return r-_t._0;if(r>=_t.A&&r<=_t.F)return r-(_t.A-10);if(r>=_t.a&&r<=_t.f)return r-(_t.a-10)}function Kt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(fa)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=aa(r.charCodeAt(s)),a=aa(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function ct(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];K(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function Mo(r,t={}){let e=(o,s)=>r(s).update(o).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=o=>r(o),Object.assign(e,t),Object.freeze(e)}function Wt(r=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(r))}var Ko=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function ua(r,t,e){return r&t^~r&e}function la(r,t,e){return r&t^r&e^t&e}var br=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,o){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=sn(this.buffer)}update(t){He(this),K(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=sn(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){He(this),ca(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,Pt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)e[u]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=sn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,l=this.get();if(f>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<f;u++)a.setUint32(4*u,l[u],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},qt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var tt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var an=BigInt(4294967295),da=BigInt(32);function hl(r,t=!1){return t?{h:Number(r&an),l:Number(r>>da&an)}:{h:Number(r>>da&an)|0,l:Number(r&an)|0}}function ha(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=hl(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var qo=(r,t,e)=>r>>>e,Ho=(r,t,e)=>r<<32-e|t>>>e,pe=(r,t,e)=>r>>>e|t<<32-e,me=(r,t,e)=>r<<32-e|t>>>e,wr=(r,t,e)=>r<<64-e|t>>>e-32,Er=(r,t,e)=>r>>>e-32|t<<64-e;function Tt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var pa=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),ma=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,ya=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),ga=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,xa=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),ba=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var ml=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jt=new Uint32Array(64),Vo=class extends br{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let u=0;u<16;u++,e+=4)Jt[u]=t.getUint32(e,!1);for(let u=16;u<64;u++){let h=Jt[u-15],m=Jt[u-2],d=vt(h,7)^vt(h,18)^h>>>3,g=vt(m,17)^vt(m,19)^m>>>10;Jt[u]=g+Jt[u-7]+d+Jt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:l}=this;for(let u=0;u<64;u++){let h=vt(a,6)^vt(a,11)^vt(a,25),m=l+h+ua(a,c,f)+ml[u]+Jt[u]|0,g=(vt(n,2)^vt(n,13)^vt(n,22))+la(n,o,s)|0;l=f,f=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,f,l)}roundClean(){Pt(Jt)}destroy(){this.set(0,0,0,0,0,0,0,0),Pt(this.buffer)}},Fo=class extends Vo{A=qt[0]|0;B=qt[1]|0;C=qt[2]|0;D=qt[3]|0;E=qt[4]|0;F=qt[5]|0;G=qt[6]|0;H=qt[7]|0;constructor(){super(32)}};var wa=ha(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),yl=wa[0],gl=wa[1],Qt=new Uint32Array(80),te=new Uint32Array(80),$o=class extends br{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:l,Fh:u,Fl:h,Gh:m,Gl:d,Hh:g,Hl:b}=this;return[t,e,n,o,s,i,a,c,f,l,u,h,m,d,g,b]}set(t,e,n,o,s,i,a,c,f,l,u,h,m,d,g,b){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=l|0,this.Fh=u|0,this.Fl=h|0,this.Gh=m|0,this.Gl=d|0,this.Hh=g|0,this.Hl=b|0}process(t,e){for(let y=0;y<16;y++,e+=4)Qt[y]=t.getUint32(e),te[y]=t.getUint32(e+=4);for(let y=16;y<80;y++){let A=Qt[y-15]|0,k=te[y-15]|0,N=pe(A,k,1)^pe(A,k,8)^qo(A,k,7),C=me(A,k,1)^me(A,k,8)^Ho(A,k,7),E=Qt[y-2]|0,I=te[y-2]|0,P=pe(E,I,19)^wr(E,I,61)^qo(E,I,6),q=me(E,I,19)^Er(E,I,61)^Ho(E,I,6),U=ya(C,q,te[y-7],te[y-16]),w=ga(U,N,P,Qt[y-7],Qt[y-16]);Qt[y]=w|0,te[y]=U|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:l,Eh:u,El:h,Fh:m,Fl:d,Gh:g,Gl:b,Hh:p,Hl:S}=this;for(let y=0;y<80;y++){let A=pe(u,h,14)^pe(u,h,18)^wr(u,h,41),k=me(u,h,14)^me(u,h,18)^Er(u,h,41),N=u&m^~u&g,C=h&d^~h&b,E=xa(S,k,C,gl[y],te[y]),I=ba(E,p,A,N,yl[y],Qt[y]),P=E|0,q=pe(n,o,28)^wr(n,o,34)^wr(n,o,39),U=me(n,o,28)^Er(n,o,34)^Er(n,o,39),w=n&s^n&a^s&a,v=o&i^o&c^i&c;p=g|0,S=b|0,g=m|0,b=d|0,m=u|0,d=h|0,{h:u,l:h}=Tt(f|0,l|0,I|0,P|0),f=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let x=pa(P,U,v);n=ma(x,I,q,w),o=x|0}({h:n,l:o}=Tt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Tt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Tt(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l}=Tt(this.Dh|0,this.Dl|0,f|0,l|0),{h:u,l:h}=Tt(this.Eh|0,this.El|0,u|0,h|0),{h:m,l:d}=Tt(this.Fh|0,this.Fl|0,m|0,d|0),{h:g,l:b}=Tt(this.Gh|0,this.Gl|0,g|0,b|0),{h:p,l:S}=Tt(this.Hh|0,this.Hl|0,p|0,S|0),this.set(n,o,s,i,a,c,f,l,u,h,m,d,g,b,p,S)}roundClean(){Pt(Qt,te)}destroy(){Pt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},zo=class extends $o{Ah=tt[0]|0;Al=tt[1]|0;Bh=tt[2]|0;Bl=tt[3]|0;Ch=tt[4]|0;Cl=tt[5]|0;Dh=tt[6]|0;Dl=tt[7]|0;Eh=tt[8]|0;El=tt[9]|0;Fh=tt[10]|0;Fl=tt[11]|0;Gh=tt[12]|0;Gl=tt[13]|0;Hh=tt[14]|0;Hl=tt[15]|0;constructor(){super(64)}};var Ea=Mo(()=>new Fo,Ko(1));var va=Mo(()=>new zo,Ko(3));var Go=BigInt(0),jo=BigInt(1);function Ht(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function Ia(r){if(typeof r=="bigint"){if(!cn(r))throw new Error("positive bigint expected, got "+r)}else Dt(r);return r}function vr(r){let t=Ia(r).toString(16);return t.length&1?"0"+t:t}function Sa(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Go:BigInt("0x"+r)}function Ve(r){return Sa(Mt(r))}function ye(r){return Sa(Mt(un(K(r)).reverse()))}function fn(r,t){Dt(t),r=Ia(r);let e=Kt(r.toString(16).padStart(t*2,"0"));if(e.length!==t)throw new Error("number too large");return e}function Zo(r,t){return fn(r,t).reverse()}function un(r){return Uint8Array.from(r)}var cn=r=>typeof r=="bigint"&&Go<=r;function xl(r,t,e){return cn(r)&&cn(t)&&cn(e)&&t<=r&&r<e}function Ir(r,t,e,n){if(!xl(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Yo(r){let t;for(t=0;r>Go;r>>=jo,t+=1);return t}var Sr=r=>(jo<<BigInt(r))-jo;function Aa(r,t,e){if(Dt(r,"hashLen"),Dt(t,"qByteLen"),typeof e!="function")throw new Error("hmacFn must be a function");let n=b=>new Uint8Array(b),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),f=n(r),l=0,u=()=>{c.fill(1),f.fill(0),l=0},h=(...b)=>e(f,ct(c,...b)),m=(b=o)=>{f=h(s,b),c=h(),b.length!==0&&(f=h(i,b),c=h())},d=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,p=[];for(;b<t;){c=h();let S=c.slice();p.push(S),b+=c.length}return ct(...p)};return(b,p)=>{u(),m(b);let S;for(;!(S=p(d()));)m();return u(),S}}function ee(r,t={},e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(t,!1),o(e,!0)}function Fe(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var st=BigInt(0),W=BigInt(1),ge=BigInt(2),Ca=BigInt(3),Da=BigInt(4),Ta=BigInt(5),bl=BigInt(7),La=BigInt(8),wl=BigInt(9),Na=BigInt(16);function Z(r,t){let e=r%t;return e>=st?e:t+e}function F(r,t,e){let n=r;for(;t-- >st;)n*=n,n%=e;return n}function Ba(r,t){if(r===st)throw new Error("invert: expected non-zero number");if(t<=st)throw new Error("invert: expected positive modulus, got "+t);let e=Z(r,t),n=t,o=st,s=W,i=W,a=st;for(;e!==st;){let f=n/e,l=n%e,u=o-i*f,h=s-a*f;n=e,e=l,o=i,s=a,i=u,a=h}if(n!==W)throw new Error("invert: does not exist");return Z(o,t)}function Wo(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function Ua(r,t){let e=(r.ORDER+W)/Da,n=r.pow(t,e);return Wo(r,n,t),n}function El(r,t){let e=(r.ORDER-Ta)/La,n=r.mul(t,ge),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,ge),o),a=r.mul(s,r.sub(i,r.ONE));return Wo(r,a,t),a}function vl(r){let t=$e(r),e=Oa(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+bl)/Na;return(a,c)=>{let f=a.pow(c,i),l=a.mul(f,n),u=a.mul(f,o),h=a.mul(f,s),m=a.eql(a.sqr(l),c),d=a.eql(a.sqr(u),c);f=a.cmov(f,l,m),l=a.cmov(h,u,d);let g=a.eql(a.sqr(l),c),b=a.cmov(f,l,g);return Wo(a,b,c),b}}function Oa(r){if(r<Ca)throw new Error("sqrt is not defined for small field");let t=r-W,e=0;for(;t%ge===st;)t/=ge,e++;let n=ge,o=$e(r);for(;ka(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Ua;let s=o.pow(n,t),i=(t+W)/ge;return function(c,f){if(c.is0(f))return f;if(ka(c,f)!==1)throw new Error("Cannot find square root");let l=e,u=c.mul(c.ONE,s),h=c.pow(f,t),m=c.pow(f,i);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let d=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(d++,g=c.sqr(g),d===l)throw new Error("Cannot find square root");let b=W<<BigInt(l-d-1),p=c.pow(u,b);l=d,u=c.sqr(p),h=c.mul(h,u),m=c.mul(m,p)}return m}}function Il(r){return r%Da===Ca?Ua:r%La===Ta?El:r%Na===wl?vl(r):Oa(r)}var Ra=(r,t)=>(Z(r,t)&W)===W,Sl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Jo(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=Sl.reduce((n,o)=>(n[o]="function",n),t);return ee(r,e),r}function Al(r,t,e){if(e<st)throw new Error("invalid exponent, negatives unsupported");if(e===st)return r.ONE;if(e===W)return t;let n=r.ONE,o=t;for(;e>st;)e&W&&(n=r.mul(n,o)),o=r.sqr(o),e>>=W;return n}function Ar(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function ka(r,t){let e=(r.ORDER-W)/ge,n=r.pow(t,e),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Bl(r,t){t!==void 0&&Dt(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}var Xo=class{ORDER;BITS;BYTES;isLE;ZERO=st;ONE=W;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=st)throw new Error("invalid field: expected ORDER > 0, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&(this.sqrt=e.sqrt),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=e.allowedLengths?.slice()),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:o,nByteLength:s}=Bl(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return Z(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return st<=t&&t<this.ORDER}is0(t){return t===st}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&W)===W}neg(t){return Z(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return Z(t*t,this.ORDER)}add(t,e){return Z(t+e,this.ORDER)}sub(t,e){return Z(t-e,this.ORDER)}mul(t,e){return Z(t*e,this.ORDER)}pow(t,e){return Al(this,t,e)}div(t,e){return Z(t*Ba(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return Ba(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=Il(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?Zo(t,this.BYTES):fn(t,this.BYTES)}fromBytes(t,e=!1){K(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let f=new Uint8Array(o);f.set(t,s?0:f.length-t.length),t=f}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?ye(t):Ve(t);if(a&&(c=Z(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Ar(this,t)}cmov(t,e,n){return n?e:t}};function $e(r,t={}){return new Xo(r,t)}function _a(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Qo(r){let t=_a(r);return t+Math.ceil(t/2)}function ts(r,t,e=!1){K(r);let n=r.length,o=_a(t),s=Qo(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?ye(r):Ve(r),a=Z(i,t-W)+W;return e?Zo(a,o):fn(a,o)}var ze=BigInt(0),xe=BigInt(1);function Br(r,t){let e=t.negate();return r?e:t}function be(r,t){let e=Ar(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function qa(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function es(r,t){qa(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=Sr(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Pa(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=xe);let f=t*n,l=f+Math.abs(a)-1,u=a===0,h=a<0,m=t%2!==0;return{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:m,offsetF:f}}var rs=new WeakMap,Ha=new WeakMap;function ns(r){return Ha.get(r)||1}function Ma(r){if(r!==ze)throw new Error("invalid wNAF")}var je=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>ze;)e&xe&&(n=n.add(o)),o=o.double(),e>>=xe;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=es(e,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=es(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:l,isNeg:u,isNegF:h,offsetF:m}=Pa(n,a,i);n=c,l?s=s.add(Br(h,e[m])):o=o.add(Br(u,e[f]))}return Ma(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=es(t,this.bits);for(let i=0;i<s.windows&&n!==ze;i++){let{nextN:a,offset:c,isZero:f,isNeg:l}=Pa(n,i,s);if(n=a,!f){let u=e[c];o=o.add(l?u.negate():u)}}return Ma(n),o}getPrecomputes(t,e,n){let o=rs.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),rs.set(e,o))),o}cached(t,e,n){let o=ns(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=ns(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){qa(e,this.bits),Ha.set(t,e),rs.delete(t)}hasCache(t){return ns(t)!==1}};function Va(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>ze||n>ze;)e&xe&&(s=s.add(o)),n&xe&&(i=i.add(o)),o=o.double(),e>>=xe,n>>=xe;return{p1:s,p2:i}}function Ka(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Jo(t),t}else return $e(r,{isLE:e})}function ln(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let f=t[c];if(!(typeof f=="bigint"&&f>ze))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Ka(t.p,e.Fp,n),s=Ka(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function dn(r,t){return function(n){let o=r(n);return{secretKey:o,publicKey:t(o)}}}var re=BigInt(0),J=BigInt(1),os=BigInt(2),kl=BigInt(8);function Cl(r,t,e,n){let o=r.sqr(e),s=r.sqr(n),i=r.add(r.mul(t.a,o),s),a=r.add(r.ONE,r.mul(t.d,r.mul(o,s)));return r.eql(i,a)}function Fa(r,t={}){let e=ln("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i}=s;ee(t,{},{uvRatio:"function"});let a=os<<BigInt(o.BYTES*8)-J,c=b=>n.create(b),f=t.uvRatio||((b,p)=>{try{return{isValid:!0,value:n.sqrt(n.div(b,p))}}catch{return{isValid:!1,value:re}}});if(!Cl(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(b,p,S=!1){let y=S?J:re;return Ir("coordinate "+b,p,y,a),p}function u(b){if(!(b instanceof d))throw new Error("EdwardsPoint expected")}let h=Fe((b,p)=>{let{X:S,Y:y,Z:A}=b,k=b.is0();p==null&&(p=k?kl:n.inv(A));let N=c(S*p),C=c(y*p),E=n.mul(A,p);if(k)return{x:re,y:J};if(E!==J)throw new Error("invZ was invalid");return{x:N,y:C}}),m=Fe(b=>{let{a:p,d:S}=s;if(b.is0())throw new Error("bad point: ZERO");let{X:y,Y:A,Z:k,T:N}=b,C=c(y*y),E=c(A*A),I=c(k*k),P=c(I*I),q=c(C*p),U=c(I*c(q+E)),w=c(P+c(S*c(C*E)));if(U!==w)throw new Error("bad point: equation left != right (1)");let v=c(y*A),x=c(k*N);if(v!==x)throw new Error("bad point: equation left != right (2)");return!0});class d{static BASE=new d(s.Gx,s.Gy,J,c(s.Gx*s.Gy));static ZERO=new d(re,J,J,re);static Fp=n;static Fn=o;X;Y;Z;T;constructor(p,S,y,A){this.X=l("x",p),this.Y=l("y",S),this.Z=l("z",y,!0),this.T=l("t",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){if(p instanceof d)throw new Error("extended point not allowed");let{x:S,y}=p||{};return l("x",S),l("y",y),new d(S,y,J,c(S*y))}static fromBytes(p,S=!1){let y=n.BYTES,{a:A,d:k}=s;p=un(K(p,y,"point")),Ht(S,"zip215");let N=un(p),C=p[y-1];N[y-1]=C&-129;let E=ye(N),I=S?a:n.ORDER;Ir("point.y",E,re,I);let P=c(E*E),q=c(P-J),U=c(k*P-A),{isValid:w,value:v}=f(q,U);if(!w)throw new Error("bad point: invalid y coordinate");let x=(v&J)===J,B=(C&128)!==0;if(!S&&v===re&&B)throw new Error("bad point: x=0 and x_0=1");return B!==x&&(v=c(-v)),d.fromAffine({x:v,y:E})}static fromHex(p,S=!1){return d.fromBytes(Kt(p),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,S=!0){return g.createCache(this,p),S||this.multiply(os),this}assertValidity(){m(this)}equals(p){u(p);let{X:S,Y:y,Z:A}=this,{X:k,Y:N,Z:C}=p,E=c(S*C),I=c(k*A),P=c(y*C),q=c(N*A);return E===I&&P===q}is0(){return this.equals(d.ZERO)}negate(){return new d(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:p}=s,{X:S,Y:y,Z:A}=this,k=c(S*S),N=c(y*y),C=c(os*c(A*A)),E=c(p*k),I=S+y,P=c(c(I*I)-k-N),q=E+N,U=q-C,w=E-N,v=c(P*U),x=c(q*w),B=c(P*w),D=c(U*q);return new d(v,x,D,B)}add(p){u(p);let{a:S,d:y}=s,{X:A,Y:k,Z:N,T:C}=this,{X:E,Y:I,Z:P,T:q}=p,U=c(A*E),w=c(k*I),v=c(C*y*q),x=c(N*P),B=c((A+k)*(E+I)-U-w),D=x-v,L=x+v,O=c(w-S*U),T=c(B*D),R=c(L*O),M=c(B*O),$=c(D*L);return new d(T,R,$,M)}subtract(p){return this.add(p.negate())}multiply(p){if(!o.isValidNot0(p))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:S,f:y}=g.cached(this,p,A=>be(d,A));return be(d,[S,y])[0]}multiplyUnsafe(p,S=d.ZERO){if(!o.isValid(p))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return p===re?d.ZERO:this.is0()||p===J?this:g.unsafe(this,p,y=>be(d,y),S)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(p){return h(this,p)}clearCofactor(){return i===J?this:this.multiplyUnsafe(i)}toBytes(){let{x:p,y:S}=this.toAffine(),y=n.toBytes(S);return y[y.length-1]|=p&J?128:0,y}toHex(){return Mt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new je(d,o.BITS);return d.BASE.precompute(8),d}function $a(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');ee(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:o,Fp:s,Fn:i}=r,a=e.randomBytes||Wt,c=e.adjustScalarBytes||(E=>E),f=e.domain||((E,I,P)=>{if(Ht(P,"phflag"),I.length||P)throw new Error("Contexts/pre-hash are not supported");return E});function l(E){return i.create(ye(E))}function u(E){let I=y.secretKey;K(E,y.secretKey,"secretKey");let P=K(t(E),2*I,"hashedSecretKey"),q=c(P.slice(0,I)),U=P.slice(I,2*I),w=l(q);return{head:q,prefix:U,scalar:w}}function h(E){let{head:I,prefix:P,scalar:q}=u(E),U=o.multiply(q),w=U.toBytes();return{head:I,prefix:P,scalar:q,point:U,pointBytes:w}}function m(E){return h(E).pointBytes}function d(E=Uint8Array.of(),...I){let P=ct(...I);return l(t(f(P,K(E,void 0,"context"),!!n)))}function g(E,I,P={}){E=K(E,void 0,"message"),n&&(E=n(E));let{prefix:q,scalar:U,pointBytes:w}=h(I),v=d(P.context,q,E),x=o.multiply(v).toBytes(),B=d(P.context,x,w,E),D=i.create(v+B*U);if(!i.isValid(D))throw new Error("sign failed: invalid s");let L=ct(x,i.toBytes(D));return K(L,y.signature,"result")}let b={zip215:!0};function p(E,I,P,q=b){let{context:U,zip215:w}=q,v=y.signature;E=K(E,v,"signature"),I=K(I,void 0,"message"),P=K(P,y.publicKey,"publicKey"),w!==void 0&&Ht(w,"zip215"),n&&(I=n(I));let x=v/2,B=E.subarray(0,x),D=ye(E.subarray(x,v)),L,O,T;try{L=r.fromBytes(P,w),O=r.fromBytes(B,w),T=o.multiplyUnsafe(D)}catch{return!1}if(!w&&L.isSmallOrder())return!1;let R=d(U,O.toBytes(),L.toBytes(),I);return O.add(L.multiplyUnsafe(R)).subtract(T).clearCofactor().is0()}let S=s.BYTES,y={secretKey:S,publicKey:S,signature:2*S,seed:S};function A(E=a(y.seed)){return K(E,y.seed,"seed")}function k(E){return he(E)&&E.length===i.BYTES}function N(E,I){try{return!!r.fromBytes(E,I)}catch{return!1}}let C={getExtendedPublicKey:h,randomSecretKey:A,isValidSecretKey:k,isValidPublicKey:N,toMontgomery(E){let{y:I}=r.fromBytes(E),P=y.publicKey,q=P===32;if(!q&&P!==57)throw new Error("only defined for 25519 and 448");let U=q?s.div(J+I,J-I):s.div(I-J,I+J);return s.toBytes(U)},toMontgomerySecret(E){let I=y.secretKey;K(E,I);let P=t(E.subarray(0,I));return c(P).subarray(0,I)}};return Object.freeze({keygen:dn(A,m),getPublicKey:m,sign:g,verify:p,utils:C,Point:r,lengths:y})}var Dl=BigInt(1),za=BigInt(2);var Tl=BigInt(5),Ll=BigInt(8),ss=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Nl={p:ss,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ll,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ul(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=ss,a=r*r%s*r%s,c=F(a,za,s)*a%s,f=F(c,Dl,s)*r%s,l=F(f,Tl,s)*f%s,u=F(l,t,s)*l%s,h=F(u,e,s)*u%s,m=F(h,n,s)*h%s,d=F(m,o,s)*m%s,g=F(d,o,s)*m%s,b=F(g,t,s)*l%s;return{pow_p_5_8:F(b,za,s)*r%s,b2:a}}function Ol(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ja=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Rl(r,t){let e=ss,n=Z(t*t*t,e),o=Z(n*n*t,e),s=Ul(r*o).pow_p_5_8,i=Z(r*n*s,e),a=Z(t*i*i,e),c=i,f=Z(i*ja,e),l=a===r,u=a===Z(-r,e),h=a===Z(-r*ja,e);return l&&(i=c),(u||h)&&(i=f),Ra(i,e)&&(i=Z(-i,e)),{isValid:l||u,value:i}}var _l=Fa(Nl,{uvRatio:Rl});function Pl(r){return $a(_l,va,Object.assign({adjustScalarBytes:Ol},r))}var Ga=Pl({});var hn=32;var is,Ml=(async()=>{try{return await Gr.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Kl(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Gr.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Gr.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function ql(r,t,e){return Ga.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Za(r,t,e){return is==null&&(is=await Ml),is?Kl(r,t,e):ql(r,t,e)}function pn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var mn=class{type="Ed25519";raw;constructor(t){this.raw=as(t,hn)}toMultihash(){return Ne.digest(qe(this))}toCID(){return Zt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=Za(this.raw,e,t);return pn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Xa(r){return r=as(r,hn),new mn(r)}function as(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new gt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Vl=Math.pow(2,7),Fl=Math.pow(2,14),$l=Math.pow(2,21),Wa=Math.pow(2,28),Ja=Math.pow(2,35),Qa=Math.pow(2,42),tc=Math.pow(2,49),it=128,ne=127;function kr(r){if(r<Vl)return 1;if(r<Fl)return 2;if(r<$l)return 3;if(r<Wa)return 4;if(r<Ja)return 5;if(r<Qa)return 6;if(r<tc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ec(r,t,e=0){switch(kr(r)){case 8:t[e++]=r&255|it,r/=128;case 7:t[e++]=r&255|it,r/=128;case 6:t[e++]=r&255|it,r/=128;case 5:t[e++]=r&255|it,r/=128;case 4:t[e++]=r&255|it,r>>>=7;case 3:t[e++]=r&255|it,r>>>=7;case 2:t[e++]=r&255|it,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function rc(r,t){let e=r[t],n=0;if(n+=e&ne,e<it||(e=r[t+1],n+=(e&ne)<<7,e<it)||(e=r[t+2],n+=(e&ne)<<14,e<it)||(e=r[t+3],n+=(e&ne)<<21,e<it)||(e=r[t+4],n+=(e&ne)*Wa,e<it)||(e=r[t+5],n+=(e&ne)*Ja,e<it)||(e=r[t+6],n+=(e&ne)*Qa,e<it)||(e=r[t+7],n+=(e&ne)*tc,e<it))return n;throw new RangeError("Could not decode varint")}var cs=new Float32Array([-0]),oe=new Uint8Array(cs.buffer);function nc(r,t,e){cs[0]=r,t[e]=oe[0],t[e+1]=oe[1],t[e+2]=oe[2],t[e+3]=oe[3]}function oc(r,t){return oe[0]=r[t],oe[1]=r[t+1],oe[2]=r[t+2],oe[3]=r[t+3],cs[0]}var fs=new Float64Array([-0]),rt=new Uint8Array(fs.buffer);function sc(r,t,e){fs[0]=r,t[e]=rt[0],t[e+1]=rt[1],t[e+2]=rt[2],t[e+3]=rt[3],t[e+4]=rt[4],t[e+5]=rt[5],t[e+6]=rt[6],t[e+7]=rt[7]}function ic(r,t){return rt[0]=r[t],rt[1]=r[t+1],rt[2]=r[t+2],rt[3]=r[t+3],rt[4]=r[t+4],rt[5]=r[t+5],rt[6]=r[t+6],rt[7]=r[t+7],fs[0]}var zl=BigInt(Number.MAX_SAFE_INTEGER),jl=BigInt(Number.MIN_SAFE_INTEGER),dt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return we;if(t<zl&&t>jl)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>ac&&(o=0n,++n>ac&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return we;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):we}},we=new dt(0,0);we.toBigInt=function(){return 0n};we.zzEncode=we.zzDecode=function(){return this};we.length=function(){return 1};var ac=4294967296n;function cc(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function fc(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function us(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function It(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function yn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ls=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,It(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw It(this,4);return yn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw It(this,4);return yn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw It(this,4);let t=oc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw It(this,4);let t=ic(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw It(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return fc(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw It(this,t);this.pos+=t}else do if(this.pos>=this.len)throw It(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new dt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw It(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw It(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw It(this,8);let t=yn(this.buf,this.pos+=4),e=yn(this.buf,this.pos+=4);return new dt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=rc(this.buf,this.pos);return this.pos+=kr(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ds(r){return new ls(r instanceof Uint8Array?r:r.subarray())}function gn(r,t,e){let n=ds(r);return t.decode(n,void 0,e)}function hs(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return ut(i);o+i>t&&(n=ut(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Ee=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function ps(){}var ys=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Gl=hs();function Zl(r){return globalThis.Buffer!=null?ut(r):Gl(r)}var Dr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ee(ps,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Ee(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new gs((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(xn,10,dt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=dt.fromBigInt(t);return this._push(xn,e.length(),e)}uint64Number(t){return this._push(ec,kr(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=dt.fromBigInt(t).zzEncode();return this._push(xn,e.length(),e)}sint64Number(t){let e=dt.fromNumber(t).zzEncode();return this._push(xn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ms,1,t?1:0)}fixed32(t){return this._push(Cr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=dt.fromBigInt(t);return this._push(Cr,4,e.lo)._push(Cr,4,e.hi)}fixed64Number(t){let e=dt.fromNumber(t);return this._push(Cr,4,e.lo)._push(Cr,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(nc,4,t)}double(t){return this._push(sc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ms,1,0):this.uint32(e)._push(Xl,e,t)}string(t){let e=cc(t);return e!==0?this.uint32(e)._push(us,e,t):this._push(ms,1,0)}fork(){return this.states=new ys(this),this.head=this.tail=new Ee(ps,0,0),this.len=0,this}reset(){return this.states!=null?(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 Ee(ps,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Zl(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ms(r,t,e){t[e]=r&255}function Yl(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var gs=class extends Ee{next;constructor(t,e){super(Yl,t,e),this.next=void 0}};function xn(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Cr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Xl(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Dr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Wl,t,r),this},Dr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Jl,t,r),this});function Wl(r,t,e){t.set(r,e)}function Jl(r,t,e){r.length<40?us(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Xt(r),e)}function xs(){return new Dr}function bn(r,t){let e=xs();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Ge;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ge||(Ge={}));function wn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function bs(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return wn("enum",Ge.VARINT,e,n)}function En(r,t){return wn("message",Ge.LENGTH_DELIMITED,r,t)}var ht;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ht||(ht={}));var ws;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(ws||(ws={}));(function(r){r.codec=()=>bs(ws)})(ht||(ht={}));var Tr;(function(r){let t;r.codec=()=>(t==null&&(t=En((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ht.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ht.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>bn(e,r.codec()),r.decode=(e,n)=>gn(e,r.codec(),n)})(Tr||(Tr={}));var Es;(function(r){let t;r.codec=()=>(t==null&&(t=En((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ht.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ht.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>bn(e,r.codec()),r.decode=(e,n)=>gn(e,r.codec(),n)})(Es||(Es={}));function Ze(r){if(isNaN(r)||r<=0)throw new gt("random bytes length must be a Number bigger than 0");return Wt(r)}var vn=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(on(t),K(e,void 0,"key"),this.iHash=t.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;let n=this.blockLen,o=new Uint8Array(n);o.set(e.length>n?t.create().update(e).digest():e);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Pt(o)}update(t){return He(this),this.iHash.update(t),this}digestInto(t){He(this),K(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},vs=(r,t,e)=>new vn(r,t).update(e).digest();vs.create=(r,t)=>new vn(r,t);var lc=(r,t)=>(r+(r>=0?t:-t)/dc)/t;function td(r,t,e){let[[n,o],[s,i]]=t,a=lc(i*r,e),c=lc(-o*r,e),f=r-a*n-c*s,l=-a*o-c*i,u=f<Vt,h=l<Vt;u&&(f=-f),h&&(l=-l);let m=Sr(Math.ceil(Yo(e)/2))+Ye;if(f<Vt||f>=m||l<Vt||l>=m)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:f,k2neg:h,k2:l}}function Ss(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Is(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return Ht(e.lowS,"lowS"),Ht(e.prehash,"prehash"),e.format!==void 0&&Ss(e.format),e}var As=class extends Error{constructor(t=""){super(t)}},se={Err:As,_tlv:{encode:(r,t)=>{let{Err:e}=se;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=vr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?vr(o.length/2|128):"";return vr(r)+s+o+t},decode(r,t){let{Err:e}=se,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let f=t.subarray(n,n+c);if(f.length!==c)throw new e("tlv.decode: length bytes not complete");if(f[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let l of f)i=i<<8|l;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=se;if(r<Vt)throw new t("integer: negative integers are not allowed");let e=vr(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=se;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Ve(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=se,o=K(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l}=n.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(f)}},hexFromSig(r){let{_tlv:t,_int:e}=se,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Vt=BigInt(0),Ye=BigInt(1),dc=BigInt(2),In=BigInt(3),ed=BigInt(4);function hc(r,t={}){let e=ln("weierstrass",r,t),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i,n:a}=s;ee(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let f=mc(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(U,w,v){let{x,y:B}=w.toAffine(),D=n.toBytes(x);if(Ht(v,"isCompressed"),v){l();let L=!n.isOdd(B);return ct(pc(L),D)}else return ct(Uint8Array.of(4),D,n.toBytes(B))}function h(U){K(U,void 0,"Point");let{publicKey:w,publicKeyUncompressed:v}=f,x=U.length,B=U[0],D=U.subarray(1);if(x===w&&(B===2||B===3)){let L=n.fromBytes(D);if(!n.isValid(L))throw new Error("bad point: is not on curve, wrong x");let O=g(L),T;try{T=n.sqrt(O)}catch($){let V=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}l();let R=n.isOdd(T);return(B&1)===1!==R&&(T=n.neg(T)),{x:L,y:T}}else if(x===v&&B===4){let L=n.BYTES,O=n.fromBytes(D.subarray(0,L)),T=n.fromBytes(D.subarray(L,L*2));if(!b(O,T))throw new Error("bad point: is not on curve");return{x:O,y:T}}else throw new Error(`bad point: got length ${x}, expected compressed=${w} or uncompressed=${v}`)}let m=t.toBytes||u,d=t.fromBytes||h;function g(U){let w=n.sqr(U),v=n.mul(w,U);return n.add(n.add(v,n.mul(U,s.a)),s.b)}function b(U,w){let v=n.sqr(w),x=g(U);return n.eql(v,x)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let p=n.mul(n.pow(s.a,In),ed),S=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(p,S)))throw new Error("bad curve params: a or b");function y(U,w,v=!1){if(!n.isValid(w)||v&&n.is0(w))throw new Error(`bad point coordinate ${U}`);return w}function A(U){if(!(U instanceof I))throw new Error("Weierstrass Point expected")}function k(U){if(!c||!c.basises)throw new Error("no endo");return td(U,c.basises,o.ORDER)}let N=Fe((U,w)=>{let{X:v,Y:x,Z:B}=U;if(n.eql(B,n.ONE))return{x:v,y:x};let D=U.is0();w==null&&(w=D?n.ONE:n.inv(B));let L=n.mul(v,w),O=n.mul(x,w),T=n.mul(B,w);if(D)return{x:n.ZERO,y:n.ZERO};if(!n.eql(T,n.ONE))throw new Error("invZ was invalid");return{x:L,y:O}}),C=Fe(U=>{if(U.is0()){if(t.allowInfinityPoint&&!n.is0(U.Y))return;throw new Error("bad point: ZERO")}let{x:w,y:v}=U.toAffine();if(!n.isValid(w)||!n.isValid(v))throw new Error("bad point: x or y not field elements");if(!b(w,v))throw new Error("bad point: equation left != right");if(!U.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(U,w,v,x,B){return v=new I(n.mul(v.X,U),v.Y,v.Z),w=Br(x,w),v=Br(B,v),w.add(v)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(w,v,x){this.X=y("x",w),this.Y=y("y",v,!0),this.Z=y("z",x),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){let{x:v,y:x}=w||{};if(!w||!n.isValid(v)||!n.isValid(x))throw new Error("invalid affine point");if(w instanceof I)throw new Error("projective point not allowed");return n.is0(v)&&n.is0(x)?I.ZERO:new I(v,x,n.ONE)}static fromBytes(w){let v=I.fromAffine(d(K(w,void 0,"point")));return v.assertValidity(),v}static fromHex(w){return I.fromBytes(Kt(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,v=!0){return q.createCache(this,w),v||this.multiply(In),this}assertValidity(){C(this)}hasEvenY(){let{y:w}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(w)}equals(w){A(w);let{X:v,Y:x,Z:B}=this,{X:D,Y:L,Z:O}=w,T=n.eql(n.mul(v,O),n.mul(D,B)),R=n.eql(n.mul(x,O),n.mul(L,B));return T&&R}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:w,b:v}=s,x=n.mul(v,In),{X:B,Y:D,Z:L}=this,O=n.ZERO,T=n.ZERO,R=n.ZERO,M=n.mul(B,B),$=n.mul(D,D),V=n.mul(L,L),H=n.mul(B,D);return H=n.add(H,H),R=n.mul(B,L),R=n.add(R,R),O=n.mul(w,R),T=n.mul(x,V),T=n.add(O,T),O=n.sub($,T),T=n.add($,T),T=n.mul(O,T),O=n.mul(H,O),R=n.mul(x,R),V=n.mul(w,V),H=n.sub(M,V),H=n.mul(w,H),H=n.add(H,R),R=n.add(M,M),M=n.add(R,M),M=n.add(M,V),M=n.mul(M,H),T=n.add(T,M),V=n.mul(D,L),V=n.add(V,V),M=n.mul(V,H),O=n.sub(O,M),R=n.mul(V,$),R=n.add(R,R),R=n.add(R,R),new I(O,T,R)}add(w){A(w);let{X:v,Y:x,Z:B}=this,{X:D,Y:L,Z:O}=w,T=n.ZERO,R=n.ZERO,M=n.ZERO,$=s.a,V=n.mul(s.b,In),H=n.mul(v,D),z=n.mul(x,L),Q=n.mul(B,O),St=n.add(v,x),j=n.add(D,L);St=n.mul(St,j),j=n.add(H,z),St=n.sub(St,j),j=n.add(v,B);let et=n.add(D,O);return j=n.mul(j,et),et=n.add(H,Q),j=n.sub(j,et),et=n.add(x,B),T=n.add(L,O),et=n.mul(et,T),T=n.add(z,Q),et=n.sub(et,T),M=n.mul($,j),T=n.mul(V,Q),M=n.add(T,M),T=n.sub(z,M),M=n.add(z,M),R=n.mul(T,M),z=n.add(H,H),z=n.add(z,H),Q=n.mul($,Q),j=n.mul(V,j),z=n.add(z,Q),Q=n.sub(H,Q),Q=n.mul($,Q),j=n.add(j,Q),H=n.mul(z,j),R=n.add(R,H),H=n.mul(et,j),T=n.mul(St,T),T=n.sub(T,H),H=n.mul(St,z),M=n.mul(et,M),M=n.add(M,H),new I(T,R,M)}subtract(w){return this.add(w.negate())}is0(){return this.equals(I.ZERO)}multiply(w){let{endo:v}=t;if(!o.isValidNot0(w))throw new Error("invalid scalar: out of range");let x,B,D=L=>q.cached(this,L,O=>be(I,O));if(v){let{k1neg:L,k1:O,k2neg:T,k2:R}=k(w),{p:M,f:$}=D(O),{p:V,f:H}=D(R);B=$.add(H),x=E(v.beta,M,V,L,T)}else{let{p:L,f:O}=D(w);x=L,B=O}return be(I,[x,B])[0]}multiplyUnsafe(w){let{endo:v}=t,x=this;if(!o.isValid(w))throw new Error("invalid scalar: out of range");if(w===Vt||x.is0())return I.ZERO;if(w===Ye)return x;if(q.hasCache(this))return this.multiply(w);if(v){let{k1neg:B,k1:D,k2neg:L,k2:O}=k(w),{p1:T,p2:R}=Va(I,x,D,O);return E(v.beta,T,R,B,L)}else return q.unsafe(x,w)}toAffine(w){return N(this,w)}isTorsionFree(){let{isTorsionFree:w}=t;return i===Ye?!0:w?w(I,this):q.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:w}=t;return i===Ye?this:w?w(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(w=!0){return Ht(w,"isCompressed"),this.assertValidity(),m(I,this,w)}toHex(w=!0){return Mt(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let P=o.BITS,q=new je(I,t.endo?Math.ceil(P/2):P);return I.BASE.precompute(8),I}function pc(r){return Uint8Array.of(r?2:3)}function mc(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function rd(r,t={}){let{Fn:e}=r,n=t.randomBytes||Wt,o=Object.assign(mc(r.Fp,e),{seed:Qo(e.ORDER)});function s(m){try{let d=e.fromBytes(m);return e.isValidNot0(d)}catch{return!1}}function i(m,d){let{publicKey:g,publicKeyUncompressed:b}=o;try{let p=m.length;return d===!0&&p!==g||d===!1&&p!==b?!1:!!r.fromBytes(m)}catch{return!1}}function a(m=n(o.seed)){return ts(K(m,o.seed,"seed"),e.ORDER)}function c(m,d=!0){return r.BASE.multiply(e.fromBytes(m)).toBytes(d)}function f(m){let{secretKey:d,publicKey:g,publicKeyUncompressed:b}=o;if(!he(m)||"_lengths"in e&&e._lengths||d===g)return;let p=K(m,void 0,"key").length;return p===g||p===b}function l(m,d,g=!0){if(f(m)===!0)throw new Error("first arg must be private key");if(f(d)===!1)throw new Error("second arg must be public key");let b=e.fromBytes(m);return r.fromBytes(d).multiply(b).toBytes(g)}let u={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=dn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:h,Point:r,utils:u,lengths:o})}function yc(r,t,e={}){on(t),ee(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let n=e.randomBytes||Wt,o=e.hmac||((v,x)=>vs(t,v,x)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:f,getPublicKey:l,getSharedSecret:u,utils:h,lengths:m}=rd(r,e),d={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},g=a*dc<s.ORDER;function b(v){let x=a>>Ye;return v>x}function p(v,x){if(!i.isValidNot0(x))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return x}function S(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function y(v,x){Ss(x);let B=m.signature,D=x==="compact"?B:x==="recovered"?B+1:void 0;return K(v,D)}class A{r;s;recovery;constructor(x,B,D){if(this.r=p("r",x),this.s=p("s",B),D!=null){if(S(),![0,1,2,3].includes(D))throw new Error("invalid recovery id");this.recovery=D}Object.freeze(this)}static fromBytes(x,B=d.format){y(x,B);let D;if(B==="der"){let{r:R,s:M}=se.toSig(K(x));return new A(R,M)}B==="recovered"&&(D=x[0],B="compact",x=x.subarray(1));let L=m.signature/2,O=x.subarray(0,L),T=x.subarray(L,L*2);return new A(i.fromBytes(O),i.fromBytes(T),D)}static fromHex(x,B){return this.fromBytes(Kt(x),B)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new A(this.r,this.s,x)}recoverPublicKey(x){let{r:B,s:D}=this,L=this.assertRecovery(),O=L===2||L===3?B+a:B;if(!s.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let T=s.toBytes(O),R=r.fromBytes(ct(pc((L&1)===0),T)),M=i.inv(O),$=N(K(x,void 0,"msgHash")),V=i.create(-$*M),H=i.create(D*M),z=r.BASE.multiplyUnsafe(V).add(R.multiplyUnsafe(H));if(z.is0())throw new Error("invalid recovery: point at infinify");return z.assertValidity(),z}hasHighS(){return b(this.s)}toBytes(x=d.format){if(Ss(x),x==="der")return Kt(se.hexFromSig(this));let{r:B,s:D}=this,L=i.toBytes(B),O=i.toBytes(D);return x==="recovered"?(S(),ct(Uint8Array.of(this.assertRecovery()),L,O)):ct(L,O)}toHex(x){return Mt(this.toBytes(x))}}let k=e.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let B=Ve(x),D=x.length*8-c;return D>0?B>>BigInt(D):B},N=e.bits2int_modN||function(x){return i.create(k(x))},C=Sr(c);function E(v){return Ir("num < 2^"+c,v,Vt,C),i.toBytes(v)}function I(v,x){return K(v,void 0,"message"),x?K(t(v),void 0,"prehashed message"):v}function P(v,x,B){let{lowS:D,prehash:L,extraEntropy:O}=Is(B,d);v=I(v,L);let T=N(v),R=i.fromBytes(x);if(!i.isValidNot0(R))throw new Error("invalid private key");let M=[E(R),E(T)];if(O!=null&&O!==!1){let z=O===!0?n(m.secretKey):O;M.push(K(z,void 0,"extraEntropy"))}let $=ct(...M),V=T;function H(z){let Q=k(z);if(!i.isValidNot0(Q))return;let St=i.inv(Q),j=r.BASE.multiply(Q).toAffine(),et=i.create(j.x);if(et===Vt)return;let Fr=i.create(St*i.create(V+et*R));if(Fr===Vt)return;let si=(j.x===et?0:2)|Number(j.y&Ye),ii=Fr;return D&&b(Fr)&&(ii=i.neg(Fr),si^=1),new A(et,ii,g?void 0:si)}return{seed:$,k2sig:H}}function q(v,x,B={}){let{seed:D,k2sig:L}=P(v,x,B);return Aa(t.outputLen,i.BYTES,o)(D,L).toBytes(B.format)}function U(v,x,B,D={}){let{lowS:L,prehash:O,format:T}=Is(D,d);if(B=K(B,void 0,"publicKey"),x=I(x,O),!he(v)){let R=v instanceof A?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+R)}y(v,T);try{let R=A.fromBytes(v,T),M=r.fromBytes(B);if(L&&R.hasHighS())return!1;let{r:$,s:V}=R,H=N(x),z=i.inv(V),Q=i.create(H*z),St=i.create($*z),j=r.BASE.multiplyUnsafe(Q).add(M.multiplyUnsafe(St));return j.is0()?!1:i.create(j.x)===$}catch{return!1}}function w(v,x,B={}){let{prehash:D}=Is(B,d);return x=I(x,D),A.fromBytes(v,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:f,getPublicKey:l,getSharedSecret:u,utils:h,lengths:m,Point:r,sign:q,verify:U,recoverPublicKey:w,Signature:A,hash:t})}var ks={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},nd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var gc=BigInt(2);function od(r){let t=ks.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%t,l=f*f*r%t,u=F(l,e,t)*l%t,h=F(u,e,t)*l%t,m=F(h,gc,t)*f%t,d=F(m,o,t)*m%t,g=F(d,s,t)*d%t,b=F(g,a,t)*g%t,p=F(b,c,t)*b%t,S=F(p,a,t)*g%t,y=F(S,e,t)*l%t,A=F(y,i,t)*d%t,k=F(A,n,t)*f%t,N=F(k,gc,t);if(!Bs.eql(Bs.sqr(N),r))throw new Error("Cannot find square root");return N}var Bs=$e(ks.p,{sqrt:od}),sd=hc(ks,{Fp:Bs,endo:nd}),Xe=yc(sd,Ea);var id=20;function Ds({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new Cs(r,t,e,n,o)}var Cs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??id,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?xc(n,this.code,e?.truncate):n.then(o=>xc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function xc(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Le(t,r)}function bc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var wc=Ds({name:"sha2-256",code:18,encode:bc("SHA-256")}),sg=Ds({name:"sha2-512",code:19,encode:bc("SHA-512")});function Ec(r,t,e,n){let o=wc.digest(e instanceof Uint8Array?e:e.subarray());if(pn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Xe.verify(t,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new ir(String(s))});try{return n?.signal?.throwIfAborted(),Xe.verify(t,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new ir(String(s))}}var Sn=class{type="secp256k1";raw;_key;constructor(t){this._key=Ic(t),this.raw=vc(this._key)}toMultihash(){return Ne.digest(qe(this))}toCID(){return Zt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e,n){return Ec(this._key,e,t,n)}};function Sc(r){return new Sn(r)}function vc(r){return Xe.Point.fromBytes(r).toBytes()}function Ic(r){try{return Xe.Point.fromBytes(r),r}catch(t){throw new Zr(String(t))}}function Ac(r){let{Type:t,Data:e}=Tr.decode(r.digest),n=e??new Uint8Array;switch(t){case ht.Ed25519:return Xa(n);case ht.secp256k1:return Sc(n);case ht.ECDSA:return oa(n);default:throw new ar}}function qe(r){return Tr.encode({Type:ht[r.type],Data:r.raw})}var ie=class{static lockQueues=new Map;static async acquire(t){let e=this.lockQueues.get(t)??Promise.resolve(),n,o=new Promise(i=>{n=i});return this.lockQueues.set(t,o),await e,()=>{n(),this.lockQueues.get(t)===o&&this.lockQueues.delete(t)}}};var ad=100,ve=class r{id;transactor;handlers;source;sourceCache;tracker;filterConflict;pending=[];latchId;constructor(t,e,n,o,s,i,a){this.id=t,this.transactor=e,this.handlers=n,this.source=o,this.sourceCache=s,this.tracker=i,this.filterConflict=a,this.latchId=`Collection:${this.id}`}static async createOrOpen(t,e,n){let o=new We(e,t,void 0),s=new Lr(o),i=new Ft(s);if(await o.tryGet(e)){let c=await xt.open(i,e);o.actionContext=await c.getActionContext()}else{let c=n.createHeaderBlock(e,i);i.insert(c),o.actionContext=void 0,await xt.open(i,e)}return new r(e,t,n.modules,o,s,i,n.filterConflict)}async act(...t){let e=await ie.acquire(this.latchId);try{await this.actInternal(...t)}finally{e()}}async actInternal(...t){await this.internalTransact(...t),this.pending.push(...t)}async internalTransact(...t){let e=new Ut(this.tracker);for(let n of t){let o=this.handlers[n.type];if(!o)throw new Error(`No handler for action type ${n.type}`);await o(n,e)}e.commit()}async update(){let t=await ie.acquire(this.latchId);try{await this.updateInternal()}finally{t()}}async updateInternal(){let t=new We(this.id,this.transactor,void 0),e=new Ft(t),n=this.source.actionContext,o=await xt.open(e,this.id),s=o?await o.getFrom(n?.rev??0):void 0,i=!1;for(let a of s?.entries??[])this.pending=this.pending.map(c=>this.doFilterConflict(c,a.actions)?c:void 0).filter(Boolean),this.sourceCache.clear(a.blockIds),i=i||this.tracker.conflicts(new Set(a.blockIds)).length>0;i&&await this.replayActions(),this.source.actionContext=s?.context}async sync(){let t=await ie.acquire(this.latchId);try{await this.syncInternal()}finally{t()}}async syncInternal(){let t=Ze(16),e=Y(t,"base64url");for(;this.pending.length||!Hn(this.tracker.transforms);){let n=[...this.pending],o=qn(this.tracker.transforms),s=new Ft(this.sourceCache,o),i=await xt.open(s,this.id);if(!i)throw new Error(`Log not found for collection ${this.id}`);let a=(this.source.actionContext?.rev??0)+1,c=await i.addActions(n,e,a,()=>s.transformedBlockIds()),f=await this.source.transact(s.transforms,e,a,this.id,c.tailPath.block.header.id);if(f)f.pending&&await new Promise(l=>setTimeout(l,ad)),await this.updateInternal();else{this.pending=this.pending.slice(n.length);let l=s.reset();await this.replayActions(),this.sourceCache.transformCache(l),this.source.actionContext=this.source.actionContext?{committed:[...this.source.actionContext.committed,{actionId:e,rev:a}],rev:a}:{committed:[{actionId:e,rev:a}],rev:a}}}}async updateAndSync(){let t=await ie.acquire(this.latchId);try{await this.updateInternal(),await this.syncInternal()}finally{t()}}async*selectLog(t=!0){let e=await xt.open(this.tracker,this.id);if(!e)throw new Error(`Log not found for collection ${this.id}`);for await(let n of e.select(void 0,t))n.action&&(yield*t?n.action.actions:n.action.actions.reverse())}async replayActions(){this.tracker.reset();for(let t of this.pending)await this.internalTransact(t)}doFilterConflict(t,e){if(this.filterConflict){let n=this.filterConflict(t,e);if(n)n!==t&&this.pending.push(n);else return!1}return!0}};var Ts=class r{collection;constructor(t){this.collection=t}static async create(t,e){let n={modules:{append:async(s,i)=>{}},createHeaderBlock:(s,i)=>({header:i.createBlockHeader(Ls,s)})},o=await ve.createOrOpen(t,e,n);return new r(o)}async append(t){let e={type:"append",data:t};await this.collection.act(e),await this.collection.updateAndSync()}async update(){await this.collection.update()}async*select(t=!0){for await(let e of this.collection.selectLog(t))yield e.data}};var Ls=bt("DIH","DiaryHeaderBlock");var Ns=bt("TRE","TreeHeaderBlock"),Us=nt("rootId");var Nr=class{store;collectionId;constructor(t,e){this.store=t,this.collectionId=e}async get(){return await X(this.store,await this.getId())}async set(t){let e=await X(this.store,this.collectionId);_(this.store,e,[Us,0,1,t.header.id])}async getId(){return(await X(this.store,this.collectionId)).rootId}};var Os=class r{collection;btree;constructor(t,e){this.collection=t,this.btree=e}static async createOrOpen(t,e,n=s=>s,o=(s,i)=>s<i?-1:s>i?1:0){let s,i={modules:{replace:async({data:c},f)=>{for(let[l,u]of c)u?await s.upsert(u):await s.deleteAt(await s.find(l))}},createHeaderBlock:(c,f)=>{let l;return s=jt.create(f,(u,h)=>(l=h,new Nr(f,c)),n,o),{header:f.createBlockHeader(Ns,c),rootId:l}}},a=await ve.createOrOpen(t,e,i);return s=s??new jt(a.tracker,new Nr(a.tracker,a.id),n,o),new r(a,s)}async replace(t){await this.collection.act({type:"replace",data:t}),await this.collection.updateAndSync()}async update(){await this.collection.update()}async first(){return await this.btree.first()}async last(){return await this.btree.last()}async find(t){return await this.btree.find(t)}async get(t){return await this.btree.get(t)}at(t){return this.btree.at(t)}range(t){return this.btree.range(t)}ascending(t){return this.btree.ascending(t)}descending(t){return this.btree.descending(t)}async getCount(t){return await this.btree.getCount(t)}async next(t){return await this.btree.next(t)}async moveNext(t){await this.btree.moveNext(t)}async prior(t){return await this.btree.prior(t)}async movePrior(t){await this.btree.movePrior(t)}isValid(t){return this.btree.isValid(t)}};var Ax=new Uint8Array(0);var cd=Cc,Bc=128,fd=127,ud=~fd,ld=Math.pow(2,31);function Cc(r,t,e){t=t||[],e=e||0;for(var n=e;r>=ld;)t[e++]=r&255|Bc,r/=128;for(;r&ud;)t[e++]=r&255|Bc,r>>>=7;return t[e]=r|0,Cc.bytes=e-n+1,t}var dd=Rs,hd=128,kc=127;function Rs(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Rs.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&kc)<<o:(i&kc)*Math.pow(2,o),o+=7}while(i>=hd);return Rs.bytes=s-n,e}var pd=Math.pow(2,7),md=Math.pow(2,14),yd=Math.pow(2,21),gd=Math.pow(2,28),xd=Math.pow(2,35),bd=Math.pow(2,42),wd=Math.pow(2,49),Ed=Math.pow(2,56),vd=Math.pow(2,63),Id=function(r){return r<pd?1:r<md?2:r<yd?3:r<gd?4:r<xd?5:r<bd?6:r<wd?7:r<Ed?8:r<vd?9:10},Sd={encode:cd,decode:dd,encodingLength:Id},Ad=Sd,_s=Ad;function Ps(r,t,e=0){return _s.encode(r,t,e),t}function Ms(r){return _s.encodingLength(r)}function Dc(r,t){let e=t.byteLength,n=Ms(r),o=n+Ms(e),s=new Uint8Array(o+e);return Ps(r,s,0),Ps(e,s,n),s.set(t,o),new Ks(r,e,t,s)}var Ks=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var Cd=20;function Hs({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new qs(r,t,e,n,o)}var qs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??Cd,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Tc(n,this.code,e?.truncate):n.then(o=>Tc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function Tc(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Dc(t,r)}function Lc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var An=Hs({name:"sha2-256",code:18,encode:Lc("SHA-256")}),Rx=Hs({name:"sha2-512",code:19,encode:Lc("SHA-512")});var Dd=nt("priorHash"),xt=class r{chain;constructor(t){this.chain=t}get id(){return this.chain.id}static async open(t,e){let n=await Be.open(t,e,r.getChainOptions(t));return n?new r(n):void 0}static async create(t,e){return new r(await Be.create(t,{...r.getChainOptions(t),newId:e}))}async addActions(t,e,n,o,s=[],i=Date.now()){let a={timestamp:i,rev:n,action:{actionId:e,actions:t,blockIds:[],collectionIds:s}},c=await this.chain.add(a),f={...a,action:{...a.action,blockIds:o()}};return this.chain.updateAt(c,f),{entry:f,tailPath:c}}async addCheckpoint(t,e,n=Date.now()){let o={timestamp:n,rev:e,checkpoint:{pendings:t}},s=await this.chain.add(o);return{entry:o,tailPath:s}}async getActionContext(){let t=await this.chain.getTail();if(!t)return;let e=await this.findCheckpoint(t);return{committed:e?[...e.pendings,...await this.pendingFrom(e.path)]:[],rev:e?.rev??0}}async getFrom(t){let e=[],n=[],o,s;for await(let i of this.chain.select(void 0,!1)){let a=de(i);if(o=o??a.rev,a.checkpoint){s=i,n.unshift(...a.checkpoint.pendings);break}n.unshift({actionId:a.action.actionId,rev:a.rev}),t!==void 0&&a.rev>t&&e.unshift(a.action)}if(s)for await(let i of this.chain.select(s,!1)){let a=de(i);if(t!==void 0&&a.rev>t)a.action&&e.unshift(a.action);else break}return{context:o?{committed:n,rev:o}:void 0,entries:e}}async*select(t,e=!0){for await(let n of this.chain.select(t,e))yield de(n)}async findCheckpoint(t){let e,n;for await(let o of this.chain.select(t,!1)){let s=de(o);if(n=n??s.rev,s.checkpoint)return{path:o,pendings:s.checkpoint.pendings,rev:n};e=o}return e?{path:e,pendings:[],rev:n}:void 0}async pendingFrom(t){let e=[];for await(let n of this.chain.select(t)){let o=de(n);o?.action&&e.push({actionId:o.action.actionId,rev:o.rev})}return e}static getChainOptions(t){return{createDataBlock:()=>({header:t.createBlockHeader("LGD")}),createHeaderBlock:e=>({header:t.createBlockHeader("LGH",e)}),newBlock:async(e,n)=>{if(n){let o=await An.digest(new TextEncoder().encode(JSON.stringify(n)));e.priorHash=Y(o.digest,"base64url")}}}}};var Vs="LGD",Fs="LGH";function ae(r){let t=5381;for(let e=0;e<r.length;e++)t=(t<<5)+t+r.charCodeAt(e)|0;return Math.abs(t).toString(36)}function Je(r,t,e,n){let o=JSON.stringify({peerId:r,timestamp:t,schemaHash:e,engineId:n}),s=`stamp:${ae(o)}`;return{peerId:r,timestamp:t,schemaHash:e,engineId:n,id:s}}function Qe(r,t,e){let n=JSON.stringify({stampId:r,statements:t,reads:e});return`tx:${ae(n)}`}Bn();Bn();var kn=class{transactor;collections;constructor(t,e){this.transactor=t,this.collections=e}async applyActions(t,e){for(let{collectionId:n,actions:o}of t){let s=this.collections.get(n);if(!s)throw new Error(`Collection not found: ${n}`);for(let i of o){let a={...i,transaction:e};await s.act(a)}}}async commit(t){let e=Array.from(this.collections.entries()).map(([c,f])=>({collectionId:c,collection:f,transforms:f.tracker.transforms})).filter(({transforms:c})=>Object.keys(c.inserts??{}).length+Object.keys(c.updates??{}).length+(c.deletes?.length??0)>0);if(e.length===0)return;let n=new Map,o=new Map;for(let{collectionId:c,collection:f,transforms:l}of e){n.set(c,l);let u=await xt.open(f.tracker,c);if(!u)throw new Error(`Log not found for collection ${c}`);let h=await u.chain.getTail();h&&o.set(c,h.block.header.id)}let s=e.flatMap(({collectionId:c,transforms:f})=>[...Object.entries(f.inserts??{}).map(([l,u])=>({type:"insert",collectionId:c,blockId:l,block:u})),...Object.entries(f.updates??{}).map(([l,u])=>({type:"update",collectionId:c,blockId:l,operations:u})),...(f.deletes??[]).map(l=>({type:"delete",collectionId:c,blockId:l}))]),i=this.hashOperations(s),a=await this.coordinateTransaction(t,i,n,o);if(!a.success)throw new Error(`Transaction commit failed: ${a.error}`)}async rollback(t){for(let e of this.collections.values())e.tracker.reset()}getTransforms(){let t=new Map;for(let[e,n]of this.collections.entries()){let o=n.tracker.transforms;(Object.keys(o.inserts??{}).length>0||Object.keys(o.updates??{}).length>0||(o.deletes?.length??0)>0)&&t.set(e,o)}return t}resetTransforms(){for(let t of this.collections.values())t.tracker.reset()}hashOperations(t){let e=JSON.stringify(t);return`ops:${ae(e)}`}async commitTransaction(t){let e=Array.from(t.getCollectionActions().entries()).map(([f,l])=>({collectionId:f,actions:l}));if(e.length===0)return{success:!0};let n=Or(e),o=t.getReads(),s=Je("local",Date.now(),"",t.engine),i={stamp:s,statements:n,reads:o,id:Qe(s.id,n,o)},{ActionsEngine:a}=await Promise.resolve().then(()=>(Bn(),Nc)),c=new a(this);return await this.execute(i,c)}async execute(t,e){let n=await e.execute(t);if(!n.success)return n;if(!n.actions||n.actions.length===0)return{success:!0};let o=new Map,s=new Map,i=new Map,a=n.actions.map(u=>u.collectionId);for(let u of n.actions){let h=await this.applyActionsToCollection(u,t,a);if(!h.success)return{success:!1,error:h.error};o.set(u.collectionId,h.transforms),s.set(u.collectionId,h.logTailBlockId),i.set(u.collectionId,h.results)}let c=Array.from(o.entries()).flatMap(([u,h])=>[...Object.entries(h.inserts??{}).map(([m,d])=>({type:"insert",collectionId:u,blockId:m,block:d})),...Object.entries(h.updates??{}).map(([m,d])=>({type:"update",collectionId:u,blockId:m,operations:d})),...(h.deletes??[]).map(m=>({type:"delete",collectionId:u,blockId:m}))]),f=this.hashOperations(c),l=await this.coordinateTransaction(t,f,o,s);return l.success?{success:!0,actions:n.actions,results:i}:l}async applyActionsToCollection(t,e,n){let o=this.collections.get(t.collectionId);if(!o)return{success:!1,error:`Collection not found: ${t.collectionId}`};let s=o.tracker.transforms,i=await xt.open(o.tracker,t.collectionId);if(!i)return{success:!1,error:`Log not found for collection ${t.collectionId}`};let a=e.id,c=(o.source.actionContext?.rev??0)+1,f=await i.addActions(t.actions,a,c,()=>At(s),n);return{success:!0,transforms:s,logTailBlockId:f.tailPath.block.header.id,results:[]}}async coordinateTransaction(t,e,n,o){let s=Array.from(o.values()),i=await this.gatherPhase(s),a=await this.pendPhase(t,e,n,i);if(!a.success)return a;let c=await this.commitPhase(t.id,s,a.pendedBlockIds);return c.success?{success:!0}:(await this.cancelPhase(t.id,n),c)}async gatherPhase(t){if(t.length===1||!this.transactor.queryClusterNominees)return null;let e=t.map(s=>this.transactor.queryClusterNominees(s));return(await Promise.all(e)).reduce((s,i)=>(i.nominees.forEach(a=>s.add(a)),s),new Set)}async pendPhase(t,e,n,o){if(n.size===0)return{success:!1,error:"No transforms to pend"};let s=new Map,i=t.id,a=o?Array.from(o):void 0;for(let[c,f]of n.entries()){let l=this.collections.get(c);if(!l)return{success:!1,error:`Collection not found: ${c}`};let u=(l.source.actionContext?.rev??0)+1,h={actionId:i,rev:u,transforms:f,policy:"r",transaction:t,operationsHash:e,superclusterNominees:a},m=await this.transactor.pend(h);if(!m.success)return{success:!1,error:`Pend failed for collection ${c}: ${m.reason}`};s.set(c,m.blockIds)}return{success:!0,pendedBlockIds:s}}async commitPhase(t,e,n){for(let[o,s]of n.entries()){let i=this.collections.get(o);if(!i)return{success:!1,error:`Collection not found: ${o}`};let a=(i.source.actionContext?.rev??0)+1,c=e.find(u=>s.includes(u));if(!c)return{success:!1,error:`Log tail block not found for collection ${o}`};let f={actionId:t,blockIds:s,tailId:c,rev:a};if(!(await this.transactor.commit(f)).success)return{success:!1,error:`Commit failed for collection ${o}`}}return{success:!0}}async cancelPhase(t,e){for(let[n,o]of e.entries()){if(!this.collections.get(n))continue;let i=At(o);await this.transactor.cancel({actionId:t,blockIds:i})}}};var Cn=class{coordinator;transactionId;engine;collectionActions=new Map;reads=[];constructor(t,e,n){this.coordinator=t,this.transactionId=e,this.engine=n}async addAction(t,e){let n={...e,transaction:this.transactionId},o=this.coordinator.collections.get(t);o&&await o.act(n),this.collectionActions.has(t)||this.collectionActions.set(t,[]),this.collectionActions.get(t).push(n)}addRead(t){this.reads.push(t)}async commit(){return await this.coordinator.commitTransaction(this)}rollback(){this.collectionActions.clear(),this.reads.length=0}getCollectionActions(){return this.collectionActions}getReads(){return this.reads}getAffectedCollections(){return new Set(this.collectionActions.keys())}};var Dn=class{coordinator;engine;statements=[];stamp;committed=!1;rolledBack=!1;constructor(t,e,n="local",o=""){this.coordinator=t,this.engine=e,this.stamp=Je(n,Date.now(),o,"unknown")}async execute(t,e){if(this.committed)return{success:!1,error:"Transaction already committed"};if(this.rolledBack)return{success:!1,error:"Transaction already rolled back"};try{let n;if(e)n=e;else{let o={stamp:this.stamp,statements:[t],reads:[],id:"temp"},s=await this.engine.execute(o);if(!s.success||!s.actions)return{success:!1,error:s.error||"Failed to translate statement"};n=s.actions}return await this.coordinator.applyActions(n,this.stamp.id),this.statements.push(t),{success:!0}}catch(n){return{success:!1,error:`Failed to execute statement: ${n instanceof Error?n.message:String(n)}`}}}async commit(){if(this.committed)return{success:!1,error:"Transaction already committed"};if(this.rolledBack)return{success:!1,error:"Transaction already rolled back"};let t={stamp:this.stamp,statements:this.statements,reads:[],id:Qe(this.stamp.id,this.statements,[])};return await this.coordinator.commit(t),this.committed=!0,{success:!0}}async rollback(){if(this.committed)throw new Error("Cannot rollback: transaction already committed");if(this.rolledBack)throw new Error("Transaction already rolled back");await this.coordinator.rollback(this.stamp.id),this.rolledBack=!0,this.statements.length=0}getStampId(){return this.stamp.id}getStamp(){return this.stamp}getStatements(){return this.statements}isCommitted(){return this.committed}isRolledBack(){return this.rolledBack}};var Tn=class{engines;createValidationCoordinator;constructor(t,e){this.engines=t,this.createValidationCoordinator=e}async validate(t,e){let{stamp:n,statements:o}=t,s=this.engines.get(n.engineId);if(!s)return{valid:!1,reason:`Unknown engine: ${n.engineId}`};let i=await s.getSchemaHash();if(i!==n.schemaHash)return{valid:!1,reason:`Schema mismatch: local=${i}, sender=${n.schemaHash}`};let a=this.createValidationCoordinator();try{let c=await s.engine.execute(t);if(!c.success)return{valid:!1,reason:`Re-execution failed: ${c.error}`};c.actions&&c.actions.length>0&&await a.applyActions(c.actions,n.id);let f=a.getTransforms(),l=this.collectOperations(f),u=this.hashOperations(l);return u!==e?{valid:!1,reason:"Operations hash mismatch",computedHash:u}:{valid:!0,computedHash:u}}finally{a.dispose()}}async getSchemaHash(t){let e=this.engines.get(t);return e?await e.getSchemaHash():void 0}collectOperations(t){return Array.from(t.entries()).flatMap(([e,n])=>[...Object.entries(n.inserts??{}).map(([o,s])=>({type:"insert",collectionId:e,blockId:o,block:s})),...Object.entries(n.updates??{}).map(([o,s])=>({type:"update",collectionId:e,blockId:o,operations:s})),...(n.deletes??[]).map(o=>({type:"delete",collectionId:e,blockId:o}))])}hashOperations(t){let e=JSON.stringify(t);return`ops:${ae(e)}`}};var yb=new Uint8Array(0);function Uc(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ce(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Td(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,b=0,p=0,S=d.length;p!==S&&d[p]===0;)p++,g++;for(var y=(S-p)*l+1>>>0,A=new Uint8Array(y);p!==S;){for(var k=d[p],N=0,C=y-1;(k!==0||N<b)&&C!==-1;C--,N++)k+=256*A[C]>>>0,A[C]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");b=N,p++}for(var E=y-b;E!==y&&A[E]===0;)E++;for(var I=c.repeat(g);E<y;++E)I+=r.charAt(A[E]);return I}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var b=0,p=0;d[g]===c;)b++,g++;for(var S=(d.length-g)*f+1>>>0,y=new Uint8Array(S);d[g];){var A=e[d.charCodeAt(g)];if(A===255)return;for(var k=0,N=S-1;(A!==0||k<p)&&N!==-1;N--,k++)A+=a*y[N]>>>0,y[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=k,g++}if(d[g]!==" "){for(var C=S-p;C!==S&&y[C]===0;)C++;for(var E=new Uint8Array(b+(S-C)),I=b;C!==S;)E[I++]=y[C++];return E}}}function m(d){var g=h(d);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:h,decode:m}}var Ld=Td,Nd=Ld,Oc=Nd;var zs=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},js=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Rc(this,t)}},Gs=class{decoders;constructor(t){this.decoders=t}or(t){return Rc(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Rc(r,t){return new Gs({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Zs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new zs(t,e,n),this.decoder=new js(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function _c({name:r,prefix:t,encode:e,decode:n}){return new Zs(r,t,e,n)}function tr({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Oc(e,r);return _c({prefix:t,name:r,encode:n,decode:s=>ce(o(s))})}function Ud(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=t[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Od(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function Rd(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function Lt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Rd(n);return _c({prefix:t,name:r,encode(s){return Od(s,n,e)},decode(s){return Ud(s,o,e,r)}})}var pt=tr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ib=tr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Rr=Lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Bb=Lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),kb=Lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Cb=Lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Db=Lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Tb=Lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Lb=Lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Nb=Lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ub=Lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ln=tr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_b=tr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var _d=Kc,Pc=128,Pd=127,Md=~Pd,Kd=Math.pow(2,31);function Kc(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Kd;)t[e++]=r&255|Pc,r/=128;for(;r&Md;)t[e++]=r&255|Pc,r>>>=7;return t[e]=r|0,Kc.bytes=e-n+1,t}var qd=Ys,Hd=128,Mc=127;function Ys(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ys.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&Mc)<<o:(i&Mc)*Math.pow(2,o),o+=7}while(i>=Hd);return Ys.bytes=s-n,e}var Vd=Math.pow(2,7),Fd=Math.pow(2,14),$d=Math.pow(2,21),zd=Math.pow(2,28),jd=Math.pow(2,35),Gd=Math.pow(2,42),Zd=Math.pow(2,49),Yd=Math.pow(2,56),Xd=Math.pow(2,63),Wd=function(r){return r<Vd?1:r<Fd?2:r<$d?3:r<zd?4:r<jd?5:r<Gd?6:r<Zd?7:r<Yd?8:r<Xd?9:10},Jd={encode:_d,decode:qd,encodingLength:Wd},Qd=Jd,_r=Qd;function Pr(r,t=0){return[_r.decode(r,t),_r.decode.bytes]}function er(r,t,e=0){return _r.encode(r,t,e),t}function rr(r){return _r.encodingLength(r)}function or(r,t){let e=t.byteLength,n=rr(r),o=n+rr(e),s=new Uint8Array(o+e);return er(r,s,0),er(e,s,n),s.set(t,o),new nr(r,e,t,s)}function Mr(r){let t=ce(r),[e,n]=Pr(t),[o,s]=Pr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new nr(e,o,i,t)}function Hc(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Uc(r.bytes,e.bytes)}}var nr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Vc(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return eh(e,Xs(r),t??pt.encoder);default:return rh(e,Xs(r),t??Rr.encoder)}}var Fc=new WeakMap;function Xs(r){let t=Fc.get(r);if(t==null){let e=new Map;return Fc.set(r,e),e}return t}var Ie=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Kr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==nh)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=or(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Hc(t.multihash,n.multihash)}toString(t){return Vc(this,t)}toJSON(){return{"/":Vc(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??$c(n,o,s.bytes))}else if(e[oh]===!0){let{version:n,multihash:o,code:s}=e,i=Mr(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Kr)throw new Error(`Version 0 CID must use dag-pb (code: ${Kr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=$c(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Kr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=ce(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new nr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,h]=Pr(t.subarray(e));return e+=h,u},o=n(),s=Kr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),f=e+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(t,e){let[n,o]=th(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Xs(s).set(n,t),s}};function th(r,t){switch(r[0]){case"Q":{let e=t??pt;return[pt.prefix,e.decode(`${pt.prefix}${r}`)]}case pt.prefix:{let e=t??pt;return[pt.prefix,e.decode(r)]}case Rr.prefix:{let e=t??Rr;return[Rr.prefix,e.decode(r)]}case Ln.prefix:{let e=t??Ln;return[Ln.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function eh(r,t,e){let{prefix:n}=e;if(n!==pt.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function rh(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Kr=112,nh=18;function $c(r,t,e){let n=rr(r),o=n+rr(t),s=new Uint8Array(o+e.byteLength);return er(r,s,0),er(t,s,n),s.set(e,o),s}var oh=Symbol.for("@ipld/js-cid/CID");var zc=0,sh="identity",jc=ce;function ih(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return or(zc,jc(r))}var Un={code:zc,name:sh,encode:jc,digest:ih};var ah=20;function Js({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new Ws(r,t,e,n,o)}var Ws=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??ah,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Gc(n,this.code,e?.truncate):n.then(o=>Gc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function Gc(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return or(t,r)}function Zc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Yc=Js({name:"sha2-256",code:18,encode:Zc("SHA-256")}),Wb=Js({name:"sha2-512",code:19,encode:Zc("SHA-512")});var Xc=Symbol.for("nodejs.util.inspect.custom"),ch=114,qr=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[eo]=!0;toString(){return this.string==null&&(this.string=pt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ie.createV1(ch,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Et(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Xc](){return`PeerId(${this.toString()})`}},On=class extends qr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Rn=class extends qr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},_n=class extends qr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},fh=2336,Hr=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Un.digest(Xt(this.url))}[Xc](){return`PeerId(${this.url})`}[eo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ie.createV1(fh,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=Y(t)),t.toString()===this.toString())}};var uh=114,Wc=2336;function Jc(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Mr(pt.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return lh(Ie.parse(r));if(t==null)throw new gt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Mr(t.decode(r))}return Qc(e)}function Qc(r){if(hh(r))return new On({multihash:r});if(dh(r))try{let t=Ac(r);if(t.type==="Ed25519")return new Rn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new _n({multihash:r,publicKey:t})}catch{let e=Y(r.digest);return new Hr(new URL(e))}throw new Xr("Supplied PeerID Multihash is invalid")}function lh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==uh&&r.code!==Wc)throw new Yr("Supplied PeerID CID is invalid");if(r.code===Wc){let t=Y(r.multihash.digest);return new Hr(new URL(t))}return Qc(r.multihash)}function dh(r){return r.code===Un.code}function hh(r){return r.code===Yc.code}async function mt(r){let t=new TextEncoder().encode(r);return(await An.digest(t)).digest}function tf(r){for(let t in r)return!1;return!0}var Vr=class{promise;response;error;t1=Date.now();duration;get isResponse(){return this.response!==void 0}get isError(){return this.error!==void 0}get isComplete(){return this.isResponse||this.isError}async result(){if(this.isResponse)return this.response;if(this.isError)throw this.error;return await this.promise}constructor(t){this.promise=t,t.then(e=>(this.duration=Date.now()-this.t1,this.response=e,e),e=>{this.duration=Date.now()-this.t1,this.error=e})}};function Qs(r,t,e,n){let o=r.reduce((s,[i,a])=>{let c=a.toString(),f=s.get(c)??{peerId:a,blockId:i,excludedPeers:n};return s.set(c,{...f,payload:e(t,i,f.payload)}),s},new Map);return Array.from(o.values())}function*ef(r){let t=[...r];for(;t.length>0;){let e=t.pop();(!e.request||!e.request.isResponse)&&(yield e),e.subsumedBy&&e.subsumedBy.length&&t.push(...e.subsumedBy)}}function ti(r,t){for(let e of r){let n=!1,o=[e];for(;o.length>0;){let s=o.pop();if(t(s)){n=!0;break}if(s.subsumedBy&&s.subsumedBy.length)for(let i=0;i<s.subsumedBy.length;i++)o.push(s.subsumedBy[i])}if(!n)return!1}return!0}function*$t(r,t){let e=[...r];for(;e.length>0;){let n=e.pop();(!t||t(n))&&(yield n),n.subsumedBy&&n.subsumedBy.length&&e.push(...n.subsumedBy)}}function Se(r,t,e){return[...e??[],t]}async function Ae(r,t,e,n,o,s){let i=new WeakMap;for(let c of r)i.set(c,c);let a=async c=>{await Promise.all(c.map(async f=>{f.request=new Vr(t(f).catch(async l=>{if(o>Date.now()){let u=[f.peerId,...f.excludedPeers??[]],h=await Pn(e(f),f.payload,n,u,s);if(h.length>0&&o>Date.now()){let m=i.get(f)??f;m.subsumedBy=[...m.subsumedBy??[],...h];for(let d of h)i.set(d,m);await a(h)}}throw l}))})),await Promise.all(c.map(f=>f.request?.result().catch(()=>{})))};await a(r)}async function Pn(r,t,e,n,o){let s=new Set(r),i=await Promise.all(Array.from(s).map(async a=>[a,await o(a,{excludedPeers:n})]));return Qs(i,t,e,n)}var ei=class{keyNetwork;timeoutMs;abortOrCancelTimeoutMs;getRepo;constructor(t){this.keyNetwork=t.keyNetwork,this.timeoutMs=t.timeoutMs,this.abortOrCancelTimeoutMs=t.abortOrCancelTimeoutMs,this.getRepo=t.getRepo}async get(t){let e=Array.from(new Set(t.blockIds)),n=await this.batchesForPayload(e,e,(h,m,d)=>[...d??[],...h.filter(g=>g===m)],[]),o=Date.now()+this.timeoutMs,s;try{await Ae(n,h=>this.getRepo(h.peerId).get({blockIds:h.payload,context:t.context},{expiration:o}),h=>h.payload,(h,m,d)=>[...d??[],...h.filter(g=>g===m)],o,async(h,m)=>this.keyNetwork.findCoordinator(await mt(h),m))}catch(h){s=h}let i=h=>h.request?.isResponse===!0&&h.request.response!=null,a=h=>{if(!i(h))return!1;let m=h.request.response;return h.payload.some(d=>{let g=m[d];return g&&typeof g=="object"&&"block"in g&&g.block!=null})},c=Array.from($t(n)).filter(h=>!i(h)||!a(h));if(c.length>0&&Date.now()<o)try{let h=new Map;for(let m of c){let d=new Set([m.peerId,...m.excludedPeers??[]]);h.set(m,d);let g=await Pn(m.payload,m.payload,(b,p,S)=>[...S??[],...b.filter(y=>y===p)],Array.from(d),async(b,p)=>this.keyNetwork.findCoordinator(await mt(b),p));g.length>0&&(m.subsumedBy=[...m.subsumedBy??[],...g],await Ae(g,b=>this.getRepo(b.peerId).get({blockIds:b.payload,context:t.context},{expiration:o}),b=>b.payload,(b,p,S)=>[...S??[],...b.filter(y=>y===p)],o,async(b,p)=>this.keyNetwork.findCoordinator(await mt(b),p)))}}catch(h){s||(s=h)}let f=Array.from($t(n,h=>h.request?.isResponse&&!tf(h.request.response))),l=new Map;for(let h of f){let m=h.request.response;for(let[d,g]of Object.entries(m)){let b=l.get(d),p=g&&typeof g=="object"&&"block"in g&&g.block!=null,S=b&&typeof b=="object"&&"block"in b&&b.block!=null;(!b||p&&!S)&&l.set(d,g)}}if(e.filter(h=>!l.has(h)).length>0){let h=this.formatBatchStatuses(n,d=>d.request?.isResponse??!1,d=>{let g=d.request==null?"no-response":d.request.isResponse?"response":"in-flight";return`${d.peerId.toString()}[block:${d.blockId}](${g})`}),m=new Error(`Some peers did not complete: ${h}${s?`; root: ${s.message}`:""}`);throw m.cause=s,m}return Object.fromEntries(l)}async getStatus(t){let e=[...new Set(t.flatMap(o=>o.blockIds))];if(e.length===0)return t.map(o=>({...o,statuses:[]}));let n=await this.get({blockIds:e});return t.map(o=>({...o,statuses:o.blockIds.map(s=>{let i=n[s];if(!i)return"aborted";let{state:a}=i;return a.pendings?.includes(o.actionId)?"pending":a.latest?.actionId===o.actionId?"committed":"aborted"})}))}async consolidateCoordinators(t,e,n){let o=await Promise.all(t.map(async a=>({blockId:a,coordinator:await this.keyNetwork.findCoordinator(await mt(a),{excludedPeers:[]})}))),s=new Map;for(let{blockId:a,coordinator:c}of o){let f=c.toString(),l=s.get(f)??[];l.push(a),s.set(f,l)}let i=[];for(let[a,c]of s){let f=o.find(u=>u.coordinator.toString()===a).coordinator,l={inserts:{},updates:{},deletes:[]};for(let u of c)l=n(e,u,l);i.push({peerId:f,payload:l,blockId:c[0],coordinatingBlockIds:c,excludedPeers:[]})}return i}async pend(t){let e=(c,f,l)=>{let u=Fn(c,f);return l?jn(l,f,u):$n(u,f)},n=At(t.transforms),o=await this.consolidateCoordinators(n,t.transforms,e),s=Date.now()+this.timeoutMs,i;try{await Ae(o,c=>this.getRepo(c.peerId).pend({...t,transforms:c.payload},{expiration:s,coordinatingBlockIds:c.coordinatingBlockIds}),c=>At(c.payload),e,s,async(c,f)=>this.keyNetwork.findCoordinator(await mt(c),f));try{let c=this.keyNetwork;if(typeof c?.recordCoordinator=="function")for(let f of Array.from($t(o)))c.recordCoordinator(await mt(f.blockId),f.peerId)}catch(c){console.warn("Failed to record coordinator hint",c)}}catch(c){i=c}if(!ti(o,c=>c.request?.isResponse&&c.request.response.success)){let c=this.formatBatchStatuses(o,u=>(u.request?.isResponse&&u.request.response?.success)??!1,u=>{let h=u.request==null?"no-response":u.request.isResponse?"non-success":"in-flight";return`${u.peerId.toString()}[block:${u.blockId}](${h})`}),f=new Error(`Some peers did not complete: ${c}${i?`; root: ${i.message}`:""}`),l=i;f.cause=l,f.errors=l?[l]:[],i=f}if(i){Promise.resolve().then(()=>this.cancelBatch(o,{blockIds:n,actionId:t.actionId}));let c=Array.from($t(o,f=>f.request?.isResponse&&!f.request.response.success));if(c.length>0)return{success:!1,missing:ri(c.flatMap(f=>f.request.response.missing).filter(f=>f!==void 0))};throw i}return{success:!0,pending:Array.from($t(o,c=>c.request?.isResponse&&c.request.response.success)).flatMap(c=>c.request.response.pending),blockIds:At(t.transforms)}}async cancel(t){let e=await this.batchesForPayload(t.blockIds,t.blockIds,Se,[]),n=Date.now()+this.abortOrCancelTimeoutMs;await Ae(e,o=>this.getRepo(o.peerId).cancel({actionId:t.actionId,blockIds:o.payload},{expiration:n}),o=>o.payload,Se,n,async(o,s)=>this.keyNetwork.findCoordinator(await mt(o),s))}async queryClusterNominees(t){let e=await mt(t),n=await this.keyNetwork.findCluster(e);return{nominees:Object.keys(n).map(s=>Jc(s))}}async commit(t){let e=[...new Set([...t.blockIds,t.tailId])];if(t.headerId&&!t.blockIds.includes(t.headerId)){let s=await this.commitBlock(t.headerId,e,t.actionId,t.rev);if(!s.success)return s}let n=await this.commitBlock(t.tailId,e,t.actionId,t.rev);if(!n.success)return n;let o=t.blockIds.filter(s=>s!==t.tailId&&!(t.headerId&&s===t.headerId&&!t.blockIds.includes(t.headerId)));if(o.length>0){let{batches:s,error:i}=await this.commitBlocks({blockIds:o,actionId:t.actionId,rev:t.rev});if(i)try{console.warn("[NetworkTransactor] non-tail commit had errors; proceeding after tail commit:",i.message)}catch{}}return{success:!0}}async commitBlock(t,e,n,o){let{batches:s,error:i}=await this.commitBlocks({blockIds:[t],actionId:n,rev:o});if(i){Promise.resolve().then(()=>this.cancel({blockIds:e,actionId:n}));let a=Array.from($t(s,c=>c.request?.isResponse&&!c.request.response.success));if(a.length>0)return{missing:ri(a.flatMap(c=>c.request.response.missing)),success:!1};throw i}return{success:!0}}async commitBlocks({blockIds:t,actionId:e,rev:n}){let o=Date.now()+this.timeoutMs,s=await this.batchesForPayload(t,t,Se,[]),i;try{await Ae(s,a=>this.getRepo(a.peerId).commit({actionId:e,blockIds:a.payload,rev:n},{expiration:o}),a=>a.payload,Se,o,async(a,c)=>this.keyNetwork.findCoordinator(await mt(a),c))}catch(a){i=a}if(!ti(s,a=>a.request?.isResponse&&a.request.response.success)){let a=this.formatBatchStatuses(s,f=>(f.request?.isResponse&&f.request.response?.success)??!1,f=>{let l=f.request==null?"no-response":f.request.isResponse?"non-success":"in-flight",u=f.request?.response,h=u&&u.success===!1?Array.isArray(u.missing)?` missing=${u.missing.length}`:" success=false":"";return`${f.peerId.toString()}[blocks:${f.payload instanceof Array?f.payload.length:1}](${l})${h?" "+h:""}`}),c=new Error(`Some peers did not complete: ${a}${i?`; root: ${i.message}`:""}`);c.cause=i,i=c}return{batches:s,error:i}}async batchesForPayload(t,e,n,o){return Pn(t,e,n,o,async(s,i)=>this.keyNetwork.findCoordinator(await mt(s),i))}async cancelBatch(t,e){let n=Date.now()+this.abortOrCancelTimeoutMs,o=Qs(Array.from($t(t)).map(s=>[s.blockId,s.peerId]),e.blockIds,Se,[]);await Ae(o,s=>this.getRepo(s.peerId).cancel({actionId:e.actionId,blockIds:s.payload},{expiration:n}),s=>s.payload,Se,n,async(s,i)=>this.keyNetwork.findCoordinator(await mt(s),i))}formatBatchStatuses(t,e,n){let s=Array.from(ef(t)).map(n).join(", ");return s.length===0&&(s=Array.from($t(t)).map(n).join(", ")),s}};function ri(r){let t=ni(r,({actionId:e})=>e);return Object.entries(t).map(([e,n])=>({actionId:e,transforms:Vn(...n.map(o=>o.transforms))}))}var We=class{collectionId;transactor;actionContext;constructor(t,e,n){this.collectionId=t,this.transactor=e,this.actionContext=n}createBlockHeader(t,e){return{type:t,id:e??this.generateId(),collectionId:this.collectionId}}generateId(){return Y(Ze(32),"base64url")}async tryGet(t){let e=await this.transactor.get({blockIds:[t],context:this.actionContext});if(e){let{block:n,state:o}=e[t];return n}}async transact(t,e,n,o,s){let i=await this.transactor.pend({transforms:t,actionId:e,rev:n,policy:"r"});if(!i.success)return i;let a=t.inserts&&Object.hasOwn(t.inserts,o),c=await this.transactor.commit({headerId:a?o:void 0,tailId:s,blockIds:i.blockIds,actionId:e,rev:n});if(!c.success)return c}};var Ft=class{source;transforms;constructor(t,e=sr()){this.source=t,this.transforms=e}async tryGet(t){let e=await this.source.tryGet(t);if(e){if((this.transforms.updates?.[t]??[]).forEach(o=>Nt(e,o)),this.transforms.deletes?.includes(t))return}else if(this.transforms.inserts&&Object.hasOwn(this.transforms.inserts,t))return structuredClone(this.transforms.inserts[t]);return e}generateId(){return this.source.generateId()}createBlockHeader(t,e){return this.source.createBlockHeader(t,e)}insert(t){let e=this.transforms.inserts??={};e[t.header.id]=structuredClone(t);let n=this.transforms.deletes,o=n?.indexOf(t.header.id)??-1;o>=0&&n.splice(o,1)}update(t,e){let n=this.transforms.inserts?.[t];if(n)Nt(n,e);else{let o=this.transforms.updates??={};oi(o,t,()=>[]).push(structuredClone(e))}}delete(t){this.transforms.inserts&&delete this.transforms.inserts[t],this.transforms.updates&&delete this.transforms.updates[t],(this.transforms.deletes??=[]).push(t)}reset(t=sr()){let e=this.transforms;return this.transforms=t,e}transformedBlockIds(){return Array.from(new Set(At(this.transforms)))}conflicts(t){return this.transformedBlockIds().filter(e=>t.has(e))}};var Ut=class extends Ft{store;constructor(t){super(t),this.store=t}commit(){let t=this.reset();zn(t,this.store)}};var Lr=class{source;cache=new Map;constructor(t){this.source=t}async tryGet(t){let e=this.cache.get(t);return e||(e=await this.source.tryGet(t),e&&this.cache.set(t,e)),structuredClone(e)}generateId(){return this.source.generateId()}createBlockHeader(t,e){return this.source.createBlockHeader(t,e)}clear(t=void 0){if(t)for(let e of t)this.cache.delete(e);else this.cache.clear()}transformCache(t){for(let e of t.deletes??[])this.cache.delete(e);for(let[,e]of Object.entries(t.inserts??{}))this.cache.set(e.header.id,structuredClone(e));for(let[e,n]of Object.entries(t.updates??{}))for(let o of n){let s=this.cache.get(e);s&&Nt(s,o)}}};function ni(r,t){return r.reduce((e,n)=>{let o=t(n);return(e[o]??=[]).push(n),e},{})}function oi(r,t,e,n){let o=r[t];return typeof o>"u"?(o=e(),r[t]=o):n&&n(o),o}function ph(r,t,e,n){let o=r.get(t);return typeof o>"u"?(o=e(),r.set(t,o)):n&&n(o),o}return cf(mh);})();
|
|
2
|
+
"use strict";var OptimysticDbCore=(()=>{var Mn=Object.defineProperty;var rf=Object.getOwnPropertyDescriptor;var nf=Object.getOwnPropertyNames;var of=Object.prototype.hasOwnProperty;var sf=(r,t)=>()=>(r&&(t=r(r=0)),t);var at=(r,t)=>{for(var e in t)Mn(r,e,{get:t[e],enumerable:!0})},af=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of nf(t))!of.call(r,o)&&o!==e&&Mn(r,o,{get:()=>t[o],enumerable:!(n=rf(t,o))||n.enumerable});return r};var cf=r=>af(Mn({},"__esModule",{value:!0}),r);var Nc={};at(Nc,{ACTIONS_ENGINE_ID:()=>$s,ActionsEngine:()=>Ur,createActionsStatements:()=>Or});function Or(r){return r.map(t=>JSON.stringify(t))}var $s,Ur,Bn=sf(()=>{"use strict";$s="actions@1.0.0",Ur=class{coordinator;constructor(t){this.coordinator=t}async execute(t){try{let e=[];for(let n of t.statements){let o=JSON.parse(n);if(!o.collectionId||typeof o.collectionId!="string")return{success:!1,error:"Invalid statement: missing collectionId"};if(!o.actions||!Array.isArray(o.actions))return{success:!1,error:`Invalid statement: collection ${o.collectionId} missing or invalid actions array`};e.push(o),await this.coordinator.applyActions([o],t.stamp.id)}return{success:!0,actions:e}}catch(e){return{success:!1,error:`Failed to execute transaction: ${e instanceof Error?e.message:String(e)}`}}}}});var mh={};at(mh,{ACTIONS_ENGINE_ID:()=>$s,ActionsEngine:()=>Ur,Atomic:()=>Ut,BTree:()=>jt,CacheSource:()=>Lr,Chain:()=>Be,Collection:()=>ve,Diary:()=>Ts,DiaryHeaderBlockType:()=>Ls,EntriesPerBlock:()=>to,KeyBound:()=>Zn,KeyRange:()=>Yn,Keyset:()=>Xn,Latches:()=>ie,Log:()=>xt,LogDataBlockType:()=>Vs,LogHeaderBlockType:()=>Fs,NetworkTransactor:()=>ei,NodeCapacity:()=>ft,Path:()=>ue,PathBranch:()=>Bt,Pending:()=>Vr,Tracker:()=>Ft,TransactionContext:()=>Cn,TransactionCoordinator:()=>kn,TransactionSession:()=>Dn,TransactionValidator:()=>Tn,TransactorSource:()=>We,Tree:()=>Os,TreeHeaderBlockType:()=>Ns,apply:()=>_,applyOperation:()=>Nt,applyOperations:()=>ai,applyTransform:()=>uf,applyTransformToStore:()=>zn,blockIdToBytes:()=>mt,blockIdsForTransforms:()=>At,concatTransform:()=>jn,concatTransforms:()=>Vn,copyTransforms:()=>qn,createActionsStatements:()=>Or,createTransactionId:()=>Qe,createTransactionStamp:()=>Je,distinctBlockActionTransforms:()=>ri,emptyTransforms:()=>sr,ensured:()=>oi,ensuredMap:()=>ph,entryAt:()=>de,get:()=>X,groupBy:()=>ni,hashString:()=>ae,isTransformsEmpty:()=>Hn,mergeTransforms:()=>ci,nameof:()=>nt,pathValid:()=>hi,priorHash$:()=>Dd,registerBlockType:()=>bt,rootId$:()=>Us,transformForBlockId:()=>Fn,transformsFromTransform:()=>$n,withOperation:()=>ff});var Kn=new Map;function bt(r,t){if(Kn.has(r))throw new Error(`Block type ${r} (${t}) already registered (${Kn.get(r)})`);return Kn.set(r,t),r}function Nt(r,[t,e,n,o]){Array.isArray(o)?r[t].splice(e,n,...structuredClone(o)):r[t]=structuredClone(o)}function ai(r,t){for(let e of t)Nt(r,e)}function ff(r,[t,e,n,o]){if(Array.isArray(o)){let s=r[t];return{...r,[t]:[...s.slice(0,e),...structuredClone(o),...s.slice(e+n)]}}else return{...r,[t]:structuredClone(o)}}function At(r){if(!r)return[];let t=Object.keys(r.inserts??{}),e=Object.keys(r.updates??{}),n=r.deletes??[];return[...new Set([...t,...e,...n])]}function sr(){return{inserts:{},updates:{},deletes:[]}}function qn(r){let t=r.updates?Object.fromEntries(Object.entries(r.updates).map(([e,n])=>[e,structuredClone(n)])):void 0;return{inserts:{...r.inserts},updates:t,deletes:r.deletes?[...r.deletes]:void 0}}function ci(r,t){return{inserts:{...r.inserts,...t.inserts},updates:{...r.updates,...t.updates},deletes:[...r.deletes??[],...t.deletes??[]]}}function Hn(r){return Object.keys(r.inserts??{}).length===0&&Object.keys(r.updates??{}).length===0&&(r.deletes?.length??0)===0}function Vn(...r){return r.reduce((t,e)=>ci(t,e),sr())}function Fn(r,t){return{...r.inserts&&t in r.inserts?{insert:r.inserts[t]}:{},...r.updates&&t in r.updates?{updates:structuredClone(r.updates[t])}:{},...r.deletes?.includes(t)?{delete:!0}:{}}}function $n(r,t){return{inserts:r.insert?{[t]:r.insert}:{},updates:r.updates?{[t]:r.updates}:{},deletes:r.delete?[t]:[]}}function zn(r,t){for(let e of r.deletes??[])t.delete(e);for(let[,e]of Object.entries(r.inserts??{}))t.insert(e);for(let[e,n]of Object.entries(r.updates??{}))for(let o of n)t.update(e,o)}function uf(r,t){if(t.insert&&(r=t.insert),r&&t.updates&&ai(r,t.updates),!t.delete)return r}function jn(r,t,e){return{inserts:{...r.inserts,...e.insert?{[t]:e.insert}:{}},updates:{...r.updates,...e.updates?{[t]:e.updates}:{}},deletes:[...r.deletes??[],...e.delete?[t]:[]]}}async function X(r,t){let e=await r.tryGet(t);if(!e)throw Error(`Missing block (${t})`);return e}function _(r,t,e){Nt(t,e),r.update(t.header.id,e)}function nt(r,t){return t??r}var fe=bt("TL","TreeLeaf"),Gn=bt("TB","TreeBranch"),yt=nt("entries"),wt=nt("partitions"),zt=nt("nodes");var ft=64,jt=class r{store;trunk;keyFromEntry;compare;_version=0;constructor(t,e,n=s=>s,o=(s,i)=>s<i?-1:s>i?1:0){this.store=t,this.trunk=e,this.keyFromEntry=n,this.compare=o}static createRoot(t){return fi(t,[])}static create(t,e,n=i=>i,o=(i,a)=>i<a?-1:i>a?1:0,s){let i=r.createRoot(t);t.insert(i);let a=e(t,i.header.id,s);return new r(t,a,n,o)}async first(){return await this.getFirst(await this.trunk.get())}async last(){return await this.getLast(await this.trunk.get())}async find(t){return await this.getPath(await this.trunk.get(),t)}async get(t){return this.at(await this.find(t))}at(t){return this.validatePath(t),t.on?this.getEntry(t):void 0}async*range(t){let e=t.first?await this.findFirst(t):t.isAscending?await this.first():await this.last(),n=t.last?await this.findLast(t):t.isAscending?await this.last():await this.first();if(!n.on)return;let o=this.keyFromPath(n),i=(t.isAscending?this.internalAscending(e):this.internalDescending(e))[Symbol.asyncIterator](),a=t.isAscending?1:-1;for await(let c of i){if(!c.on||this.compare(this.keyFromPath(c),o)*a>0)break;yield c}}isValid(t){return t.version===this._version}async insert(t){Object.freeze(t);let e=await this.internalInsert(t);return e.on&&(e.version=++this._version),e}async updateAt(t,e){this.validatePath(t),t.on&&Object.freeze(e);let n=await this.internalUpdate(t,e);return n[0].on&&(n[0].version=++this._version),n}async upsert(t){let e=await this.find(this.keyFromEntry(t));return Object.freeze(t),e.on?this.updateEntry(e,t):await this.internalInsertAt(e,t),e.version=++this._version,e}async merge(t,e){let n=await this.keyFromEntry(t),o=await this.find(n);return o.on?await this.updateAt(o,e(this.getEntry(o))):(await this.internalInsertAt(o,Object.freeze(t)),o.on=!0,o.version=++this._version,[o,!1])}async deleteAt(t){this.validatePath(t);let e=await this.internalDelete(t);return e&&++this._version,e}async drop(){let t=await this.trunk.get();for await(let e of this.nodeIds(t))this.store.delete(e)}ascending(t){return this.validatePath(t),this.internalAscending(t.clone())}descending(t){return this.validatePath(t),this.internalDescending(t.clone())}async getCount(t){let e=0,n=t?t.path.clone():await this.first();if(t?.ascending??!0)for(;n.on;)e+=n.leafNode.entries.length-n.leafIndex,n.leafIndex=n.leafNode.entries.length-1,await this.internalNext(n);else for(;n.on;)e+=n.leafIndex+1,n.leafIndex=0,await this.internalPrior(n);return e}async next(t){let e=t.clone();return await this.moveNext(e),e}async moveNext(t){this.validatePath(t),await this.internalNext(t)}async prior(t){let e=t.clone();return this.movePrior(e),e}async movePrior(t){this.validatePath(t),await this.internalPrior(t)}keyFromPath(t){return this.keyFromEntry(t.leafNode.entries[t.leafIndex])}async*internalAscending(t){for(this.validatePath(t);t.on;)yield t,await this.moveNext(t)}async*internalDescending(t){for(this.validatePath(t);t.on;)yield t,await this.movePrior(t)}async findFirst(t){let e=await this.find(t.first.key);return(!e.on||t.first&&!t.first.inclusive)&&(t.isAscending?await this.internalNext(e):await this.internalPrior(e)),e}async findLast(t){let e=await this.find(t.last.key);return(!e.on||t.last&&!t.last.inclusive)&&(t.isAscending?await this.internalPrior(e):await this.internalNext(e)),e}async getPath(t,e){if(t.header.type===fe){let n=t,[o,s]=this.indexOfEntry(n.entries,e);return new ue([],n,s,o,this._version)}else{let n=t,o=this.indexOfKey(n.partitions,e),s=await this.getPath(await X(this.store,n.nodes[o]),e);return s.branches.unshift(new Bt(n,o)),s}}indexOfEntry(t,e){let n=0,o=t.length-1,s=0,i=-1;for(;n<=o;){if(s=n+o>>>1,i=this.compare(e,this.keyFromEntry(t[s])),i===0)return[!0,s];i<0?o=s-1:n=s+1}return[!1,n]}indexOfKey(t,e){let n=0,o=t.length-1,s=0,i=-1;for(;n<=o;){if(s=n+o>>>1,i=this.compare(e,t[s]),i===0)return s+1;i<0?o=s-1:n=s+1}return n}async internalNext(t){if(t.on)if(t.leafIndex>=t.leafNode.entries.length-1){let e=0,n=!1,o=t.branches.length-1;for(;e<=o&&!n;){let s=t.branches[o-e];s.index===s.node.partitions.length?++e:n=!0}if(!n)t.leafIndex=t.leafNode.entries.length,t.on=!1;else{t.branches.splice(-e,e);let s=t.branches.at(-1);++s.index,this.moveToFirst(await X(this.store,s.node.nodes[s.index]),t)}}else++t.leafIndex,t.on=!0;else if(t.on=t.branches.every(e=>e.index>=0&&e.index<e.node.nodes.length)&&t.leafIndex>=0&&t.leafIndex<t.leafNode.entries.length,t.on)return}async internalPrior(t){if(this.validatePath(t),t.leafIndex<=0){let e=0,n=!1,o=t.branches.length-1;for(;e<=o&&!n;)t.branches[o-e].index===0?++e:n=!0;if(!n)t.leafIndex=0,t.on=!1;else{t.branches.splice(-e,e);let s=t.branches.at(-1);--s.index,await this.moveToLast(await X(this.store,s.node.nodes[s.index]),t)}}else--t.leafIndex,t.on=!0}async internalUpdate(t,e){if(t.on){let n=this.keyFromPath(t),o=this.keyFromEntry(e);if(this.compare(n,o)!==0){let s=await this.internalInsert(e);return s.on&&(this.internalDelete(await this.find(n)),s=await this.find(o)),[s,!1]}else this.updateEntry(t,e)}return[t,!0]}async internalDelete(t){if(t.on){if(_(this.store,t.leafNode,[yt,t.leafIndex,1,[]]),t.branches.length>0){if(t.leafIndex===0&&t.leafNode.entries.length>0){let n=t.branches.at(-1);this.updatePartition(n.index,t,t.branches.length-1,this.keyFromPath(t))}let e=await this.rebalanceLeaf(t,t.branches.length);e&&await this.trunk.set(e)}return t.on=!1,!0}else return!1}async internalInsert(t){let e=await this.find(this.keyFromEntry(t));return e.on?(e.on=!1,e):(await this.internalInsertAt(e,t),e.on=!0,e)}async internalInsertAt(t,e){let n=this.leafInsert(t,e),o=t.branches.length-1;for(;n&&o>=0;)n=await this.branchInsert(t,o,n),--o;if(n){let s=ui(this.store,[n.key],[await this.trunk.getId(),n.right.header.id]);await this.store.insert(s),await this.trunk.set(s),t.branches.unshift(new Bt(s,n.indexDelta))}}async moveToFirst(t,e){if(t.header.type===fe){let n=t;e.leafNode=n,e.leafIndex=0,e.on=n.entries.length>0}else e.branches.push(new Bt(t,0)),await this.moveToFirst(await X(this.store,t.nodes[0]),e)}async moveToLast(t,e){if(t.header.type===fe){let n=t,o=n.entries.length;e.leafNode=n,e.on=o>0,e.leafIndex=o>0?o-1:0}else{let n=t,o=new Bt(n,n.partitions.length);e.branches.push(o),await this.moveToLast(await X(this.store,n.nodes[o.index]),e)}}async getFirst(t){if(t.header.type===fe){let e=t;return new ue([],e,0,e.entries.length>0,this._version)}else{let e=t,n=await this.getFirst(await X(this.store,e.nodes[0]));return n.branches.unshift(new Bt(e,0)),n}}async getLast(t){if(t.header.type===fe){let e=t,n=e.entries.length;return new ue([],e,n>0?n-1:0,n>0,this._version)}else{let e=t,n=e.nodes.length-1,o=await this.getLast(await X(this.store,e.nodes[n]));return o.branches.unshift(new Bt(e,n)),o}}leafInsert(t,e){let{leafNode:n,leafIndex:o}=t;if(n.entries.length<ft){_(this.store,n,[yt,o,0,[e]]);return}let s=n.entries.length+1>>>1,i=n.entries.slice(s);o>=s&&i.splice(o-s,0,e);let a=fi(this.store,i);return this.store.insert(a),_(this.store,n,[yt,s,n.entries.length-s,[]]),o<s?_(this.store,n,[yt,o,0,[e]]):(t.leafNode=a,t.leafIndex-=s),new $r(this.keyFromEntry(i[0]),a,o<s?0:1)}async branchInsert(t,e,n){let o=t.branches[e],{index:s,node:i}=o;if(o.index+=n.indexDelta,i.nodes.length<ft){_(this.store,i,[wt,s,0,[n.key]]),_(this.store,i,[zt,s+1,0,[n.right.header.id]]);return}let a=i.nodes.length+1>>>1,c=i.partitions.slice(a),f=i.nodes.slice(a),l=o.index<a?0:1;l&&(o.index-=a,c.splice(o.index,0,n.key),f.splice(o.index+1,0,n.right.header.id));let u=ui(this.store,c,f),h=i.partitions[a-1];return _(this.store,i,[wt,a-1,c.length+1,[]]),_(this.store,i,[zt,a,f.length,[]]),o.index<a&&(_(this.store,i,[wt,s,0,[n.key]]),_(this.store,i,[zt,s+1,0,[n.right.header.id]])),new $r(h,u,l)}async rebalanceLeaf(t,e){if(e===0||t.leafNode.entries.length>=ft>>>1)return;let n=t.leafNode,o=t.branches.at(e-1),s=o.index,i=o.node,a=i.nodes[s+1],c=a?await X(this.store,a):void 0;if(c&&c.entries.length>ft>>>1){let u=c.entries[0];_(this.store,c,[yt,0,1,[]]),_(this.store,n,[yt,n.entries.length,0,[u]]),this.updatePartition(s+1,t,e-1,this.keyFromEntry(u));return}let f=i.nodes[s-1],l=f?await X(this.store,f):void 0;if(l&&l.entries.length>ft>>>1){let u=l.entries[l.entries.length-1];_(this.store,l,[yt,l.entries.length-1,1,[]]),_(this.store,n,[yt,0,0,[u]]),this.updatePartition(s,t,e-1,this.keyFromEntry(u)),t.leafIndex+=1;return}if(c&&c.entries.length+n.entries.length<=ft)return _(this.store,n,[yt,n.entries.length,0,c.entries]),this.deletePartition(i,s),s===0&&this.updatePartition(s,t,e-1,this.keyFromEntry(n.entries[0])),this.store.delete(c.header.id),await this.rebalanceBranch(t,e-1);if(l&&l.entries.length+n.entries.length<=ft)return t.leafNode=l,t.leafIndex+=l.entries.length,_(this.store,l,[yt,l.entries.length,0,n.entries]),this.deletePartition(i,s-1),this.store.delete(n.header.id),await this.rebalanceBranch(t,e-1)}async rebalanceBranch(t,e){let n=t.branches[e],o=n.node;if(e===0&&o.partitions.length===0)return t.branches[e+1]?.node??t.leafNode;if(e===0||o.nodes.length>=ft>>>1)return;let s=t.branches.at(e-1),i=s.index,a=s.node,c=a.nodes[i+1],f=c?await X(this.store,c):void 0;if(f&&f.nodes.length>ft>>>1){let h=f.nodes[0],m=f.partitions[0];this.insertPartition(o,o.partitions.length,a.partitions[i],h),this.deletePartition(f,0,0),this.updatePartition(i+1,t,e-1,m);return}let l=a.nodes[i-1],u=l?await X(this.store,l):void 0;if(u&&u.nodes.length>ft>>>1){let h=u.nodes[u.nodes.length-1],m=u.partitions[u.partitions.length-1];this.insertPartition(o,0,a.partitions[i-1],h,0),this.deletePartition(u,u.partitions.length-1),n.index+=1,this.updatePartition(i,t,e-1,m);return}if(f&&f.nodes.length+o.nodes.length<=ft){let h=a.partitions[i];return this.deletePartition(a,i),_(this.store,o,[wt,o.partitions.length,0,[h]]),_(this.store,o,[wt,o.partitions.length,0,f.partitions]),_(this.store,o,[zt,o.nodes.length,0,f.nodes]),i===0&&a.partitions.length>0&&this.updatePartition(i,t,e-1,a.partitions[0]),this.store.delete(f.header.id),this.rebalanceBranch(t,e-1)}if(u&&u.nodes.length+o.nodes.length<=ft){let h=a.partitions[i-1];return this.deletePartition(a,i-1),_(this.store,u,[wt,u.partitions.length,0,[h]]),_(this.store,u,[wt,u.partitions.length,0,o.partitions]),_(this.store,u,[zt,u.nodes.length,0,o.nodes]),n.node=u,n.index+=u.nodes.length,this.store.delete(o.header.id),this.rebalanceBranch(t,e-1)}}updatePartition(t,e,n,o){let s=e.branches[n];t>0?_(this.store,s.node,[wt,t-1,1,[o]]):n!==0&&this.updatePartition(e.branches[n-1].index,e,n-1,o)}insertPartition(t,e,n,o,s=1){_(this.store,t,[wt,e,0,[n]]),_(this.store,t,[zt,e+s,0,[o]])}deletePartition(t,e,n=1){_(this.store,t,[wt,e,1,[]]),_(this.store,t,[zt,e+n,1,[]])}validatePath(t){if(!this.isValid(t))throw new Error("Path is invalid due to mutation of the tree")}async*nodeIds(t){if(t.header.type===Gn){let e=await Promise.all(t.nodes.map(n=>X(this.store,n)));for(let n of e)yield*this.nodeIds(n)}yield t.header.id}getEntry(t){return t.leafNode.entries[t.leafIndex]}updateEntry(t,e){_(this.store,t.leafNode,[yt,t.leafIndex,1,[e]])}},$r=class{key;right;indexDelta;constructor(t,e,n){this.key=t,this.right=e,this.indexDelta=n}};function fi(r,t){return{header:r.createBlockHeader(fe),entries:t}}function ui(r,t,e){return{header:r.createBlockHeader(Gn),partitions:t,nodes:e}}var Zn=class{key;inclusive;constructor(t,e=!0){this.key=t,this.inclusive=e}},Yn=class{first;last;isAscending;constructor(t,e,n=!0){this.first=t,this.last=e,this.isAscending=n}};var Xn=class extends jt{};var Bt=class r{node;index;constructor(t,e){this.node=t,this.index=e}clone(){return new r(this.node,this.index)}},ue=class r{branches;leafNode;leafIndex;on;version;constructor(t,e,n,o,s){this.branches=t,this.leafNode=e,this.leafIndex=n,this.on=o,this.version=s}isEqual(t){return this.leafNode===t.leafNode&&this.leafIndex===t.leafIndex&&this.on===t.on&&this.version===t.version}clone(){return new r(this.branches.map(t=>t.clone()),this.leafNode,this.leafIndex,this.on,this.version)}};var le=nt("entries"),li=nt("priorId"),Wn=nt("nextId"),Jn=bt("CHD","ChainDataBlock"),Qn=nt("headId"),zr=nt("tailId"),di=bt("CHH","ChainHeaderBlock");var to=32,Be=class r{store;id;options;constructor(t,e,n){this.store=t,this.id=e,this.options=n}static async create(t,e){let n=r.createTailBlock(t,e),o={...e?.createHeaderBlock?.(e?.newId)??{header:t.createBlockHeader(di,e?.newId)},headId:n.header.id,tailId:n.header.id};return t.insert(o),t.insert(n),new r(t,o.header.id,e)}static createTailBlock(t,e){return{...e?.createDataBlock?.()??{header:t.createBlockHeader(Jn)},entries:[],priorId:void 0,nextId:void 0}}static async open(t,e,n){let o=await t.tryGet(e);if(!o)return;let s=o;if(!Object.hasOwn(s,"headId")||!Object.hasOwn(s,"tailId")){let i=r.createTailBlock(t,n);t.insert(i),_(t,o,[Qn,0,0,i.header.id]),_(t,o,[zr,0,0,i.header.id])}return new r(t,e,n)}async add(...t){let e=await this.getTail();if(!e)throw new Error("Cannot add to non-existent chain");let{headerBlock:n,block:o}=e,s=o,i=new Ut(this.store),a=t.slice(0,to-s.entries.length);for(a.length>0&&(_(i,s,[le,s.entries.length,0,a]),t=t.slice(a.length));t.length>0;){let c={...this.options?.createDataBlock?.()??{header:this.store.createBlockHeader(Jn)},entries:t.splice(0,Math.min(to,t.length)),priorId:s.header.id,nextId:void 0};await this.options?.newBlock?.(c,o),i.insert(c),_(i,s,[Wn,0,0,c.header.id]),s=c}return s!==o&&_(i,n,[zr,0,0,s.header.id]),i.commit(),{headerBlock:n,block:s,index:s.entries.length-1}}updateAt(t,e){if(!hi(t))throw new Error("Invalid path");let{index:n,block:o}=t;_(this.store,o,[le,n,1,[e]])}async pop(t=1){if(t<=0)return[];let e=await this.getTail();if(!e)return[];let{headerBlock:n,block:o}=e,s=o,i=[],a=new Ut(this.store);for(;t>0;)if(s.entries.length>t){let c=s.entries.slice(-t);i.unshift(...c),_(a,s,[le,s.entries.length-t,t,[]]);break}else if(i.unshift(...s.entries),t-=s.entries.length,s.priorId)a.delete(s.header.id),s=await a.tryGet(s.priorId),_(a,s,[Wn,0,0,void 0]);else{_(a,s,[le,0,s.entries.length,[]]);break}return s!==o&&_(a,n,[zr,0,0,s.header.id]),a.commit(),i}async dequeue(t=1){if(t<=0)return[];let e=new Ut(this.store),n=await this.getHead();if(!n)return[];let{headerBlock:o,block:s}=n,i=s,a=[];for(;t>0;)if(i.entries.length>t){a.push(...i.entries.slice(0,t)),_(e,i,[le,0,t,[]]);break}else if(a.push(...i.entries),t-=i.entries.length,i.nextId)e.delete(i.header.id),i=await e.tryGet(i.nextId),_(e,i,[li,0,0,void 0]);else{_(e,i,[le,0,i.entries.length,[]]);break}return i!==s&&_(e,o,[Qn,0,0,i.header.id]),e.commit(),a}async*select(t,e=!0){let n=t??(e?await this.getHead():await this.getTail());if(!n)return;let o=n.block,s=n.index;if(e)for(;o;){for(;s<o.entries.length;++s)yield{headerBlock:n.headerBlock,block:o,index:s};o=o.nextId?await this.store.tryGet(o.nextId):void 0,s=0}else for(;o;){for(;s>=0;--s)yield{headerBlock:n.headerBlock,block:o,index:s};o=o.priorId?await this.store.tryGet(o.priorId):void 0,s=(o?.entries.length??0)-1}}async next(t){let{headerBlock:e,block:n,index:o}=t;return o<n.entries.length-1||!n.nextId?{headerBlock:e,block:n,index:o+1}:{headerBlock:e,block:await this.store.tryGet(n.nextId),index:0}}async prev(t){let{headerBlock:e,block:n,index:o}=t;if(o>0||!n.priorId)return{headerBlock:e,block:n,index:o-1};let s=await this.store.tryGet(n.priorId);return{headerBlock:e,block:s,index:s.entries.length-1}}async getTail(t){let e=t??await this.getHeader(),n=e?await this.store.tryGet(e.tailId):void 0;for(;n?.nextId;)n=await this.store.tryGet(n.nextId);return n?{headerBlock:e,block:n,index:n.entries.length-1}:void 0}async getHead(t){let e=t??await this.getHeader(),n=e?await this.store.tryGet(e.headId):void 0;for(;n?.priorId;)n=await this.store.tryGet(n.priorId);return n?{headerBlock:e,block:n,index:0}:void 0}async getHeader(){return await this.store.tryGet(this.id)}};function hi(r){return r.block.entries.length>r.index&&r.index>=0}function de(r){return r.block.entries[r.index]}var ir=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},jr=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var pi={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new jr("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Gr=pi;var gt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Zr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Yr=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Xr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var ar=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var eo=Symbol.for("@libp2p/peer-id");var cp=new Uint8Array(0);function mi(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Gt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function lf(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,b=0,p=0,S=d.length;p!==S&&d[p]===0;)p++,g++;for(var y=(S-p)*l+1>>>0,A=new Uint8Array(y);p!==S;){for(var k=d[p],N=0,C=y-1;(k!==0||N<b)&&C!==-1;C--,N++)k+=256*A[C]>>>0,A[C]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");b=N,p++}for(var E=y-b;E!==y&&A[E]===0;)E++;for(var I=c.repeat(g);E<y;++E)I+=r.charAt(A[E]);return I}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var b=0,p=0;d[g]===c;)b++,g++;for(var S=(d.length-g)*f+1>>>0,y=new Uint8Array(S);d[g];){var A=e[d.charCodeAt(g)];if(A===255)return;for(var k=0,N=S-1;(A!==0||k<p)&&N!==-1;N--,k++)A+=a*y[N]>>>0,y[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=k,g++}if(d[g]!==" "){for(var C=S-p;C!==S&&y[C]===0;)C++;for(var E=new Uint8Array(b+(S-C)),I=b;C!==S;)E[I++]=y[C++];return E}}}function m(d){var g=h(d);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:h,decode:m}}var df=lf,hf=df,yi=hf;var ro=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},no=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return gi(this,t)}},oo=class{decoders;constructor(t){this.decoders=t}or(t){return gi(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function gi(r,t){return new oo({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var so=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new ro(t,e,n),this.decoder=new no(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function xi({name:r,prefix:t,encode:e,decode:n}){return new so(r,t,e,n)}function ke({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=yi(e,r);return xi({prefix:t,name:r,encode:n,decode:s=>Gt(o(s))})}function pf(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=t[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function mf(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function yf(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function kt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=yf(n);return xi({prefix:t,name:r,encode(s){return mf(s,n,e)},decode(s){return pf(s,o,e,r)}})}var ot=ke({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),mp=ke({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var cr=kt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),xp=kt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),bp=kt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),wp=kt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ep=kt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vp=kt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ip=kt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Sp=kt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ap=kt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Wr=ke({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Cp=ke({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gf=Ei,bi=128,xf=127,bf=~xf,wf=Math.pow(2,31);function Ei(r,t,e){t=t||[],e=e||0;for(var n=e;r>=wf;)t[e++]=r&255|bi,r/=128;for(;r&bf;)t[e++]=r&255|bi,r>>>=7;return t[e]=r|0,Ei.bytes=e-n+1,t}var Ef=io,vf=128,wi=127;function io(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw io.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&wi)<<o:(i&wi)*Math.pow(2,o),o+=7}while(i>=vf);return io.bytes=s-n,e}var If=Math.pow(2,7),Sf=Math.pow(2,14),Af=Math.pow(2,21),Bf=Math.pow(2,28),kf=Math.pow(2,35),Cf=Math.pow(2,42),Df=Math.pow(2,49),Tf=Math.pow(2,56),Lf=Math.pow(2,63),Nf=function(r){return r<If?1:r<Sf?2:r<Af?3:r<Bf?4:r<kf?5:r<Cf?6:r<Df?7:r<Tf?8:r<Lf?9:10},Uf={encode:gf,decode:Ef,encodingLength:Nf},Of=Uf,fr=Of;function ur(r,t=0){return[fr.decode(r,t),fr.decode.bytes]}function Ce(r,t,e=0){return fr.encode(r,t,e),t}function De(r){return fr.encodingLength(r)}function Le(r,t){let e=t.byteLength,n=De(r),o=n+De(e),s=new Uint8Array(o+e);return Ce(r,s,0),Ce(e,s,n),s.set(t,o),new Te(r,e,t,s)}function Ii(r){let t=Gt(r),[e,n]=ur(t),[o,s]=ur(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Te(e,o,i,t)}function Si(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&mi(r.bytes,e.bytes)}}var Te=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Ai(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return _f(e,co(r),t??ot.encoder);default:return Pf(e,co(r),t??cr.encoder)}}var Bi=new WeakMap;function co(r){let t=Bi.get(r);if(t==null){let e=new Map;return Bi.set(r,e),e}return t}var Zt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==lr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Mf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Le(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Si(t.multihash,n.multihash)}toString(t){return Ai(this,t)}toJSON(){return{"/":Ai(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??ki(n,o,s.bytes))}else if(e[Kf]===!0){let{version:n,multihash:o,code:s}=e,i=Ii(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==lr)throw new Error(`Version 0 CID must use dag-pb (code: ${lr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=ki(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,lr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Gt(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Te(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,h]=ur(t.subarray(e));return e+=h,u},o=n(),s=lr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),f=e+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(t,e){let[n,o]=Rf(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return co(s).set(n,t),s}};function Rf(r,t){switch(r[0]){case"Q":{let e=t??ot;return[ot.prefix,e.decode(`${ot.prefix}${r}`)]}case ot.prefix:{let e=t??ot;return[ot.prefix,e.decode(r)]}case cr.prefix:{let e=t??cr;return[cr.prefix,e.decode(r)]}case Wr.prefix:{let e=t??Wr;return[Wr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function _f(r,t,e){let{prefix:n}=e;if(n!==ot.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Pf(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var lr=112,Mf=18;function ki(r,t,e){let n=De(r),o=n+De(t),s=new Uint8Array(o+e.byteLength);return Ce(r,s,0),Ce(t,s,n),s.set(e,o),s}var Kf=Symbol.for("@ipld/js-cid/CID");var Ci=0,qf="identity",Di=Gt;function Hf(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Le(Ci,Di(r))}var Ne={code:Ci,name:qf,encode:Di,digest:Hf};function Et(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ot(r=0){return new Uint8Array(r)}function ut(r=0){return new Uint8Array(r)}function Jr(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=ut(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Li=Symbol.for("@achingbrain/uint8arraylist");function Ti(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Qr(r){return!!r?.[Li]}var lt=class r{bufs;length;[Li]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Qr(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Qr(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Ti(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ti(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Qr(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Jr(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Jr(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let f=t>=a&&t<c,l=e>a&&e<=c;if(f&&l){if(t===a&&e===c){n.push(i);break}let u=t-a;n.push(i.subarray(u,u+(e-t)));break}if(f){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(l){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Qr(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,l;for(let u=e;u<=c;u+=l){l=0;for(let h=f;h>=0;h--){let m=this.get(u+h);if(n[h]!==m){l=Math.max(1,h-a[m]);break}}if(l===0)return u}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=ut(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=Ot(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=Ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=Ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=ut(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=Ot(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=Ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=Ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=Ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=Ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Et(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var po={};at(po,{base10:()=>Zf});var Jp=new Uint8Array(0);function Ni(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Rt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Ui(r){return new TextEncoder().encode(r)}function Oi(r){return new TextDecoder().decode(r)}function Vf(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,b=0,p=0,S=d.length;p!==S&&d[p]===0;)p++,g++;for(var y=(S-p)*l+1>>>0,A=new Uint8Array(y);p!==S;){for(var k=d[p],N=0,C=y-1;(k!==0||N<b)&&C!==-1;C--,N++)k+=256*A[C]>>>0,A[C]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");b=N,p++}for(var E=y-b;E!==y&&A[E]===0;)E++;for(var I=c.repeat(g);E<y;++E)I+=r.charAt(A[E]);return I}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var b=0,p=0;d[g]===c;)b++,g++;for(var S=(d.length-g)*f+1>>>0,y=new Uint8Array(S);d[g];){var A=e[d.charCodeAt(g)];if(A===255)return;for(var k=0,N=S-1;(A!==0||k<p)&&N!==-1;N--,k++)A+=a*y[N]>>>0,y[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=k,g++}if(d[g]!==" "){for(var C=S-p;C!==S&&y[C]===0;)C++;for(var E=new Uint8Array(b+(S-C)),I=b;C!==S;)E[I++]=y[C++];return E}}}function m(d){var g=h(d);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:h,decode:m}}var Ff=Vf,$f=Ff,_i=$f;var fo=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},uo=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Pi(this,t)}},lo=class{decoders;constructor(t){this.decoders=t}or(t){return Pi(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Pi(r,t){return new lo({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ho=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new fo(t,e,n),this.decoder=new uo(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ue({name:r,prefix:t,encode:e,decode:n}){return new ho(r,t,e,n)}function Yt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=_i(e,r);return Ue({prefix:t,name:r,encode:n,decode:s=>Rt(o(s))})}function zf(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=t[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function jf(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function Gf(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function G({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Gf(n);return Ue({prefix:t,name:r,encode(s){return jf(s,n,e)},decode(s){return zf(s,o,e,r)}})}var Zf=Yt({prefix:"9",name:"base10",alphabet:"0123456789"});var mo={};at(mo,{base16:()=>Yf,base16upper:()=>Xf});var Yf=G({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xf=G({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var yo={};at(yo,{base2:()=>Wf});var Wf=G({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var go={};at(go,{base256emoji:()=>ru});var Mi=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Jf=Mi.reduce((r,t,e)=>(r[e]=t,r),[]),Qf=Mi.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function tu(r){return r.reduce((t,e)=>(t+=Jf[e],t),"")}function eu(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Qf[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var ru=Ue({prefix:"\u{1F680}",name:"base256emoji",encode:tu,decode:eu});var xo={};at(xo,{base32:()=>Oe,base32hex:()=>iu,base32hexpad:()=>cu,base32hexpadupper:()=>fu,base32hexupper:()=>au,base32pad:()=>ou,base32padupper:()=>su,base32upper:()=>nu,base32z:()=>uu});var Oe=G({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),nu=G({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ou=G({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),su=G({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),iu=G({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),au=G({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cu=G({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),fu=G({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),uu=G({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var bo={};at(bo,{base36:()=>dr,base36upper:()=>lu});var dr=Yt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),lu=Yt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var wo={};at(wo,{base58btc:()=>Ct,base58flickr:()=>du});var Ct=Yt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),du=Yt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Eo={};at(Eo,{base64:()=>hu,base64pad:()=>pu,base64url:()=>mu,base64urlpad:()=>yu});var hu=G({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),pu=G({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),mu=G({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),yu=G({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var vo={};at(vo,{base8:()=>gu});var gu=G({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Io={};at(Io,{identity:()=>xu});var xu=Ue({prefix:"\0",name:"identity",encode:r=>Oi(r),decode:r=>Ui(r)});var p0=new TextEncoder,m0=new TextDecoder;var Ao={};at(Ao,{identity:()=>Hu});var Eu=Hi,Ki=128,vu=127,Iu=~vu,Su=Math.pow(2,31);function Hi(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Su;)t[e++]=r&255|Ki,r/=128;for(;r&Iu;)t[e++]=r&255|Ki,r>>>=7;return t[e]=r|0,Hi.bytes=e-n+1,t}var Au=So,Bu=128,qi=127;function So(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw So.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&qi)<<o:(i&qi)*Math.pow(2,o),o+=7}while(i>=Bu);return So.bytes=s-n,e}var ku=Math.pow(2,7),Cu=Math.pow(2,14),Du=Math.pow(2,21),Tu=Math.pow(2,28),Lu=Math.pow(2,35),Nu=Math.pow(2,42),Uu=Math.pow(2,49),Ou=Math.pow(2,56),Ru=Math.pow(2,63),_u=function(r){return r<ku?1:r<Cu?2:r<Du?3:r<Tu?4:r<Lu?5:r<Nu?6:r<Uu?7:r<Ou?8:r<Ru?9:10},Pu={encode:Eu,decode:Au,encodingLength:_u},Mu=Pu,hr=Mu;function pr(r,t=0){return[hr.decode(r,t),hr.decode.bytes]}function Re(r,t,e=0){return hr.encode(r,t,e),t}function _e(r){return hr.encodingLength(r)}function Me(r,t){let e=t.byteLength,n=_e(r),o=n+_e(e),s=new Uint8Array(o+e);return Re(r,s,0),Re(e,s,n),s.set(t,o),new Pe(r,e,t,s)}function Vi(r){let t=Rt(r),[e,n]=pr(t),[o,s]=pr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Pe(e,o,i,t)}function Fi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Ni(r.bytes,e.bytes)}}var Pe=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var $i=0,Ku="identity",zi=Rt;function qu(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Me($i,zi(r))}var Hu={code:$i,name:Ku,encode:zi,digest:qu};var Co={};at(Co,{sha256:()=>Fu,sha512:()=>$u});var Vu=20;function ko({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new Bo(r,t,e,n,o)}var Bo=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??Vu,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?ji(n,this.code,e?.truncate):n.then(o=>ji(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function ji(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Me(t,r)}function Zi(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Fu=ko({name:"sha2-256",code:18,encode:Zi("SHA-256")}),$u=ko({name:"sha2-512",code:19,encode:Zi("SHA-512")});function Yi(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return ju(e,Do(r),t??Ct.encoder);default:return Gu(e,Do(r),t??Oe.encoder)}}var Xi=new WeakMap;function Do(r){let t=Xi.get(r);if(t==null){let e=new Map;return Xi.set(r,e),e}return t}var en=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==yr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Zu)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Me(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Fi(t.multihash,n.multihash)}toString(t){return Yi(this,t)}toJSON(){return{"/":Yi(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Wi(n,o,s.bytes))}else if(e[Yu]===!0){let{version:n,multihash:o,code:s}=e,i=Vi(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==yr)throw new Error(`Version 0 CID must use dag-pb (code: ${yr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Wi(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,yr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Rt(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Pe(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,h]=pr(t.subarray(e));return e+=h,u},o=n(),s=yr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),f=e+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(t,e){let[n,o]=zu(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Do(s).set(n,t),s}};function zu(r,t){switch(r[0]){case"Q":{let e=t??Ct;return[Ct.prefix,e.decode(`${Ct.prefix}${r}`)]}case Ct.prefix:{let e=t??Ct;return[Ct.prefix,e.decode(r)]}case Oe.prefix:{let e=t??Oe;return[Oe.prefix,e.decode(r)]}case dr.prefix:{let e=t??dr;return[dr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function ju(r,t,e){let{prefix:n}=e;if(n!==Ct.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Gu(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var yr=112,Zu=18;function Wi(r,t,e){let n=_e(r),o=n+_e(t),s=new Uint8Array(o+e.byteLength);return Re(r,s,0),Re(t,s,n),s.set(e,o),s}var Yu=Symbol.for("@ipld/js-cid/CID");var To={...Io,...yo,...vo,...po,...mo,...xo,...bo,...wo,...Eo,...go},P0={...Co,...Ao};function Qi(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ji=Qi("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Lo=Qi("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=ut(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Xu={utf8:Ji,"utf-8":Ji,hex:To.base16,latin1:Lo,ascii:Lo,binary:Lo,...To},rn=Xu;function Xt(r,t="utf8"){let e=rn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Y(r,t="utf8"){let e=rn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Wu=parseInt("11111",2),No=parseInt("10000000",2),Ju=parseInt("01111111",2),ta={0:gr,1:gr,2:Qu,3:rl,4:nl,5:el,6:tl,16:gr,22:gr,48:gr};function Uo(r,t={offset:0}){let e=r[t.offset]&Wu;if(t.offset++,ta[e]!=null)return ta[e](r,t);throw new Error("No decoder for tag "+e)}function xr(r,t){let e=0;if((r[t.offset]&No)===No){let n=r[t.offset]&Ju,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function gr(r,t){xr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=Uo(r,t);if(n===null)break;e.push(n)}return e}function Qu(r,t){let e=xr(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function tl(r,t){let e=xr(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let f=r[t.offset];if(t.offset++,c.push(f&127),f<128){c.reverse();let l=0;for(let u=0;u<c.length;u++)l+=c[u]<<u*7;a+=`.${l}`,c=[]}}return a}function el(r,t){return t.offset++,null}function rl(r,t){let e=xr(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function nl(r,t){let e=xr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function ol(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new lt;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Oo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=ol(r.byteLength);return new lt(Uint8Array.from([t.byteLength|No]),t)}function ea(r){let t=new lt,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new lt(Uint8Array.from([2]),Oo(t),t)}function ra(r){let t=Uint8Array.from([0]),e=new lt(t,r);return new lt(Uint8Array.from([3]),Oo(e),e)}function nn(r,t=48){let e=new lt;for(let n of r)e.append(n);return new lt(Uint8Array.from([t]),Oo(e),e)}async function na(r,t,e,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,e.subarray());return n?.signal?.throwIfAborted(),s}var sl=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),il=Uint8Array.from([6,5,43,129,4,0,34]),al=Uint8Array.from([6,5,43,129,4,0,35]),cl={ext:!0,kty:"EC",crv:"P-256"},fl={ext:!0,kty:"EC",crv:"P-384"},ul={ext:!0,kty:"EC",crv:"P-521"},Ro=32,_o=48,Po=66;function oa(r){let t=Uo(r);return sa(t)}function sa(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Ro*2+1)return n=Y(t.subarray(e,e+Ro),"base64url"),o=Y(t.subarray(e+Ro),"base64url"),new Ke({...cl,key_ops:["verify"],x:n,y:o});if(t.byteLength===_o*2+1)return n=Y(t.subarray(e,e+_o),"base64url"),o=Y(t.subarray(e+_o),"base64url"),new Ke({...fl,key_ops:["verify"],x:n,y:o});if(t.byteLength===Po*2+1)return n=Y(t.subarray(e,e+Po),"base64url"),o=Y(t.subarray(e+Po),"base64url"),new Ke({...ul,key_ops:["verify"],x:n,y:o});throw new gt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function ia(r){return nn([ea(Uint8Array.from([1])),nn([ll(r.crv)],160),nn([ra(new lt(Uint8Array.from([4]),Xt(r.x??"","base64url"),Xt(r.y??"","base64url")))],161)]).subarray()}function ll(r){if(r==="P-256")return sl;if(r==="P-384")return il;if(r==="P-521")return al;throw new gt(`Invalid curve ${r}`)}var Ke=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=ia(this.jwk)),this._raw}toMultihash(){return Ne.digest(qe(this))}toCID(){return Zt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}async verify(t,e,n){return na(this.jwk,e,t,n)}};function he(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Dt(r,t=""){if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new Error(`${e}expected integer >= 0, got ${r}`)}}function K(r,t,e=""){let n=he(r),o=r?.length,s=t!==void 0;if(!n||s&&o!==t){let i=e&&`"${e}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function on(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Dt(r.outputLen),Dt(r.blockLen)}function He(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function ca(r,t){K(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new Error('"digestInto() output" expected to be of length >='+e)}function Pt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function sn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function vt(r,t){return r<<32-t|r>>>t}var fa=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",dl=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Mt(r){if(K(r),fa)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=dl[r[e]];return t}var _t={_0:48,_9:57,A:65,F:70,a:97,f:102};function aa(r){if(r>=_t._0&&r<=_t._9)return r-_t._0;if(r>=_t.A&&r<=_t.F)return r-(_t.A-10);if(r>=_t.a&&r<=_t.f)return r-(_t.a-10)}function Kt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(fa)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=aa(r.charCodeAt(s)),a=aa(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function ct(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];K(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function Mo(r,t={}){let e=(o,s)=>r(s).update(o).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=o=>r(o),Object.assign(e,t),Object.freeze(e)}function Wt(r=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(r))}var Ko=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function ua(r,t,e){return r&t^~r&e}function la(r,t,e){return r&t^r&e^t&e}var br=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,o){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=sn(this.buffer)}update(t){He(this),K(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=sn(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){He(this),ca(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,Pt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)e[u]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=sn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,l=this.get();if(f>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<f;u++)a.setUint32(4*u,l[u],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},qt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var tt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var an=BigInt(4294967295),da=BigInt(32);function hl(r,t=!1){return t?{h:Number(r&an),l:Number(r>>da&an)}:{h:Number(r>>da&an)|0,l:Number(r&an)|0}}function ha(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=hl(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var qo=(r,t,e)=>r>>>e,Ho=(r,t,e)=>r<<32-e|t>>>e,pe=(r,t,e)=>r>>>e|t<<32-e,me=(r,t,e)=>r<<32-e|t>>>e,wr=(r,t,e)=>r<<64-e|t>>>e-32,Er=(r,t,e)=>r>>>e-32|t<<64-e;function Tt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var pa=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),ma=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,ya=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),ga=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,xa=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),ba=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var ml=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jt=new Uint32Array(64),Vo=class extends br{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let u=0;u<16;u++,e+=4)Jt[u]=t.getUint32(e,!1);for(let u=16;u<64;u++){let h=Jt[u-15],m=Jt[u-2],d=vt(h,7)^vt(h,18)^h>>>3,g=vt(m,17)^vt(m,19)^m>>>10;Jt[u]=g+Jt[u-7]+d+Jt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:l}=this;for(let u=0;u<64;u++){let h=vt(a,6)^vt(a,11)^vt(a,25),m=l+h+ua(a,c,f)+ml[u]+Jt[u]|0,g=(vt(n,2)^vt(n,13)^vt(n,22))+la(n,o,s)|0;l=f,f=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,f,l)}roundClean(){Pt(Jt)}destroy(){this.set(0,0,0,0,0,0,0,0),Pt(this.buffer)}},Fo=class extends Vo{A=qt[0]|0;B=qt[1]|0;C=qt[2]|0;D=qt[3]|0;E=qt[4]|0;F=qt[5]|0;G=qt[6]|0;H=qt[7]|0;constructor(){super(32)}};var wa=ha(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),yl=wa[0],gl=wa[1],Qt=new Uint32Array(80),te=new Uint32Array(80),$o=class extends br{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:l,Fh:u,Fl:h,Gh:m,Gl:d,Hh:g,Hl:b}=this;return[t,e,n,o,s,i,a,c,f,l,u,h,m,d,g,b]}set(t,e,n,o,s,i,a,c,f,l,u,h,m,d,g,b){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=l|0,this.Fh=u|0,this.Fl=h|0,this.Gh=m|0,this.Gl=d|0,this.Hh=g|0,this.Hl=b|0}process(t,e){for(let y=0;y<16;y++,e+=4)Qt[y]=t.getUint32(e),te[y]=t.getUint32(e+=4);for(let y=16;y<80;y++){let A=Qt[y-15]|0,k=te[y-15]|0,N=pe(A,k,1)^pe(A,k,8)^qo(A,k,7),C=me(A,k,1)^me(A,k,8)^Ho(A,k,7),E=Qt[y-2]|0,I=te[y-2]|0,P=pe(E,I,19)^wr(E,I,61)^qo(E,I,6),q=me(E,I,19)^Er(E,I,61)^Ho(E,I,6),U=ya(C,q,te[y-7],te[y-16]),w=ga(U,N,P,Qt[y-7],Qt[y-16]);Qt[y]=w|0,te[y]=U|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:l,Eh:u,El:h,Fh:m,Fl:d,Gh:g,Gl:b,Hh:p,Hl:S}=this;for(let y=0;y<80;y++){let A=pe(u,h,14)^pe(u,h,18)^wr(u,h,41),k=me(u,h,14)^me(u,h,18)^Er(u,h,41),N=u&m^~u&g,C=h&d^~h&b,E=xa(S,k,C,gl[y],te[y]),I=ba(E,p,A,N,yl[y],Qt[y]),P=E|0,q=pe(n,o,28)^wr(n,o,34)^wr(n,o,39),U=me(n,o,28)^Er(n,o,34)^Er(n,o,39),w=n&s^n&a^s&a,v=o&i^o&c^i&c;p=g|0,S=b|0,g=m|0,b=d|0,m=u|0,d=h|0,{h:u,l:h}=Tt(f|0,l|0,I|0,P|0),f=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let x=pa(P,U,v);n=ma(x,I,q,w),o=x|0}({h:n,l:o}=Tt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Tt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Tt(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l}=Tt(this.Dh|0,this.Dl|0,f|0,l|0),{h:u,l:h}=Tt(this.Eh|0,this.El|0,u|0,h|0),{h:m,l:d}=Tt(this.Fh|0,this.Fl|0,m|0,d|0),{h:g,l:b}=Tt(this.Gh|0,this.Gl|0,g|0,b|0),{h:p,l:S}=Tt(this.Hh|0,this.Hl|0,p|0,S|0),this.set(n,o,s,i,a,c,f,l,u,h,m,d,g,b,p,S)}roundClean(){Pt(Qt,te)}destroy(){Pt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},zo=class extends $o{Ah=tt[0]|0;Al=tt[1]|0;Bh=tt[2]|0;Bl=tt[3]|0;Ch=tt[4]|0;Cl=tt[5]|0;Dh=tt[6]|0;Dl=tt[7]|0;Eh=tt[8]|0;El=tt[9]|0;Fh=tt[10]|0;Fl=tt[11]|0;Gh=tt[12]|0;Gl=tt[13]|0;Hh=tt[14]|0;Hl=tt[15]|0;constructor(){super(64)}};var Ea=Mo(()=>new Fo,Ko(1));var va=Mo(()=>new zo,Ko(3));var Go=BigInt(0),jo=BigInt(1);function Ht(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function Ia(r){if(typeof r=="bigint"){if(!cn(r))throw new Error("positive bigint expected, got "+r)}else Dt(r);return r}function vr(r){let t=Ia(r).toString(16);return t.length&1?"0"+t:t}function Sa(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Go:BigInt("0x"+r)}function Ve(r){return Sa(Mt(r))}function ye(r){return Sa(Mt(un(K(r)).reverse()))}function fn(r,t){Dt(t),r=Ia(r);let e=Kt(r.toString(16).padStart(t*2,"0"));if(e.length!==t)throw new Error("number too large");return e}function Zo(r,t){return fn(r,t).reverse()}function un(r){return Uint8Array.from(r)}var cn=r=>typeof r=="bigint"&&Go<=r;function xl(r,t,e){return cn(r)&&cn(t)&&cn(e)&&t<=r&&r<e}function Ir(r,t,e,n){if(!xl(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Yo(r){let t;for(t=0;r>Go;r>>=jo,t+=1);return t}var Sr=r=>(jo<<BigInt(r))-jo;function Aa(r,t,e){if(Dt(r,"hashLen"),Dt(t,"qByteLen"),typeof e!="function")throw new Error("hmacFn must be a function");let n=b=>new Uint8Array(b),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),f=n(r),l=0,u=()=>{c.fill(1),f.fill(0),l=0},h=(...b)=>e(f,ct(c,...b)),m=(b=o)=>{f=h(s,b),c=h(),b.length!==0&&(f=h(i,b),c=h())},d=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,p=[];for(;b<t;){c=h();let S=c.slice();p.push(S),b+=c.length}return ct(...p)};return(b,p)=>{u(),m(b);let S;for(;!(S=p(d()));)m();return u(),S}}function ee(r,t={},e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(t,!1),o(e,!0)}function Fe(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var st=BigInt(0),W=BigInt(1),ge=BigInt(2),Ca=BigInt(3),Da=BigInt(4),Ta=BigInt(5),bl=BigInt(7),La=BigInt(8),wl=BigInt(9),Na=BigInt(16);function Z(r,t){let e=r%t;return e>=st?e:t+e}function F(r,t,e){let n=r;for(;t-- >st;)n*=n,n%=e;return n}function Ba(r,t){if(r===st)throw new Error("invert: expected non-zero number");if(t<=st)throw new Error("invert: expected positive modulus, got "+t);let e=Z(r,t),n=t,o=st,s=W,i=W,a=st;for(;e!==st;){let f=n/e,l=n%e,u=o-i*f,h=s-a*f;n=e,e=l,o=i,s=a,i=u,a=h}if(n!==W)throw new Error("invert: does not exist");return Z(o,t)}function Wo(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function Ua(r,t){let e=(r.ORDER+W)/Da,n=r.pow(t,e);return Wo(r,n,t),n}function El(r,t){let e=(r.ORDER-Ta)/La,n=r.mul(t,ge),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,ge),o),a=r.mul(s,r.sub(i,r.ONE));return Wo(r,a,t),a}function vl(r){let t=$e(r),e=Oa(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+bl)/Na;return(a,c)=>{let f=a.pow(c,i),l=a.mul(f,n),u=a.mul(f,o),h=a.mul(f,s),m=a.eql(a.sqr(l),c),d=a.eql(a.sqr(u),c);f=a.cmov(f,l,m),l=a.cmov(h,u,d);let g=a.eql(a.sqr(l),c),b=a.cmov(f,l,g);return Wo(a,b,c),b}}function Oa(r){if(r<Ca)throw new Error("sqrt is not defined for small field");let t=r-W,e=0;for(;t%ge===st;)t/=ge,e++;let n=ge,o=$e(r);for(;ka(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Ua;let s=o.pow(n,t),i=(t+W)/ge;return function(c,f){if(c.is0(f))return f;if(ka(c,f)!==1)throw new Error("Cannot find square root");let l=e,u=c.mul(c.ONE,s),h=c.pow(f,t),m=c.pow(f,i);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let d=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(d++,g=c.sqr(g),d===l)throw new Error("Cannot find square root");let b=W<<BigInt(l-d-1),p=c.pow(u,b);l=d,u=c.sqr(p),h=c.mul(h,u),m=c.mul(m,p)}return m}}function Il(r){return r%Da===Ca?Ua:r%La===Ta?El:r%Na===wl?vl(r):Oa(r)}var Ra=(r,t)=>(Z(r,t)&W)===W,Sl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Jo(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=Sl.reduce((n,o)=>(n[o]="function",n),t);return ee(r,e),r}function Al(r,t,e){if(e<st)throw new Error("invalid exponent, negatives unsupported");if(e===st)return r.ONE;if(e===W)return t;let n=r.ONE,o=t;for(;e>st;)e&W&&(n=r.mul(n,o)),o=r.sqr(o),e>>=W;return n}function Ar(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function ka(r,t){let e=(r.ORDER-W)/ge,n=r.pow(t,e),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Bl(r,t){t!==void 0&&Dt(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}var Xo=class{ORDER;BITS;BYTES;isLE;ZERO=st;ONE=W;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=st)throw new Error("invalid field: expected ORDER > 0, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&(this.sqrt=e.sqrt),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=e.allowedLengths?.slice()),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:o,nByteLength:s}=Bl(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return Z(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return st<=t&&t<this.ORDER}is0(t){return t===st}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&W)===W}neg(t){return Z(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return Z(t*t,this.ORDER)}add(t,e){return Z(t+e,this.ORDER)}sub(t,e){return Z(t-e,this.ORDER)}mul(t,e){return Z(t*e,this.ORDER)}pow(t,e){return Al(this,t,e)}div(t,e){return Z(t*Ba(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return Ba(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=Il(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?Zo(t,this.BYTES):fn(t,this.BYTES)}fromBytes(t,e=!1){K(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let f=new Uint8Array(o);f.set(t,s?0:f.length-t.length),t=f}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?ye(t):Ve(t);if(a&&(c=Z(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Ar(this,t)}cmov(t,e,n){return n?e:t}};function $e(r,t={}){return new Xo(r,t)}function _a(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Qo(r){let t=_a(r);return t+Math.ceil(t/2)}function ts(r,t,e=!1){K(r);let n=r.length,o=_a(t),s=Qo(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?ye(r):Ve(r),a=Z(i,t-W)+W;return e?Zo(a,o):fn(a,o)}var ze=BigInt(0),xe=BigInt(1);function Br(r,t){let e=t.negate();return r?e:t}function be(r,t){let e=Ar(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function qa(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function es(r,t){qa(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=Sr(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Pa(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=xe);let f=t*n,l=f+Math.abs(a)-1,u=a===0,h=a<0,m=t%2!==0;return{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:m,offsetF:f}}var rs=new WeakMap,Ha=new WeakMap;function ns(r){return Ha.get(r)||1}function Ma(r){if(r!==ze)throw new Error("invalid wNAF")}var je=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>ze;)e&xe&&(n=n.add(o)),o=o.double(),e>>=xe;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=es(e,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=es(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:l,isNeg:u,isNegF:h,offsetF:m}=Pa(n,a,i);n=c,l?s=s.add(Br(h,e[m])):o=o.add(Br(u,e[f]))}return Ma(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=es(t,this.bits);for(let i=0;i<s.windows&&n!==ze;i++){let{nextN:a,offset:c,isZero:f,isNeg:l}=Pa(n,i,s);if(n=a,!f){let u=e[c];o=o.add(l?u.negate():u)}}return Ma(n),o}getPrecomputes(t,e,n){let o=rs.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),rs.set(e,o))),o}cached(t,e,n){let o=ns(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=ns(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){qa(e,this.bits),Ha.set(t,e),rs.delete(t)}hasCache(t){return ns(t)!==1}};function Va(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>ze||n>ze;)e&xe&&(s=s.add(o)),n&xe&&(i=i.add(o)),o=o.double(),e>>=xe,n>>=xe;return{p1:s,p2:i}}function Ka(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Jo(t),t}else return $e(r,{isLE:e})}function ln(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let f=t[c];if(!(typeof f=="bigint"&&f>ze))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Ka(t.p,e.Fp,n),s=Ka(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function dn(r,t){return function(n){let o=r(n);return{secretKey:o,publicKey:t(o)}}}var re=BigInt(0),J=BigInt(1),os=BigInt(2),kl=BigInt(8);function Cl(r,t,e,n){let o=r.sqr(e),s=r.sqr(n),i=r.add(r.mul(t.a,o),s),a=r.add(r.ONE,r.mul(t.d,r.mul(o,s)));return r.eql(i,a)}function Fa(r,t={}){let e=ln("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i}=s;ee(t,{},{uvRatio:"function"});let a=os<<BigInt(o.BYTES*8)-J,c=b=>n.create(b),f=t.uvRatio||((b,p)=>{try{return{isValid:!0,value:n.sqrt(n.div(b,p))}}catch{return{isValid:!1,value:re}}});if(!Cl(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(b,p,S=!1){let y=S?J:re;return Ir("coordinate "+b,p,y,a),p}function u(b){if(!(b instanceof d))throw new Error("EdwardsPoint expected")}let h=Fe((b,p)=>{let{X:S,Y:y,Z:A}=b,k=b.is0();p==null&&(p=k?kl:n.inv(A));let N=c(S*p),C=c(y*p),E=n.mul(A,p);if(k)return{x:re,y:J};if(E!==J)throw new Error("invZ was invalid");return{x:N,y:C}}),m=Fe(b=>{let{a:p,d:S}=s;if(b.is0())throw new Error("bad point: ZERO");let{X:y,Y:A,Z:k,T:N}=b,C=c(y*y),E=c(A*A),I=c(k*k),P=c(I*I),q=c(C*p),U=c(I*c(q+E)),w=c(P+c(S*c(C*E)));if(U!==w)throw new Error("bad point: equation left != right (1)");let v=c(y*A),x=c(k*N);if(v!==x)throw new Error("bad point: equation left != right (2)");return!0});class d{static BASE=new d(s.Gx,s.Gy,J,c(s.Gx*s.Gy));static ZERO=new d(re,J,J,re);static Fp=n;static Fn=o;X;Y;Z;T;constructor(p,S,y,A){this.X=l("x",p),this.Y=l("y",S),this.Z=l("z",y,!0),this.T=l("t",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){if(p instanceof d)throw new Error("extended point not allowed");let{x:S,y}=p||{};return l("x",S),l("y",y),new d(S,y,J,c(S*y))}static fromBytes(p,S=!1){let y=n.BYTES,{a:A,d:k}=s;p=un(K(p,y,"point")),Ht(S,"zip215");let N=un(p),C=p[y-1];N[y-1]=C&-129;let E=ye(N),I=S?a:n.ORDER;Ir("point.y",E,re,I);let P=c(E*E),q=c(P-J),U=c(k*P-A),{isValid:w,value:v}=f(q,U);if(!w)throw new Error("bad point: invalid y coordinate");let x=(v&J)===J,B=(C&128)!==0;if(!S&&v===re&&B)throw new Error("bad point: x=0 and x_0=1");return B!==x&&(v=c(-v)),d.fromAffine({x:v,y:E})}static fromHex(p,S=!1){return d.fromBytes(Kt(p),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,S=!0){return g.createCache(this,p),S||this.multiply(os),this}assertValidity(){m(this)}equals(p){u(p);let{X:S,Y:y,Z:A}=this,{X:k,Y:N,Z:C}=p,E=c(S*C),I=c(k*A),P=c(y*C),q=c(N*A);return E===I&&P===q}is0(){return this.equals(d.ZERO)}negate(){return new d(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:p}=s,{X:S,Y:y,Z:A}=this,k=c(S*S),N=c(y*y),C=c(os*c(A*A)),E=c(p*k),I=S+y,P=c(c(I*I)-k-N),q=E+N,U=q-C,w=E-N,v=c(P*U),x=c(q*w),B=c(P*w),D=c(U*q);return new d(v,x,D,B)}add(p){u(p);let{a:S,d:y}=s,{X:A,Y:k,Z:N,T:C}=this,{X:E,Y:I,Z:P,T:q}=p,U=c(A*E),w=c(k*I),v=c(C*y*q),x=c(N*P),B=c((A+k)*(E+I)-U-w),D=x-v,L=x+v,O=c(w-S*U),T=c(B*D),R=c(L*O),M=c(B*O),$=c(D*L);return new d(T,R,$,M)}subtract(p){return this.add(p.negate())}multiply(p){if(!o.isValidNot0(p))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:S,f:y}=g.cached(this,p,A=>be(d,A));return be(d,[S,y])[0]}multiplyUnsafe(p,S=d.ZERO){if(!o.isValid(p))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return p===re?d.ZERO:this.is0()||p===J?this:g.unsafe(this,p,y=>be(d,y),S)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(p){return h(this,p)}clearCofactor(){return i===J?this:this.multiplyUnsafe(i)}toBytes(){let{x:p,y:S}=this.toAffine(),y=n.toBytes(S);return y[y.length-1]|=p&J?128:0,y}toHex(){return Mt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new je(d,o.BITS);return d.BASE.precompute(8),d}function $a(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');ee(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:o,Fp:s,Fn:i}=r,a=e.randomBytes||Wt,c=e.adjustScalarBytes||(E=>E),f=e.domain||((E,I,P)=>{if(Ht(P,"phflag"),I.length||P)throw new Error("Contexts/pre-hash are not supported");return E});function l(E){return i.create(ye(E))}function u(E){let I=y.secretKey;K(E,y.secretKey,"secretKey");let P=K(t(E),2*I,"hashedSecretKey"),q=c(P.slice(0,I)),U=P.slice(I,2*I),w=l(q);return{head:q,prefix:U,scalar:w}}function h(E){let{head:I,prefix:P,scalar:q}=u(E),U=o.multiply(q),w=U.toBytes();return{head:I,prefix:P,scalar:q,point:U,pointBytes:w}}function m(E){return h(E).pointBytes}function d(E=Uint8Array.of(),...I){let P=ct(...I);return l(t(f(P,K(E,void 0,"context"),!!n)))}function g(E,I,P={}){E=K(E,void 0,"message"),n&&(E=n(E));let{prefix:q,scalar:U,pointBytes:w}=h(I),v=d(P.context,q,E),x=o.multiply(v).toBytes(),B=d(P.context,x,w,E),D=i.create(v+B*U);if(!i.isValid(D))throw new Error("sign failed: invalid s");let L=ct(x,i.toBytes(D));return K(L,y.signature,"result")}let b={zip215:!0};function p(E,I,P,q=b){let{context:U,zip215:w}=q,v=y.signature;E=K(E,v,"signature"),I=K(I,void 0,"message"),P=K(P,y.publicKey,"publicKey"),w!==void 0&&Ht(w,"zip215"),n&&(I=n(I));let x=v/2,B=E.subarray(0,x),D=ye(E.subarray(x,v)),L,O,T;try{L=r.fromBytes(P,w),O=r.fromBytes(B,w),T=o.multiplyUnsafe(D)}catch{return!1}if(!w&&L.isSmallOrder())return!1;let R=d(U,O.toBytes(),L.toBytes(),I);return O.add(L.multiplyUnsafe(R)).subtract(T).clearCofactor().is0()}let S=s.BYTES,y={secretKey:S,publicKey:S,signature:2*S,seed:S};function A(E=a(y.seed)){return K(E,y.seed,"seed")}function k(E){return he(E)&&E.length===i.BYTES}function N(E,I){try{return!!r.fromBytes(E,I)}catch{return!1}}let C={getExtendedPublicKey:h,randomSecretKey:A,isValidSecretKey:k,isValidPublicKey:N,toMontgomery(E){let{y:I}=r.fromBytes(E),P=y.publicKey,q=P===32;if(!q&&P!==57)throw new Error("only defined for 25519 and 448");let U=q?s.div(J+I,J-I):s.div(I-J,I+J);return s.toBytes(U)},toMontgomerySecret(E){let I=y.secretKey;K(E,I);let P=t(E.subarray(0,I));return c(P).subarray(0,I)}};return Object.freeze({keygen:dn(A,m),getPublicKey:m,sign:g,verify:p,utils:C,Point:r,lengths:y})}var Dl=BigInt(1),za=BigInt(2);var Tl=BigInt(5),Ll=BigInt(8),ss=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Nl={p:ss,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ll,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ul(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=ss,a=r*r%s*r%s,c=F(a,za,s)*a%s,f=F(c,Dl,s)*r%s,l=F(f,Tl,s)*f%s,u=F(l,t,s)*l%s,h=F(u,e,s)*u%s,m=F(h,n,s)*h%s,d=F(m,o,s)*m%s,g=F(d,o,s)*m%s,b=F(g,t,s)*l%s;return{pow_p_5_8:F(b,za,s)*r%s,b2:a}}function Ol(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ja=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Rl(r,t){let e=ss,n=Z(t*t*t,e),o=Z(n*n*t,e),s=Ul(r*o).pow_p_5_8,i=Z(r*n*s,e),a=Z(t*i*i,e),c=i,f=Z(i*ja,e),l=a===r,u=a===Z(-r,e),h=a===Z(-r*ja,e);return l&&(i=c),(u||h)&&(i=f),Ra(i,e)&&(i=Z(-i,e)),{isValid:l||u,value:i}}var _l=Fa(Nl,{uvRatio:Rl});function Pl(r){return $a(_l,va,Object.assign({adjustScalarBytes:Ol},r))}var Ga=Pl({});var hn=32;var is,Ml=(async()=>{try{return await Gr.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Kl(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Gr.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Gr.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function ql(r,t,e){return Ga.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Za(r,t,e){return is==null&&(is=await Ml),is?Kl(r,t,e):ql(r,t,e)}function pn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var mn=class{type="Ed25519";raw;constructor(t){this.raw=as(t,hn)}toMultihash(){return Ne.digest(qe(this))}toCID(){return Zt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=Za(this.raw,e,t);return pn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Xa(r){return r=as(r,hn),new mn(r)}function as(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new gt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Vl=Math.pow(2,7),Fl=Math.pow(2,14),$l=Math.pow(2,21),Wa=Math.pow(2,28),Ja=Math.pow(2,35),Qa=Math.pow(2,42),tc=Math.pow(2,49),it=128,ne=127;function kr(r){if(r<Vl)return 1;if(r<Fl)return 2;if(r<$l)return 3;if(r<Wa)return 4;if(r<Ja)return 5;if(r<Qa)return 6;if(r<tc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ec(r,t,e=0){switch(kr(r)){case 8:t[e++]=r&255|it,r/=128;case 7:t[e++]=r&255|it,r/=128;case 6:t[e++]=r&255|it,r/=128;case 5:t[e++]=r&255|it,r/=128;case 4:t[e++]=r&255|it,r>>>=7;case 3:t[e++]=r&255|it,r>>>=7;case 2:t[e++]=r&255|it,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function rc(r,t){let e=r[t],n=0;if(n+=e&ne,e<it||(e=r[t+1],n+=(e&ne)<<7,e<it)||(e=r[t+2],n+=(e&ne)<<14,e<it)||(e=r[t+3],n+=(e&ne)<<21,e<it)||(e=r[t+4],n+=(e&ne)*Wa,e<it)||(e=r[t+5],n+=(e&ne)*Ja,e<it)||(e=r[t+6],n+=(e&ne)*Qa,e<it)||(e=r[t+7],n+=(e&ne)*tc,e<it))return n;throw new RangeError("Could not decode varint")}var cs=new Float32Array([-0]),oe=new Uint8Array(cs.buffer);function nc(r,t,e){cs[0]=r,t[e]=oe[0],t[e+1]=oe[1],t[e+2]=oe[2],t[e+3]=oe[3]}function oc(r,t){return oe[0]=r[t],oe[1]=r[t+1],oe[2]=r[t+2],oe[3]=r[t+3],cs[0]}var fs=new Float64Array([-0]),rt=new Uint8Array(fs.buffer);function sc(r,t,e){fs[0]=r,t[e]=rt[0],t[e+1]=rt[1],t[e+2]=rt[2],t[e+3]=rt[3],t[e+4]=rt[4],t[e+5]=rt[5],t[e+6]=rt[6],t[e+7]=rt[7]}function ic(r,t){return rt[0]=r[t],rt[1]=r[t+1],rt[2]=r[t+2],rt[3]=r[t+3],rt[4]=r[t+4],rt[5]=r[t+5],rt[6]=r[t+6],rt[7]=r[t+7],fs[0]}var zl=BigInt(Number.MAX_SAFE_INTEGER),jl=BigInt(Number.MIN_SAFE_INTEGER),dt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return we;if(t<zl&&t>jl)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>ac&&(o=0n,++n>ac&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return we;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):we}},we=new dt(0,0);we.toBigInt=function(){return 0n};we.zzEncode=we.zzDecode=function(){return this};we.length=function(){return 1};var ac=4294967296n;function cc(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function fc(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function us(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function It(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function yn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ls=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,It(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw It(this,4);return yn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw It(this,4);return yn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw It(this,4);let t=oc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw It(this,4);let t=ic(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw It(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return fc(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw It(this,t);this.pos+=t}else do if(this.pos>=this.len)throw It(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new dt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw It(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw It(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw It(this,8);let t=yn(this.buf,this.pos+=4),e=yn(this.buf,this.pos+=4);return new dt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=rc(this.buf,this.pos);return this.pos+=kr(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ds(r){return new ls(r instanceof Uint8Array?r:r.subarray())}function gn(r,t,e){let n=ds(r);return t.decode(n,void 0,e)}function hs(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return ut(i);o+i>t&&(n=ut(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Ee=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function ps(){}var ys=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Gl=hs();function Zl(r){return globalThis.Buffer!=null?ut(r):Gl(r)}var Dr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ee(ps,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Ee(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new gs((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(xn,10,dt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=dt.fromBigInt(t);return this._push(xn,e.length(),e)}uint64Number(t){return this._push(ec,kr(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=dt.fromBigInt(t).zzEncode();return this._push(xn,e.length(),e)}sint64Number(t){let e=dt.fromNumber(t).zzEncode();return this._push(xn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ms,1,t?1:0)}fixed32(t){return this._push(Cr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=dt.fromBigInt(t);return this._push(Cr,4,e.lo)._push(Cr,4,e.hi)}fixed64Number(t){let e=dt.fromNumber(t);return this._push(Cr,4,e.lo)._push(Cr,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(nc,4,t)}double(t){return this._push(sc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ms,1,0):this.uint32(e)._push(Xl,e,t)}string(t){let e=cc(t);return e!==0?this.uint32(e)._push(us,e,t):this._push(ms,1,0)}fork(){return this.states=new ys(this),this.head=this.tail=new Ee(ps,0,0),this.len=0,this}reset(){return this.states!=null?(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 Ee(ps,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Zl(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ms(r,t,e){t[e]=r&255}function Yl(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var gs=class extends Ee{next;constructor(t,e){super(Yl,t,e),this.next=void 0}};function xn(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Cr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Xl(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Dr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Wl,t,r),this},Dr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Jl,t,r),this});function Wl(r,t,e){t.set(r,e)}function Jl(r,t,e){r.length<40?us(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Xt(r),e)}function xs(){return new Dr}function bn(r,t){let e=xs();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Ge;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ge||(Ge={}));function wn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function bs(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return wn("enum",Ge.VARINT,e,n)}function En(r,t){return wn("message",Ge.LENGTH_DELIMITED,r,t)}var ht;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ht||(ht={}));var ws;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(ws||(ws={}));(function(r){r.codec=()=>bs(ws)})(ht||(ht={}));var Tr;(function(r){let t;r.codec=()=>(t==null&&(t=En((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ht.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ht.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>bn(e,r.codec()),r.decode=(e,n)=>gn(e,r.codec(),n)})(Tr||(Tr={}));var Es;(function(r){let t;r.codec=()=>(t==null&&(t=En((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ht.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ht.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>bn(e,r.codec()),r.decode=(e,n)=>gn(e,r.codec(),n)})(Es||(Es={}));function Ze(r){if(isNaN(r)||r<=0)throw new gt("random bytes length must be a Number bigger than 0");return Wt(r)}var vn=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(on(t),K(e,void 0,"key"),this.iHash=t.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;let n=this.blockLen,o=new Uint8Array(n);o.set(e.length>n?t.create().update(e).digest():e);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Pt(o)}update(t){return He(this),this.iHash.update(t),this}digestInto(t){He(this),K(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},vs=(r,t,e)=>new vn(r,t).update(e).digest();vs.create=(r,t)=>new vn(r,t);var lc=(r,t)=>(r+(r>=0?t:-t)/dc)/t;function td(r,t,e){let[[n,o],[s,i]]=t,a=lc(i*r,e),c=lc(-o*r,e),f=r-a*n-c*s,l=-a*o-c*i,u=f<Vt,h=l<Vt;u&&(f=-f),h&&(l=-l);let m=Sr(Math.ceil(Yo(e)/2))+Ye;if(f<Vt||f>=m||l<Vt||l>=m)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:f,k2neg:h,k2:l}}function Ss(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Is(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return Ht(e.lowS,"lowS"),Ht(e.prehash,"prehash"),e.format!==void 0&&Ss(e.format),e}var As=class extends Error{constructor(t=""){super(t)}},se={Err:As,_tlv:{encode:(r,t)=>{let{Err:e}=se;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=vr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?vr(o.length/2|128):"";return vr(r)+s+o+t},decode(r,t){let{Err:e}=se,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let f=t.subarray(n,n+c);if(f.length!==c)throw new e("tlv.decode: length bytes not complete");if(f[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let l of f)i=i<<8|l;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=se;if(r<Vt)throw new t("integer: negative integers are not allowed");let e=vr(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=se;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Ve(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=se,o=K(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l}=n.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(f)}},hexFromSig(r){let{_tlv:t,_int:e}=se,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Vt=BigInt(0),Ye=BigInt(1),dc=BigInt(2),In=BigInt(3),ed=BigInt(4);function hc(r,t={}){let e=ln("weierstrass",r,t),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i,n:a}=s;ee(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let f=mc(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(U,w,v){let{x,y:B}=w.toAffine(),D=n.toBytes(x);if(Ht(v,"isCompressed"),v){l();let L=!n.isOdd(B);return ct(pc(L),D)}else return ct(Uint8Array.of(4),D,n.toBytes(B))}function h(U){K(U,void 0,"Point");let{publicKey:w,publicKeyUncompressed:v}=f,x=U.length,B=U[0],D=U.subarray(1);if(x===w&&(B===2||B===3)){let L=n.fromBytes(D);if(!n.isValid(L))throw new Error("bad point: is not on curve, wrong x");let O=g(L),T;try{T=n.sqrt(O)}catch($){let V=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}l();let R=n.isOdd(T);return(B&1)===1!==R&&(T=n.neg(T)),{x:L,y:T}}else if(x===v&&B===4){let L=n.BYTES,O=n.fromBytes(D.subarray(0,L)),T=n.fromBytes(D.subarray(L,L*2));if(!b(O,T))throw new Error("bad point: is not on curve");return{x:O,y:T}}else throw new Error(`bad point: got length ${x}, expected compressed=${w} or uncompressed=${v}`)}let m=t.toBytes||u,d=t.fromBytes||h;function g(U){let w=n.sqr(U),v=n.mul(w,U);return n.add(n.add(v,n.mul(U,s.a)),s.b)}function b(U,w){let v=n.sqr(w),x=g(U);return n.eql(v,x)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let p=n.mul(n.pow(s.a,In),ed),S=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(p,S)))throw new Error("bad curve params: a or b");function y(U,w,v=!1){if(!n.isValid(w)||v&&n.is0(w))throw new Error(`bad point coordinate ${U}`);return w}function A(U){if(!(U instanceof I))throw new Error("Weierstrass Point expected")}function k(U){if(!c||!c.basises)throw new Error("no endo");return td(U,c.basises,o.ORDER)}let N=Fe((U,w)=>{let{X:v,Y:x,Z:B}=U;if(n.eql(B,n.ONE))return{x:v,y:x};let D=U.is0();w==null&&(w=D?n.ONE:n.inv(B));let L=n.mul(v,w),O=n.mul(x,w),T=n.mul(B,w);if(D)return{x:n.ZERO,y:n.ZERO};if(!n.eql(T,n.ONE))throw new Error("invZ was invalid");return{x:L,y:O}}),C=Fe(U=>{if(U.is0()){if(t.allowInfinityPoint&&!n.is0(U.Y))return;throw new Error("bad point: ZERO")}let{x:w,y:v}=U.toAffine();if(!n.isValid(w)||!n.isValid(v))throw new Error("bad point: x or y not field elements");if(!b(w,v))throw new Error("bad point: equation left != right");if(!U.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(U,w,v,x,B){return v=new I(n.mul(v.X,U),v.Y,v.Z),w=Br(x,w),v=Br(B,v),w.add(v)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(w,v,x){this.X=y("x",w),this.Y=y("y",v,!0),this.Z=y("z",x),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){let{x:v,y:x}=w||{};if(!w||!n.isValid(v)||!n.isValid(x))throw new Error("invalid affine point");if(w instanceof I)throw new Error("projective point not allowed");return n.is0(v)&&n.is0(x)?I.ZERO:new I(v,x,n.ONE)}static fromBytes(w){let v=I.fromAffine(d(K(w,void 0,"point")));return v.assertValidity(),v}static fromHex(w){return I.fromBytes(Kt(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,v=!0){return q.createCache(this,w),v||this.multiply(In),this}assertValidity(){C(this)}hasEvenY(){let{y:w}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(w)}equals(w){A(w);let{X:v,Y:x,Z:B}=this,{X:D,Y:L,Z:O}=w,T=n.eql(n.mul(v,O),n.mul(D,B)),R=n.eql(n.mul(x,O),n.mul(L,B));return T&&R}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:w,b:v}=s,x=n.mul(v,In),{X:B,Y:D,Z:L}=this,O=n.ZERO,T=n.ZERO,R=n.ZERO,M=n.mul(B,B),$=n.mul(D,D),V=n.mul(L,L),H=n.mul(B,D);return H=n.add(H,H),R=n.mul(B,L),R=n.add(R,R),O=n.mul(w,R),T=n.mul(x,V),T=n.add(O,T),O=n.sub($,T),T=n.add($,T),T=n.mul(O,T),O=n.mul(H,O),R=n.mul(x,R),V=n.mul(w,V),H=n.sub(M,V),H=n.mul(w,H),H=n.add(H,R),R=n.add(M,M),M=n.add(R,M),M=n.add(M,V),M=n.mul(M,H),T=n.add(T,M),V=n.mul(D,L),V=n.add(V,V),M=n.mul(V,H),O=n.sub(O,M),R=n.mul(V,$),R=n.add(R,R),R=n.add(R,R),new I(O,T,R)}add(w){A(w);let{X:v,Y:x,Z:B}=this,{X:D,Y:L,Z:O}=w,T=n.ZERO,R=n.ZERO,M=n.ZERO,$=s.a,V=n.mul(s.b,In),H=n.mul(v,D),z=n.mul(x,L),Q=n.mul(B,O),St=n.add(v,x),j=n.add(D,L);St=n.mul(St,j),j=n.add(H,z),St=n.sub(St,j),j=n.add(v,B);let et=n.add(D,O);return j=n.mul(j,et),et=n.add(H,Q),j=n.sub(j,et),et=n.add(x,B),T=n.add(L,O),et=n.mul(et,T),T=n.add(z,Q),et=n.sub(et,T),M=n.mul($,j),T=n.mul(V,Q),M=n.add(T,M),T=n.sub(z,M),M=n.add(z,M),R=n.mul(T,M),z=n.add(H,H),z=n.add(z,H),Q=n.mul($,Q),j=n.mul(V,j),z=n.add(z,Q),Q=n.sub(H,Q),Q=n.mul($,Q),j=n.add(j,Q),H=n.mul(z,j),R=n.add(R,H),H=n.mul(et,j),T=n.mul(St,T),T=n.sub(T,H),H=n.mul(St,z),M=n.mul(et,M),M=n.add(M,H),new I(T,R,M)}subtract(w){return this.add(w.negate())}is0(){return this.equals(I.ZERO)}multiply(w){let{endo:v}=t;if(!o.isValidNot0(w))throw new Error("invalid scalar: out of range");let x,B,D=L=>q.cached(this,L,O=>be(I,O));if(v){let{k1neg:L,k1:O,k2neg:T,k2:R}=k(w),{p:M,f:$}=D(O),{p:V,f:H}=D(R);B=$.add(H),x=E(v.beta,M,V,L,T)}else{let{p:L,f:O}=D(w);x=L,B=O}return be(I,[x,B])[0]}multiplyUnsafe(w){let{endo:v}=t,x=this;if(!o.isValid(w))throw new Error("invalid scalar: out of range");if(w===Vt||x.is0())return I.ZERO;if(w===Ye)return x;if(q.hasCache(this))return this.multiply(w);if(v){let{k1neg:B,k1:D,k2neg:L,k2:O}=k(w),{p1:T,p2:R}=Va(I,x,D,O);return E(v.beta,T,R,B,L)}else return q.unsafe(x,w)}toAffine(w){return N(this,w)}isTorsionFree(){let{isTorsionFree:w}=t;return i===Ye?!0:w?w(I,this):q.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:w}=t;return i===Ye?this:w?w(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(w=!0){return Ht(w,"isCompressed"),this.assertValidity(),m(I,this,w)}toHex(w=!0){return Mt(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let P=o.BITS,q=new je(I,t.endo?Math.ceil(P/2):P);return I.BASE.precompute(8),I}function pc(r){return Uint8Array.of(r?2:3)}function mc(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function rd(r,t={}){let{Fn:e}=r,n=t.randomBytes||Wt,o=Object.assign(mc(r.Fp,e),{seed:Qo(e.ORDER)});function s(m){try{let d=e.fromBytes(m);return e.isValidNot0(d)}catch{return!1}}function i(m,d){let{publicKey:g,publicKeyUncompressed:b}=o;try{let p=m.length;return d===!0&&p!==g||d===!1&&p!==b?!1:!!r.fromBytes(m)}catch{return!1}}function a(m=n(o.seed)){return ts(K(m,o.seed,"seed"),e.ORDER)}function c(m,d=!0){return r.BASE.multiply(e.fromBytes(m)).toBytes(d)}function f(m){let{secretKey:d,publicKey:g,publicKeyUncompressed:b}=o;if(!he(m)||"_lengths"in e&&e._lengths||d===g)return;let p=K(m,void 0,"key").length;return p===g||p===b}function l(m,d,g=!0){if(f(m)===!0)throw new Error("first arg must be private key");if(f(d)===!1)throw new Error("second arg must be public key");let b=e.fromBytes(m);return r.fromBytes(d).multiply(b).toBytes(g)}let u={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=dn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:h,Point:r,utils:u,lengths:o})}function yc(r,t,e={}){on(t),ee(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let n=e.randomBytes||Wt,o=e.hmac||((v,x)=>vs(t,v,x)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:f,getPublicKey:l,getSharedSecret:u,utils:h,lengths:m}=rd(r,e),d={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},g=a*dc<s.ORDER;function b(v){let x=a>>Ye;return v>x}function p(v,x){if(!i.isValidNot0(x))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return x}function S(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function y(v,x){Ss(x);let B=m.signature,D=x==="compact"?B:x==="recovered"?B+1:void 0;return K(v,D)}class A{r;s;recovery;constructor(x,B,D){if(this.r=p("r",x),this.s=p("s",B),D!=null){if(S(),![0,1,2,3].includes(D))throw new Error("invalid recovery id");this.recovery=D}Object.freeze(this)}static fromBytes(x,B=d.format){y(x,B);let D;if(B==="der"){let{r:R,s:M}=se.toSig(K(x));return new A(R,M)}B==="recovered"&&(D=x[0],B="compact",x=x.subarray(1));let L=m.signature/2,O=x.subarray(0,L),T=x.subarray(L,L*2);return new A(i.fromBytes(O),i.fromBytes(T),D)}static fromHex(x,B){return this.fromBytes(Kt(x),B)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new A(this.r,this.s,x)}recoverPublicKey(x){let{r:B,s:D}=this,L=this.assertRecovery(),O=L===2||L===3?B+a:B;if(!s.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let T=s.toBytes(O),R=r.fromBytes(ct(pc((L&1)===0),T)),M=i.inv(O),$=N(K(x,void 0,"msgHash")),V=i.create(-$*M),H=i.create(D*M),z=r.BASE.multiplyUnsafe(V).add(R.multiplyUnsafe(H));if(z.is0())throw new Error("invalid recovery: point at infinify");return z.assertValidity(),z}hasHighS(){return b(this.s)}toBytes(x=d.format){if(Ss(x),x==="der")return Kt(se.hexFromSig(this));let{r:B,s:D}=this,L=i.toBytes(B),O=i.toBytes(D);return x==="recovered"?(S(),ct(Uint8Array.of(this.assertRecovery()),L,O)):ct(L,O)}toHex(x){return Mt(this.toBytes(x))}}let k=e.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let B=Ve(x),D=x.length*8-c;return D>0?B>>BigInt(D):B},N=e.bits2int_modN||function(x){return i.create(k(x))},C=Sr(c);function E(v){return Ir("num < 2^"+c,v,Vt,C),i.toBytes(v)}function I(v,x){return K(v,void 0,"message"),x?K(t(v),void 0,"prehashed message"):v}function P(v,x,B){let{lowS:D,prehash:L,extraEntropy:O}=Is(B,d);v=I(v,L);let T=N(v),R=i.fromBytes(x);if(!i.isValidNot0(R))throw new Error("invalid private key");let M=[E(R),E(T)];if(O!=null&&O!==!1){let z=O===!0?n(m.secretKey):O;M.push(K(z,void 0,"extraEntropy"))}let $=ct(...M),V=T;function H(z){let Q=k(z);if(!i.isValidNot0(Q))return;let St=i.inv(Q),j=r.BASE.multiply(Q).toAffine(),et=i.create(j.x);if(et===Vt)return;let Fr=i.create(St*i.create(V+et*R));if(Fr===Vt)return;let si=(j.x===et?0:2)|Number(j.y&Ye),ii=Fr;return D&&b(Fr)&&(ii=i.neg(Fr),si^=1),new A(et,ii,g?void 0:si)}return{seed:$,k2sig:H}}function q(v,x,B={}){let{seed:D,k2sig:L}=P(v,x,B);return Aa(t.outputLen,i.BYTES,o)(D,L).toBytes(B.format)}function U(v,x,B,D={}){let{lowS:L,prehash:O,format:T}=Is(D,d);if(B=K(B,void 0,"publicKey"),x=I(x,O),!he(v)){let R=v instanceof A?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+R)}y(v,T);try{let R=A.fromBytes(v,T),M=r.fromBytes(B);if(L&&R.hasHighS())return!1;let{r:$,s:V}=R,H=N(x),z=i.inv(V),Q=i.create(H*z),St=i.create($*z),j=r.BASE.multiplyUnsafe(Q).add(M.multiplyUnsafe(St));return j.is0()?!1:i.create(j.x)===$}catch{return!1}}function w(v,x,B={}){let{prehash:D}=Is(B,d);return x=I(x,D),A.fromBytes(v,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:f,getPublicKey:l,getSharedSecret:u,utils:h,lengths:m,Point:r,sign:q,verify:U,recoverPublicKey:w,Signature:A,hash:t})}var ks={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},nd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var gc=BigInt(2);function od(r){let t=ks.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%t,l=f*f*r%t,u=F(l,e,t)*l%t,h=F(u,e,t)*l%t,m=F(h,gc,t)*f%t,d=F(m,o,t)*m%t,g=F(d,s,t)*d%t,b=F(g,a,t)*g%t,p=F(b,c,t)*b%t,S=F(p,a,t)*g%t,y=F(S,e,t)*l%t,A=F(y,i,t)*d%t,k=F(A,n,t)*f%t,N=F(k,gc,t);if(!Bs.eql(Bs.sqr(N),r))throw new Error("Cannot find square root");return N}var Bs=$e(ks.p,{sqrt:od}),sd=hc(ks,{Fp:Bs,endo:nd}),Xe=yc(sd,Ea);var id=20;function Ds({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new Cs(r,t,e,n,o)}var Cs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??id,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?xc(n,this.code,e?.truncate):n.then(o=>xc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function xc(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Le(t,r)}function bc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var wc=Ds({name:"sha2-256",code:18,encode:bc("SHA-256")}),sg=Ds({name:"sha2-512",code:19,encode:bc("SHA-512")});function Ec(r,t,e,n){let o=wc.digest(e instanceof Uint8Array?e:e.subarray());if(pn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Xe.verify(t,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new ir(String(s))});try{return n?.signal?.throwIfAborted(),Xe.verify(t,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new ir(String(s))}}var Sn=class{type="secp256k1";raw;_key;constructor(t){this._key=Ic(t),this.raw=vc(this._key)}toMultihash(){return Ne.digest(qe(this))}toCID(){return Zt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e,n){return Ec(this._key,e,t,n)}};function Sc(r){return new Sn(r)}function vc(r){return Xe.Point.fromBytes(r).toBytes()}function Ic(r){try{return Xe.Point.fromBytes(r),r}catch(t){throw new Zr(String(t))}}function Ac(r){let{Type:t,Data:e}=Tr.decode(r.digest),n=e??new Uint8Array;switch(t){case ht.Ed25519:return Xa(n);case ht.secp256k1:return Sc(n);case ht.ECDSA:return oa(n);default:throw new ar}}function qe(r){return Tr.encode({Type:ht[r.type],Data:r.raw})}var ie=class{static lockQueues=new Map;static async acquire(t){let e=this.lockQueues.get(t)??Promise.resolve(),n,o=new Promise(i=>{n=i});return this.lockQueues.set(t,o),await e,()=>{n(),this.lockQueues.get(t)===o&&this.lockQueues.delete(t)}}};var ad=100,ve=class r{id;transactor;handlers;source;sourceCache;tracker;filterConflict;pending=[];latchId;constructor(t,e,n,o,s,i,a){this.id=t,this.transactor=e,this.handlers=n,this.source=o,this.sourceCache=s,this.tracker=i,this.filterConflict=a,this.latchId=`Collection:${this.id}`}static async createOrOpen(t,e,n){let o=new We(e,t,void 0),s=new Lr(o),i=new Ft(s);if(await o.tryGet(e)){let c=await xt.open(i,e);o.actionContext=await c.getActionContext()}else{let c=n.createHeaderBlock(e,i);i.insert(c),o.actionContext=void 0,await xt.open(i,e)}return new r(e,t,n.modules,o,s,i,n.filterConflict)}async act(...t){let e=await ie.acquire(this.latchId);try{await this.actInternal(...t)}finally{e()}}async actInternal(...t){await this.internalTransact(...t),this.pending.push(...t)}async internalTransact(...t){let e=new Ut(this.tracker);for(let n of t){let o=this.handlers[n.type];if(!o)throw new Error(`No handler for action type ${n.type}`);await o(n,e)}e.commit()}async update(){let t=await ie.acquire(this.latchId);try{await this.updateInternal()}finally{t()}}async updateInternal(){let t=new We(this.id,this.transactor,void 0),e=new Ft(t),n=this.source.actionContext,o=await xt.open(e,this.id),s=o?await o.getFrom(n?.rev??0):void 0,i=!1;for(let a of s?.entries??[])this.pending=this.pending.map(c=>this.doFilterConflict(c,a.actions)?c:void 0).filter(Boolean),this.sourceCache.clear(a.blockIds),i=i||this.tracker.conflicts(new Set(a.blockIds)).length>0;i&&await this.replayActions(),this.source.actionContext=s?.context}async sync(){let t=await ie.acquire(this.latchId);try{await this.syncInternal()}finally{t()}}async syncInternal(){let t=Ze(16),e=Y(t,"base64url");for(;this.pending.length||!Hn(this.tracker.transforms);){let n=[...this.pending],o=qn(this.tracker.transforms),s=new Ft(this.sourceCache,o),i=await xt.open(s,this.id);if(!i)throw new Error(`Log not found for collection ${this.id}`);let a=(this.source.actionContext?.rev??0)+1,c=await i.addActions(n,e,a,()=>s.transformedBlockIds()),f=await this.source.transact(s.transforms,e,a,this.id,c.tailPath.block.header.id);if(f)f.pending&&await new Promise(l=>setTimeout(l,ad)),await this.updateInternal();else{this.pending=this.pending.slice(n.length);let l=s.reset();await this.replayActions(),this.sourceCache.transformCache(l),this.source.actionContext=this.source.actionContext?{committed:[...this.source.actionContext.committed,{actionId:e,rev:a}],rev:a}:{committed:[{actionId:e,rev:a}],rev:a}}}}async updateAndSync(){let t=await ie.acquire(this.latchId);try{await this.updateInternal(),await this.syncInternal()}finally{t()}}async*selectLog(t=!0){let e=await xt.open(this.tracker,this.id);if(!e)throw new Error(`Log not found for collection ${this.id}`);for await(let n of e.select(void 0,t))n.action&&(yield*t?n.action.actions:n.action.actions.reverse())}async replayActions(){this.tracker.reset();for(let t of this.pending)await this.internalTransact(t)}doFilterConflict(t,e){if(this.filterConflict){let n=this.filterConflict(t,e);if(n)n!==t&&this.pending.push(n);else return!1}return!0}};var Ts=class r{collection;constructor(t){this.collection=t}static async create(t,e){let n={modules:{append:async(s,i)=>{}},createHeaderBlock:(s,i)=>({header:i.createBlockHeader(Ls,s)})},o=await ve.createOrOpen(t,e,n);return new r(o)}async append(t){let e={type:"append",data:t};await this.collection.act(e),await this.collection.updateAndSync()}async update(){await this.collection.update()}async*select(t=!0){for await(let e of this.collection.selectLog(t))yield e.data}};var Ls=bt("DIH","DiaryHeaderBlock");var Ns=bt("TRE","TreeHeaderBlock"),Us=nt("rootId");var Nr=class{store;collectionId;constructor(t,e){this.store=t,this.collectionId=e}async get(){return await X(this.store,await this.getId())}async set(t){let e=await X(this.store,this.collectionId);_(this.store,e,[Us,0,1,t.header.id])}async getId(){return(await X(this.store,this.collectionId)).rootId}};var Os=class r{collection;btree;constructor(t,e){this.collection=t,this.btree=e}static async createOrOpen(t,e,n=s=>s,o=(s,i)=>s<i?-1:s>i?1:0){let s,i={modules:{replace:async({data:c},f)=>{for(let[l,u]of c)u?await s.upsert(u):await s.deleteAt(await s.find(l))}},createHeaderBlock:(c,f)=>{let l;return s=jt.create(f,(u,h)=>(l=h,new Nr(f,c)),n,o),{header:f.createBlockHeader(Ns,c),rootId:l}}},a=await ve.createOrOpen(t,e,i);return s=s??new jt(a.tracker,new Nr(a.tracker,a.id),n,o),new r(a,s)}async replace(t){await this.collection.act({type:"replace",data:t}),await this.collection.updateAndSync()}async update(){await this.collection.update()}async first(){return await this.btree.first()}async last(){return await this.btree.last()}async find(t){return await this.btree.find(t)}async get(t){return await this.btree.get(t)}at(t){return this.btree.at(t)}range(t){return this.btree.range(t)}ascending(t){return this.btree.ascending(t)}descending(t){return this.btree.descending(t)}async getCount(t){return await this.btree.getCount(t)}async next(t){return await this.btree.next(t)}async moveNext(t){await this.btree.moveNext(t)}async prior(t){return await this.btree.prior(t)}async movePrior(t){await this.btree.movePrior(t)}isValid(t){return this.btree.isValid(t)}};var Bx=new Uint8Array(0);var cd=Cc,Bc=128,fd=127,ud=~fd,ld=Math.pow(2,31);function Cc(r,t,e){t=t||[],e=e||0;for(var n=e;r>=ld;)t[e++]=r&255|Bc,r/=128;for(;r&ud;)t[e++]=r&255|Bc,r>>>=7;return t[e]=r|0,Cc.bytes=e-n+1,t}var dd=Rs,hd=128,kc=127;function Rs(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Rs.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&kc)<<o:(i&kc)*Math.pow(2,o),o+=7}while(i>=hd);return Rs.bytes=s-n,e}var pd=Math.pow(2,7),md=Math.pow(2,14),yd=Math.pow(2,21),gd=Math.pow(2,28),xd=Math.pow(2,35),bd=Math.pow(2,42),wd=Math.pow(2,49),Ed=Math.pow(2,56),vd=Math.pow(2,63),Id=function(r){return r<pd?1:r<md?2:r<yd?3:r<gd?4:r<xd?5:r<bd?6:r<wd?7:r<Ed?8:r<vd?9:10},Sd={encode:cd,decode:dd,encodingLength:Id},Ad=Sd,_s=Ad;function Ps(r,t,e=0){return _s.encode(r,t,e),t}function Ms(r){return _s.encodingLength(r)}function Dc(r,t){let e=t.byteLength,n=Ms(r),o=n+Ms(e),s=new Uint8Array(o+e);return Ps(r,s,0),Ps(e,s,n),s.set(t,o),new Ks(r,e,t,s)}var Ks=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var Cd=20;function Hs({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new qs(r,t,e,n,o)}var qs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??Cd,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Tc(n,this.code,e?.truncate):n.then(o=>Tc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function Tc(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Dc(t,r)}function Lc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var An=Hs({name:"sha2-256",code:18,encode:Lc("SHA-256")}),_x=Hs({name:"sha2-512",code:19,encode:Lc("SHA-512")});var Dd=nt("priorHash"),xt=class r{chain;constructor(t){this.chain=t}get id(){return this.chain.id}static async open(t,e){let n=await Be.open(t,e,r.getChainOptions(t));return n?new r(n):void 0}static async create(t,e){return new r(await Be.create(t,{...r.getChainOptions(t),newId:e}))}async addActions(t,e,n,o,s=[],i=Date.now()){let a={timestamp:i,rev:n,action:{actionId:e,actions:t,blockIds:[],collectionIds:s}},c=await this.chain.add(a),f={...a,action:{...a.action,blockIds:o()}};return this.chain.updateAt(c,f),{entry:f,tailPath:c}}async addCheckpoint(t,e,n=Date.now()){let o={timestamp:n,rev:e,checkpoint:{pendings:t}},s=await this.chain.add(o);return{entry:o,tailPath:s}}async getActionContext(){let t=await this.chain.getTail();if(!t)return;let e=await this.findCheckpoint(t);return{committed:e?[...e.pendings,...await this.pendingFrom(e.path)]:[],rev:e?.rev??0}}async getFrom(t){let e=[],n=[],o,s;for await(let i of this.chain.select(void 0,!1)){let a=de(i);if(o=o??a.rev,a.checkpoint){s=i,n.unshift(...a.checkpoint.pendings);break}n.unshift({actionId:a.action.actionId,rev:a.rev}),t!==void 0&&a.rev>t&&e.unshift(a.action)}if(s)for await(let i of this.chain.select(s,!1)){let a=de(i);if(t!==void 0&&a.rev>t)a.action&&e.unshift(a.action);else break}return{context:o?{committed:n,rev:o}:void 0,entries:e}}async*select(t,e=!0){for await(let n of this.chain.select(t,e))yield de(n)}async findCheckpoint(t){let e,n;for await(let o of this.chain.select(t,!1)){let s=de(o);if(n=n??s.rev,s.checkpoint)return{path:o,pendings:s.checkpoint.pendings,rev:n};e=o}return e?{path:e,pendings:[],rev:n}:void 0}async pendingFrom(t){let e=[];for await(let n of this.chain.select(t)){let o=de(n);o?.action&&e.push({actionId:o.action.actionId,rev:o.rev})}return e}static getChainOptions(t){return{createDataBlock:()=>({header:t.createBlockHeader("LGD")}),createHeaderBlock:e=>({header:t.createBlockHeader("LGH",e)}),newBlock:async(e,n)=>{if(n){let o=await An.digest(new TextEncoder().encode(JSON.stringify(n)));e.priorHash=Y(o.digest,"base64url")}}}}};var Vs="LGD",Fs="LGH";function ae(r){let t=5381;for(let e=0;e<r.length;e++)t=(t<<5)+t+r.charCodeAt(e)|0;return Math.abs(t).toString(36)}function Je(r,t,e,n){let o=JSON.stringify({peerId:r,timestamp:t,schemaHash:e,engineId:n}),s=`stamp:${ae(o)}`;return{peerId:r,timestamp:t,schemaHash:e,engineId:n,id:s}}function Qe(r,t,e){let n=JSON.stringify({stampId:r,statements:t,reads:e});return`tx:${ae(n)}`}Bn();Bn();var kn=class{transactor;collections;constructor(t,e){this.transactor=t,this.collections=e}async applyActions(t,e){for(let{collectionId:n,actions:o}of t){let s=this.collections.get(n);if(!s)throw new Error(`Collection not found: ${n}`);for(let i of o){let a={...i,transaction:e};await s.act(a)}}}async commit(t){let e=Array.from(this.collections.entries()).map(([c,f])=>({collectionId:c,collection:f,transforms:f.tracker.transforms})).filter(({transforms:c})=>Object.keys(c.inserts??{}).length+Object.keys(c.updates??{}).length+(c.deletes?.length??0)>0);if(e.length===0)return;let n=new Map,o=new Map;for(let{collectionId:c,collection:f,transforms:l}of e){n.set(c,l);let u=await xt.open(f.tracker,c);if(!u)throw new Error(`Log not found for collection ${c}`);let h=await u.chain.getTail();h&&o.set(c,h.block.header.id)}let s=e.flatMap(({collectionId:c,transforms:f})=>[...Object.entries(f.inserts??{}).map(([l,u])=>({type:"insert",collectionId:c,blockId:l,block:u})),...Object.entries(f.updates??{}).map(([l,u])=>({type:"update",collectionId:c,blockId:l,operations:u})),...(f.deletes??[]).map(l=>({type:"delete",collectionId:c,blockId:l}))]),i=this.hashOperations(s),a=await this.coordinateTransaction(t,i,n,o);if(!a.success)throw new Error(`Transaction commit failed: ${a.error}`)}async rollback(t){for(let e of this.collections.values())e.tracker.reset()}getTransforms(){let t=new Map;for(let[e,n]of this.collections.entries()){let o=n.tracker.transforms;(Object.keys(o.inserts??{}).length>0||Object.keys(o.updates??{}).length>0||(o.deletes?.length??0)>0)&&t.set(e,o)}return t}resetTransforms(){for(let t of this.collections.values())t.tracker.reset()}hashOperations(t){let e=JSON.stringify(t);return`ops:${ae(e)}`}async commitTransaction(t){let e=Array.from(t.getCollectionActions().entries()).map(([f,l])=>({collectionId:f,actions:l}));if(e.length===0)return{success:!0};let n=Or(e),o=t.getReads(),s=Je("local",Date.now(),"",t.engine),i={stamp:s,statements:n,reads:o,id:Qe(s.id,n,o)},{ActionsEngine:a}=await Promise.resolve().then(()=>(Bn(),Nc)),c=new a(this);return await this.execute(i,c)}async execute(t,e){let n=await e.execute(t);if(!n.success)return n;if(!n.actions||n.actions.length===0)return{success:!0};let o=new Map,s=new Map,i=new Map,a=n.actions.map(u=>u.collectionId);for(let u of n.actions){let h=await this.applyActionsToCollection(u,t,a);if(!h.success)return{success:!1,error:h.error};o.set(u.collectionId,h.transforms),s.set(u.collectionId,h.logTailBlockId),i.set(u.collectionId,h.results)}let c=Array.from(o.entries()).flatMap(([u,h])=>[...Object.entries(h.inserts??{}).map(([m,d])=>({type:"insert",collectionId:u,blockId:m,block:d})),...Object.entries(h.updates??{}).map(([m,d])=>({type:"update",collectionId:u,blockId:m,operations:d})),...(h.deletes??[]).map(m=>({type:"delete",collectionId:u,blockId:m}))]),f=this.hashOperations(c),l=await this.coordinateTransaction(t,f,o,s);return l.success?{success:!0,actions:n.actions,results:i}:l}async applyActionsToCollection(t,e,n){let o=this.collections.get(t.collectionId);if(!o)return{success:!1,error:`Collection not found: ${t.collectionId}`};let s=o.tracker.transforms,i=await xt.open(o.tracker,t.collectionId);if(!i)return{success:!1,error:`Log not found for collection ${t.collectionId}`};let a=e.id,c=(o.source.actionContext?.rev??0)+1,f=await i.addActions(t.actions,a,c,()=>At(s),n);return{success:!0,transforms:s,logTailBlockId:f.tailPath.block.header.id,results:[]}}async coordinateTransaction(t,e,n,o){let s=Array.from(o.values()),i=await this.gatherPhase(s),a=await this.pendPhase(t,e,n,i);if(!a.success)return a;let c=await this.commitPhase(t.id,s,a.pendedBlockIds);return c.success?{success:!0}:(await this.cancelPhase(t.id,n),c)}async gatherPhase(t){if(t.length===1||!this.transactor.queryClusterNominees)return null;let e=t.map(s=>this.transactor.queryClusterNominees(s));return(await Promise.all(e)).reduce((s,i)=>(i.nominees.forEach(a=>s.add(a)),s),new Set)}async pendPhase(t,e,n,o){if(n.size===0)return{success:!1,error:"No transforms to pend"};let s=new Map,i=t.id,a=o?Array.from(o):void 0;for(let[c,f]of n.entries()){let l=this.collections.get(c);if(!l)return{success:!1,error:`Collection not found: ${c}`};let u=(l.source.actionContext?.rev??0)+1,h={actionId:i,rev:u,transforms:f,policy:"r",transaction:t,operationsHash:e,superclusterNominees:a},m=await this.transactor.pend(h);if(!m.success)return{success:!1,error:`Pend failed for collection ${c}: ${m.reason}`};s.set(c,m.blockIds)}return{success:!0,pendedBlockIds:s}}async commitPhase(t,e,n){for(let[o,s]of n.entries()){let i=this.collections.get(o);if(!i)return{success:!1,error:`Collection not found: ${o}`};let a=(i.source.actionContext?.rev??0)+1,c=e.find(u=>s.includes(u));if(!c)return{success:!1,error:`Log tail block not found for collection ${o}`};let f={actionId:t,blockIds:s,tailId:c,rev:a};if(!(await this.transactor.commit(f)).success)return{success:!1,error:`Commit failed for collection ${o}`}}return{success:!0}}async cancelPhase(t,e){for(let[n,o]of e.entries()){if(!this.collections.get(n))continue;let i=At(o);await this.transactor.cancel({actionId:t,blockIds:i})}}};var Cn=class{coordinator;transactionId;engine;collectionActions=new Map;reads=[];constructor(t,e,n){this.coordinator=t,this.transactionId=e,this.engine=n}async addAction(t,e){let n={...e,transaction:this.transactionId},o=this.coordinator.collections.get(t);o&&await o.act(n),this.collectionActions.has(t)||this.collectionActions.set(t,[]),this.collectionActions.get(t).push(n)}addRead(t){this.reads.push(t)}async commit(){return await this.coordinator.commitTransaction(this)}rollback(){this.collectionActions.clear(),this.reads.length=0}getCollectionActions(){return this.collectionActions}getReads(){return this.reads}getAffectedCollections(){return new Set(this.collectionActions.keys())}};var Dn=class{coordinator;engine;statements=[];stamp;committed=!1;rolledBack=!1;constructor(t,e,n="local",o=""){this.coordinator=t,this.engine=e,this.stamp=Je(n,Date.now(),o,"unknown")}async execute(t,e){if(this.committed)return{success:!1,error:"Transaction already committed"};if(this.rolledBack)return{success:!1,error:"Transaction already rolled back"};try{let n;if(e)n=e;else{let o={stamp:this.stamp,statements:[t],reads:[],id:"temp"},s=await this.engine.execute(o);if(!s.success||!s.actions)return{success:!1,error:s.error||"Failed to translate statement"};n=s.actions}return await this.coordinator.applyActions(n,this.stamp.id),this.statements.push(t),{success:!0}}catch(n){return{success:!1,error:`Failed to execute statement: ${n instanceof Error?n.message:String(n)}`}}}async commit(){if(this.committed)return{success:!1,error:"Transaction already committed"};if(this.rolledBack)return{success:!1,error:"Transaction already rolled back"};let t={stamp:this.stamp,statements:this.statements,reads:[],id:Qe(this.stamp.id,this.statements,[])};return await this.coordinator.commit(t),this.committed=!0,{success:!0}}async rollback(){if(this.committed)throw new Error("Cannot rollback: transaction already committed");if(this.rolledBack)throw new Error("Transaction already rolled back");await this.coordinator.rollback(this.stamp.id),this.rolledBack=!0,this.statements.length=0}getStampId(){return this.stamp.id}getStamp(){return this.stamp}getStatements(){return this.statements}isCommitted(){return this.committed}isRolledBack(){return this.rolledBack}};var Tn=class{engines;createValidationCoordinator;constructor(t,e){this.engines=t,this.createValidationCoordinator=e}async validate(t,e){let{stamp:n,statements:o}=t,s=this.engines.get(n.engineId);if(!s)return{valid:!1,reason:`Unknown engine: ${n.engineId}`};let i=await s.getSchemaHash();if(i!==n.schemaHash)return{valid:!1,reason:`Schema mismatch: local=${i}, sender=${n.schemaHash}`};let a=this.createValidationCoordinator();try{let c=await s.engine.execute(t);if(!c.success)return{valid:!1,reason:`Re-execution failed: ${c.error}`};c.actions&&c.actions.length>0&&await a.applyActions(c.actions,n.id);let f=a.getTransforms(),l=this.collectOperations(f),u=this.hashOperations(l);return u!==e?{valid:!1,reason:"Operations hash mismatch",computedHash:u}:{valid:!0,computedHash:u}}finally{a.dispose()}}async getSchemaHash(t){let e=this.engines.get(t);return e?await e.getSchemaHash():void 0}collectOperations(t){return Array.from(t.entries()).flatMap(([e,n])=>[...Object.entries(n.inserts??{}).map(([o,s])=>({type:"insert",collectionId:e,blockId:o,block:s})),...Object.entries(n.updates??{}).map(([o,s])=>({type:"update",collectionId:e,blockId:o,operations:s})),...(n.deletes??[]).map(o=>({type:"delete",collectionId:e,blockId:o}))])}hashOperations(t){let e=JSON.stringify(t);return`ops:${ae(e)}`}};var xb=new Uint8Array(0);function Uc(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ce(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Td(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,b=0,p=0,S=d.length;p!==S&&d[p]===0;)p++,g++;for(var y=(S-p)*l+1>>>0,A=new Uint8Array(y);p!==S;){for(var k=d[p],N=0,C=y-1;(k!==0||N<b)&&C!==-1;C--,N++)k+=256*A[C]>>>0,A[C]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");b=N,p++}for(var E=y-b;E!==y&&A[E]===0;)E++;for(var I=c.repeat(g);E<y;++E)I+=r.charAt(A[E]);return I}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var b=0,p=0;d[g]===c;)b++,g++;for(var S=(d.length-g)*f+1>>>0,y=new Uint8Array(S);d[g];){var A=e[d.charCodeAt(g)];if(A===255)return;for(var k=0,N=S-1;(A!==0||k<p)&&N!==-1;N--,k++)A+=a*y[N]>>>0,y[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=k,g++}if(d[g]!==" "){for(var C=S-p;C!==S&&y[C]===0;)C++;for(var E=new Uint8Array(b+(S-C)),I=b;C!==S;)E[I++]=y[C++];return E}}}function m(d){var g=h(d);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:h,decode:m}}var Ld=Td,Nd=Ld,Oc=Nd;var zs=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},js=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Rc(this,t)}},Gs=class{decoders;constructor(t){this.decoders=t}or(t){return Rc(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Rc(r,t){return new Gs({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Zs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new zs(t,e,n),this.decoder=new js(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function _c({name:r,prefix:t,encode:e,decode:n}){return new Zs(r,t,e,n)}function tr({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Oc(e,r);return _c({prefix:t,name:r,encode:n,decode:s=>ce(o(s))})}function Ud(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=t[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Od(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function Rd(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function Lt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Rd(n);return _c({prefix:t,name:r,encode(s){return Od(s,n,e)},decode(s){return Ud(s,o,e,r)}})}var pt=tr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ab=tr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Rr=Lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Cb=Lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Db=Lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Tb=Lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Lb=Lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Nb=Lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ub=Lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ob=Lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Rb=Lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ln=tr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Mb=tr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var _d=Kc,Pc=128,Pd=127,Md=~Pd,Kd=Math.pow(2,31);function Kc(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Kd;)t[e++]=r&255|Pc,r/=128;for(;r&Md;)t[e++]=r&255|Pc,r>>>=7;return t[e]=r|0,Kc.bytes=e-n+1,t}var qd=Ys,Hd=128,Mc=127;function Ys(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ys.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&Mc)<<o:(i&Mc)*Math.pow(2,o),o+=7}while(i>=Hd);return Ys.bytes=s-n,e}var Vd=Math.pow(2,7),Fd=Math.pow(2,14),$d=Math.pow(2,21),zd=Math.pow(2,28),jd=Math.pow(2,35),Gd=Math.pow(2,42),Zd=Math.pow(2,49),Yd=Math.pow(2,56),Xd=Math.pow(2,63),Wd=function(r){return r<Vd?1:r<Fd?2:r<$d?3:r<zd?4:r<jd?5:r<Gd?6:r<Zd?7:r<Yd?8:r<Xd?9:10},Jd={encode:_d,decode:qd,encodingLength:Wd},Qd=Jd,_r=Qd;function Pr(r,t=0){return[_r.decode(r,t),_r.decode.bytes]}function er(r,t,e=0){return _r.encode(r,t,e),t}function rr(r){return _r.encodingLength(r)}function or(r,t){let e=t.byteLength,n=rr(r),o=n+rr(e),s=new Uint8Array(o+e);return er(r,s,0),er(e,s,n),s.set(t,o),new nr(r,e,t,s)}function Mr(r){let t=ce(r),[e,n]=Pr(t),[o,s]=Pr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new nr(e,o,i,t)}function Hc(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Uc(r.bytes,e.bytes)}}var nr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Vc(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return eh(e,Xs(r),t??pt.encoder);default:return rh(e,Xs(r),t??Rr.encoder)}}var Fc=new WeakMap;function Xs(r){let t=Fc.get(r);if(t==null){let e=new Map;return Fc.set(r,e),e}return t}var Ie=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Kr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==nh)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=or(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Hc(t.multihash,n.multihash)}toString(t){return Vc(this,t)}toJSON(){return{"/":Vc(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??$c(n,o,s.bytes))}else if(e[oh]===!0){let{version:n,multihash:o,code:s}=e,i=Mr(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Kr)throw new Error(`Version 0 CID must use dag-pb (code: ${Kr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=$c(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Kr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=ce(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new nr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,h]=Pr(t.subarray(e));return e+=h,u},o=n(),s=Kr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),f=e+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(t,e){let[n,o]=th(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Xs(s).set(n,t),s}};function th(r,t){switch(r[0]){case"Q":{let e=t??pt;return[pt.prefix,e.decode(`${pt.prefix}${r}`)]}case pt.prefix:{let e=t??pt;return[pt.prefix,e.decode(r)]}case Rr.prefix:{let e=t??Rr;return[Rr.prefix,e.decode(r)]}case Ln.prefix:{let e=t??Ln;return[Ln.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function eh(r,t,e){let{prefix:n}=e;if(n!==pt.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function rh(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Kr=112,nh=18;function $c(r,t,e){let n=rr(r),o=n+rr(t),s=new Uint8Array(o+e.byteLength);return er(r,s,0),er(t,s,n),s.set(e,o),s}var oh=Symbol.for("@ipld/js-cid/CID");var zc=0,sh="identity",jc=ce;function ih(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return or(zc,jc(r))}var Un={code:zc,name:sh,encode:jc,digest:ih};var ah=20;function Js({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new Ws(r,t,e,n,o)}var Ws=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??ah,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Gc(n,this.code,e?.truncate):n.then(o=>Gc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function Gc(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return or(t,r)}function Zc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Yc=Js({name:"sha2-256",code:18,encode:Zc("SHA-256")}),Qb=Js({name:"sha2-512",code:19,encode:Zc("SHA-512")});var Xc=Symbol.for("nodejs.util.inspect.custom"),ch=114,qr=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[eo]=!0;toString(){return this.string==null&&(this.string=pt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ie.createV1(ch,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Et(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Xc](){return`PeerId(${this.toString()})`}},On=class extends qr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Rn=class extends qr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},_n=class extends qr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},fh=2336,Hr=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Un.digest(Xt(this.url))}[Xc](){return`PeerId(${this.url})`}[eo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ie.createV1(fh,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=Y(t)),t.toString()===this.toString())}};var uh=114,Wc=2336;function Jc(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Mr(pt.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return lh(Ie.parse(r));if(t==null)throw new gt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Mr(t.decode(r))}return Qc(e)}function Qc(r){if(hh(r))return new On({multihash:r});if(dh(r))try{let t=Ac(r);if(t.type==="Ed25519")return new Rn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new _n({multihash:r,publicKey:t})}catch{let e=Y(r.digest);return new Hr(new URL(e))}throw new Xr("Supplied PeerID Multihash is invalid")}function lh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==uh&&r.code!==Wc)throw new Yr("Supplied PeerID CID is invalid");if(r.code===Wc){let t=Y(r.multihash.digest);return new Hr(new URL(t))}return Qc(r.multihash)}function dh(r){return r.code===Un.code}function hh(r){return r.code===Yc.code}async function mt(r){let t=new TextEncoder().encode(r);return(await An.digest(t)).digest}function tf(r){for(let t in r)return!1;return!0}var Vr=class{promise;response;error;t1=Date.now();duration;get isResponse(){return this.response!==void 0}get isError(){return this.error!==void 0}get isComplete(){return this.isResponse||this.isError}async result(){if(this.isResponse)return this.response;if(this.isError)throw this.error;return await this.promise}constructor(t){this.promise=t,t.then(e=>(this.duration=Date.now()-this.t1,this.response=e,e),e=>{this.duration=Date.now()-this.t1,this.error=e})}};function Qs(r,t,e,n){let o=r.reduce((s,[i,a])=>{let c=a.toString(),f=s.get(c)??{peerId:a,blockId:i,excludedPeers:n};return s.set(c,{...f,payload:e(t,i,f.payload)}),s},new Map);return Array.from(o.values())}function*ef(r){let t=[...r];for(;t.length>0;){let e=t.pop();(!e.request||!e.request.isResponse)&&(yield e),e.subsumedBy&&e.subsumedBy.length&&t.push(...e.subsumedBy)}}function ti(r,t){for(let e of r){let n=!1,o=[e];for(;o.length>0;){let s=o.pop();if(t(s)){n=!0;break}if(s.subsumedBy&&s.subsumedBy.length)for(let i=0;i<s.subsumedBy.length;i++)o.push(s.subsumedBy[i])}if(!n)return!1}return!0}function*$t(r,t){let e=[...r];for(;e.length>0;){let n=e.pop();(!t||t(n))&&(yield n),n.subsumedBy&&n.subsumedBy.length&&e.push(...n.subsumedBy)}}function Se(r,t,e){return[...e??[],t]}async function Ae(r,t,e,n,o,s){let i=new WeakMap;for(let c of r)i.set(c,c);let a=async c=>{await Promise.all(c.map(async f=>{f.request=new Vr(t(f).catch(async l=>{if(o>Date.now()){let u=[f.peerId,...f.excludedPeers??[]],h=await Pn(e(f),f.payload,n,u,s);if(h.length>0&&o>Date.now()){let m=i.get(f)??f;m.subsumedBy=[...m.subsumedBy??[],...h];for(let d of h)i.set(d,m);await a(h)}}throw l}))})),await Promise.all(c.map(f=>f.request?.result().catch(()=>{})))};await a(r)}async function Pn(r,t,e,n,o){let s=new Set(r),i=await Promise.all(Array.from(s).map(async a=>[a,await o(a,{excludedPeers:n})]));return Qs(i,t,e,n)}var ei=class{keyNetwork;timeoutMs;abortOrCancelTimeoutMs;getRepo;constructor(t){this.keyNetwork=t.keyNetwork,this.timeoutMs=t.timeoutMs,this.abortOrCancelTimeoutMs=t.abortOrCancelTimeoutMs,this.getRepo=t.getRepo}async get(t){let e=Array.from(new Set(t.blockIds)),n=await this.batchesForPayload(e,e,(h,m,d)=>[...d??[],...h.filter(g=>g===m)],[]),o=Date.now()+this.timeoutMs,s;try{await Ae(n,h=>this.getRepo(h.peerId).get({blockIds:h.payload,context:t.context},{expiration:o}),h=>h.payload,(h,m,d)=>[...d??[],...h.filter(g=>g===m)],o,async(h,m)=>this.keyNetwork.findCoordinator(await mt(h),m))}catch(h){s=h}let i=h=>h.request?.isResponse===!0&&h.request.response!=null,a=h=>{if(!i(h))return!1;let m=h.request.response;return h.payload.some(d=>{let g=m[d];return g&&typeof g=="object"&&"block"in g&&g.block!=null})},c=Array.from($t(n)).filter(h=>!i(h)||!a(h));if(c.length>0&&Date.now()<o)try{let h=new Map;for(let m of c){let d=new Set([m.peerId,...m.excludedPeers??[]]);h.set(m,d);let g=await Pn(m.payload,m.payload,(b,p,S)=>[...S??[],...b.filter(y=>y===p)],Array.from(d),async(b,p)=>this.keyNetwork.findCoordinator(await mt(b),p));g.length>0&&(m.subsumedBy=[...m.subsumedBy??[],...g],await Ae(g,b=>this.getRepo(b.peerId).get({blockIds:b.payload,context:t.context},{expiration:o}),b=>b.payload,(b,p,S)=>[...S??[],...b.filter(y=>y===p)],o,async(b,p)=>this.keyNetwork.findCoordinator(await mt(b),p)))}}catch(h){s||(s=h)}let f=Array.from($t(n,h=>h.request?.isResponse&&!tf(h.request.response))),l=new Map;for(let h of f){let m=h.request.response;for(let[d,g]of Object.entries(m)){let b=l.get(d),p=g&&typeof g=="object"&&"block"in g&&g.block!=null,S=b&&typeof b=="object"&&"block"in b&&b.block!=null;(!b||p&&!S)&&l.set(d,g)}}if(e.filter(h=>!l.has(h)).length>0){let h=this.formatBatchStatuses(n,d=>d.request?.isResponse??!1,d=>{let g=d.request==null?"no-response":d.request.isResponse?"response":"in-flight";return`${d.peerId.toString()}[block:${d.blockId}](${g})`}),m=new Error(`Some peers did not complete: ${h}${s?`; root: ${s.message}`:""}`);throw m.cause=s,m}return Object.fromEntries(l)}async getStatus(t){let e=[...new Set(t.flatMap(o=>o.blockIds))];if(e.length===0)return t.map(o=>({...o,statuses:[]}));let n=await this.get({blockIds:e});return t.map(o=>({...o,statuses:o.blockIds.map(s=>{let i=n[s];if(!i)return"aborted";let{state:a}=i;return a.pendings?.includes(o.actionId)?"pending":a.latest?.actionId===o.actionId?"committed":"aborted"})}))}async consolidateCoordinators(t,e,n){let o=await Promise.all(t.map(async a=>({blockId:a,coordinator:await this.keyNetwork.findCoordinator(await mt(a),{excludedPeers:[]})}))),s=new Map;for(let{blockId:a,coordinator:c}of o){let f=c.toString(),l=s.get(f)??[];l.push(a),s.set(f,l)}let i=[];for(let[a,c]of s){let f=o.find(u=>u.coordinator.toString()===a).coordinator,l={inserts:{},updates:{},deletes:[]};for(let u of c)l=n(e,u,l);i.push({peerId:f,payload:l,blockId:c[0],coordinatingBlockIds:c,excludedPeers:[]})}return i}async pend(t){let e=(c,f,l)=>{let u=Fn(c,f);return l?jn(l,f,u):$n(u,f)},n=At(t.transforms),o=await this.consolidateCoordinators(n,t.transforms,e),s=Date.now()+this.timeoutMs,i;try{await Ae(o,c=>this.getRepo(c.peerId).pend({...t,transforms:c.payload},{expiration:s,coordinatingBlockIds:c.coordinatingBlockIds}),c=>At(c.payload),e,s,async(c,f)=>this.keyNetwork.findCoordinator(await mt(c),f));try{let c=this.keyNetwork;if(typeof c?.recordCoordinator=="function")for(let f of Array.from($t(o)))c.recordCoordinator(await mt(f.blockId),f.peerId)}catch(c){console.warn("Failed to record coordinator hint",c)}}catch(c){i=c}if(!ti(o,c=>c.request?.isResponse&&c.request.response.success)){let c=this.formatBatchStatuses(o,u=>(u.request?.isResponse&&u.request.response?.success)??!1,u=>{let h=u.request==null?"no-response":u.request.isResponse?"non-success":"in-flight";return`${u.peerId.toString()}[block:${u.blockId}](${h})`}),f=new Error(`Some peers did not complete: ${c}${i?`; root: ${i.message}`:""}`),l=i;f.cause=l,f.errors=l?[l]:[],i=f}if(i){Promise.resolve().then(()=>this.cancelBatch(o,{blockIds:n,actionId:t.actionId}));let c=Array.from($t(o,f=>f.request?.isResponse&&!f.request.response.success));if(c.length>0)return{success:!1,missing:ri(c.flatMap(f=>f.request.response.missing).filter(f=>f!==void 0))};throw i}return{success:!0,pending:Array.from($t(o,c=>c.request?.isResponse&&c.request.response.success)).flatMap(c=>c.request.response.pending),blockIds:At(t.transforms)}}async cancel(t){let e=await this.batchesForPayload(t.blockIds,t.blockIds,Se,[]),n=Date.now()+this.abortOrCancelTimeoutMs;await Ae(e,o=>this.getRepo(o.peerId).cancel({actionId:t.actionId,blockIds:o.payload},{expiration:n}),o=>o.payload,Se,n,async(o,s)=>this.keyNetwork.findCoordinator(await mt(o),s))}async queryClusterNominees(t){let e=await mt(t),n=await this.keyNetwork.findCluster(e);return{nominees:Object.keys(n).map(s=>Jc(s))}}async commit(t){let e=[...new Set([...t.blockIds,t.tailId])];if(t.headerId&&!t.blockIds.includes(t.headerId)){let s=await this.commitBlock(t.headerId,e,t.actionId,t.rev);if(!s.success)return s}let n=await this.commitBlock(t.tailId,e,t.actionId,t.rev);if(!n.success)return n;let o=t.blockIds.filter(s=>s!==t.tailId&&!(t.headerId&&s===t.headerId&&!t.blockIds.includes(t.headerId)));if(o.length>0){let{batches:s,error:i}=await this.commitBlocks({blockIds:o,actionId:t.actionId,rev:t.rev});if(i)try{console.warn("[NetworkTransactor] non-tail commit had errors; proceeding after tail commit:",i.message)}catch{}}return{success:!0}}async commitBlock(t,e,n,o){let{batches:s,error:i}=await this.commitBlocks({blockIds:[t],actionId:n,rev:o});if(i){Promise.resolve().then(()=>this.cancel({blockIds:e,actionId:n}));let a=Array.from($t(s,c=>c.request?.isResponse&&!c.request.response.success));if(a.length>0)return{missing:ri(a.flatMap(c=>c.request.response.missing)),success:!1};throw i}return{success:!0}}async commitBlocks({blockIds:t,actionId:e,rev:n}){let o=Date.now()+this.timeoutMs,s=await this.batchesForPayload(t,t,Se,[]),i;try{await Ae(s,a=>this.getRepo(a.peerId).commit({actionId:e,blockIds:a.payload,rev:n},{expiration:o}),a=>a.payload,Se,o,async(a,c)=>this.keyNetwork.findCoordinator(await mt(a),c))}catch(a){i=a}if(!ti(s,a=>a.request?.isResponse&&a.request.response.success)){let a=this.formatBatchStatuses(s,f=>(f.request?.isResponse&&f.request.response?.success)??!1,f=>{let l=f.request==null?"no-response":f.request.isResponse?"non-success":"in-flight",u=f.request?.response,h=u&&u.success===!1?Array.isArray(u.missing)?` missing=${u.missing.length}`:" success=false":"";return`${f.peerId.toString()}[blocks:${f.payload instanceof Array?f.payload.length:1}](${l})${h?" "+h:""}`}),c=new Error(`Some peers did not complete: ${a}${i?`; root: ${i.message}`:""}`);c.cause=i,i=c}return{batches:s,error:i}}async batchesForPayload(t,e,n,o){return Pn(t,e,n,o,async(s,i)=>this.keyNetwork.findCoordinator(await mt(s),i))}async cancelBatch(t,e){let n=Date.now()+this.abortOrCancelTimeoutMs,o=Qs(Array.from($t(t)).map(s=>[s.blockId,s.peerId]),e.blockIds,Se,[]);await Ae(o,s=>this.getRepo(s.peerId).cancel({actionId:e.actionId,blockIds:s.payload},{expiration:n}),s=>s.payload,Se,n,async(s,i)=>this.keyNetwork.findCoordinator(await mt(s),i))}formatBatchStatuses(t,e,n){let s=Array.from(ef(t)).map(n).join(", ");return s.length===0&&(s=Array.from($t(t)).map(n).join(", ")),s}};function ri(r){let t=ni(r,({actionId:e})=>e);return Object.entries(t).map(([e,n])=>({actionId:e,transforms:Vn(...n.map(o=>o.transforms))}))}var We=class{collectionId;transactor;actionContext;constructor(t,e,n){this.collectionId=t,this.transactor=e,this.actionContext=n}createBlockHeader(t,e){return{type:t,id:e??this.generateId(),collectionId:this.collectionId}}generateId(){return Y(Ze(32),"base64url")}async tryGet(t){let e=await this.transactor.get({blockIds:[t],context:this.actionContext});if(e){let{block:n,state:o}=e[t];return n}}async transact(t,e,n,o,s){let i=await this.transactor.pend({transforms:t,actionId:e,rev:n,policy:"r"});if(!i.success)return i;let a=t.inserts&&Object.hasOwn(t.inserts,o),c=await this.transactor.commit({headerId:a?o:void 0,tailId:s,blockIds:i.blockIds,actionId:e,rev:n});if(!c.success)return c}};var Ft=class{source;transforms;constructor(t,e=sr()){this.source=t,this.transforms=e}async tryGet(t){let e=await this.source.tryGet(t);if(e){if((this.transforms.updates?.[t]??[]).forEach(o=>Nt(e,o)),this.transforms.deletes?.includes(t))return}else if(this.transforms.inserts&&Object.hasOwn(this.transforms.inserts,t))return structuredClone(this.transforms.inserts[t]);return e}generateId(){return this.source.generateId()}createBlockHeader(t,e){return this.source.createBlockHeader(t,e)}insert(t){let e=this.transforms.inserts??={};e[t.header.id]=structuredClone(t);let n=this.transforms.deletes,o=n?.indexOf(t.header.id)??-1;o>=0&&n.splice(o,1)}update(t,e){let n=this.transforms.inserts?.[t];if(n)Nt(n,e);else{let o=this.transforms.updates??={};oi(o,t,()=>[]).push(structuredClone(e))}}delete(t){this.transforms.inserts&&delete this.transforms.inserts[t],this.transforms.updates&&delete this.transforms.updates[t],(this.transforms.deletes??=[]).push(t)}reset(t=sr()){let e=this.transforms;return this.transforms=t,e}transformedBlockIds(){return Array.from(new Set(At(this.transforms)))}conflicts(t){return this.transformedBlockIds().filter(e=>t.has(e))}};var Ut=class extends Ft{store;constructor(t){super(t),this.store=t}commit(){let t=this.reset();zn(t,this.store)}};var Lr=class{source;cache=new Map;constructor(t){this.source=t}async tryGet(t){let e=this.cache.get(t);return e||(e=await this.source.tryGet(t),e&&this.cache.set(t,e)),structuredClone(e)}generateId(){return this.source.generateId()}createBlockHeader(t,e){return this.source.createBlockHeader(t,e)}clear(t=void 0){if(t)for(let e of t)this.cache.delete(e);else this.cache.clear()}transformCache(t){for(let e of t.deletes??[])this.cache.delete(e);for(let[,e]of Object.entries(t.inserts??{}))this.cache.set(e.header.id,structuredClone(e));for(let[e,n]of Object.entries(t.updates??{}))for(let o of n){let s=this.cache.get(e);s&&Nt(s,o)}}};function ni(r,t){return r.reduce((e,n)=>{let o=t(n);return(e[o]??=[]).push(n),e},{})}function oi(r,t,e,n){let o=r[t];return typeof o>"u"?(o=e(),r[t]=o):n&&n(o),o}function ph(r,t,e,n){let o=r.get(t);return typeof o>"u"?(o=e(),r.set(t,o)):n&&n(o),o}return cf(mh);})();
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@noble/hashes/utils.js:
|