@interncom/diplomatic 0.4.1 → 0.4.2
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/web/index.mjs +1 -1
- package/dist/web/mapPool.d.ts +6 -0
- package/dist/web/sync.d.ts +11 -1
- package/dist/web/worker.mjs +1 -1
- package/package.json +1 -1
package/dist/web/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function v$(V){let $=V.length,Q=0,Z=0;while(Z<$){let J=V.charCodeAt(Z++);if((J&4294967168)===0){Q++;continue}else if((J&4294965248)===0)Q+=2;else{if(J>=55296&&J<=56319){if(Z<$){let I=V.charCodeAt(Z);if((I&64512)===56320)++Z,J=((J&1023)<<10)+(I&1023)+65536}}if((J&4294901760)===0)Q+=3;else Q+=4}}return Q}function rQ(V,$,Q){let Z=V.length,J=Q,I=0;while(I<Z){let W=V.charCodeAt(I++);if((W&4294967168)===0){$[J++]=W;continue}else if((W&4294965248)===0)$[J++]=W>>6&31|192;else{if(W>=55296&&W<=56319){if(I<Z){let Y=V.charCodeAt(I);if((Y&64512)===56320)++I,W=((W&1023)<<10)+(Y&1023)+65536}}if((W&4294901760)===0)$[J++]=W>>12&15|224,$[J++]=W>>6&63|128;else $[J++]=W>>18&7|240,$[J++]=W>>12&63|128,$[J++]=W>>6&63|128}$[J++]=W&63|128}}var hQ=new TextEncoder,cQ=50;function dQ(V,$,Q){hQ.encodeInto(V,$.subarray(Q))}function u$(V,$,Q){if(V.length>cQ)dQ(V,$,Q);else rQ(V,$,Q)}var oQ=4096;function gV(V,$,Q){let Z=$,J=Z+Q,I=[],W="";while(Z<J){let Y=V[Z++];if((Y&128)===0)I.push(Y);else if((Y&224)===192){let X=V[Z++]&63;I.push((Y&31)<<6|X)}else if((Y&240)===224){let X=V[Z++]&63,G=V[Z++]&63;I.push((Y&31)<<12|X<<6|G)}else if((Y&248)===240){let X=V[Z++]&63,G=V[Z++]&63,K=V[Z++]&63,R=(Y&7)<<18|X<<12|G<<6|K;if(R>65535)R-=65536,I.push(R>>>10&1023|55296),R=56320|R&1023;I.push(R)}else I.push(Y);if(I.length>=oQ)W+=String.fromCharCode(...I),I.length=0}if(I.length>0)W+=String.fromCharCode(...I);return W}var aQ=new TextDecoder,sQ=200;function tQ(V,$,Q){let Z=V.subarray($,$+Q);return aQ.decode(Z)}function n$(V,$,Q){if(Q>sQ)return tQ(V,$,Q);else return gV(V,$,Q)}class g0{type;data;constructor(V,$){this.type=V,this.data=$}}class s extends Error{constructor(V){super(V);let $=Object.create(s.prototype);Object.setPrototypeOf(this,$),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:s.name})}}var i0=4294967295;function y$(V,$,Q){let Z=Q/4294967296,J=Q;V.setUint32($,Z),V.setUint32($+4,J)}function IV(V,$,Q){let Z=Math.floor(Q/4294967296),J=Q;V.setUint32($,Z),V.setUint32($+4,J)}function WV(V,$){let Q=V.getInt32($),Z=V.getUint32($+4);return Q*4294967296+Z}function b$(V,$){let Q=V.getUint32($),Z=V.getUint32($+4);return Q*4294967296+Z}var eQ=-1,VZ=4294967295,$Z=17179869183;function QZ({sec:V,nsec:$}){if(V>=0&&$>=0&&V<=$Z)if($===0&&V<=VZ){let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,V),Q}else{let Q=V/4294967296,Z=V&4294967295,J=new Uint8Array(8),I=new DataView(J.buffer);return I.setUint32(0,$<<2|Q&3),I.setUint32(4,Z),J}else{let Q=new Uint8Array(12),Z=new DataView(Q.buffer);return Z.setUint32(0,$),IV(Z,4,V),Q}}function ZZ(V){let $=V.getTime(),Q=Math.floor($/1000),Z=($-Q*1000)*1e6,J=Math.floor(Z/1e9);return{sec:Q+J,nsec:Z-J*1e9}}function JZ(V){if(V instanceof Date){let $=ZZ(V);return QZ($)}else return null}function IZ(V){let $=new DataView(V.buffer,V.byteOffset,V.byteLength);switch(V.byteLength){case 4:{let Q=$.getUint32(0),Z=0;return{sec:Q,nsec:0}}case 8:{let Q=$.getUint32(0),Z=$.getUint32(4),J=(Q&3)*4294967296+Z,I=Q>>>2;return{sec:J,nsec:I}}case 12:{let Q=WV($,4),Z=$.getUint32(0);return{sec:Q,nsec:Z}}default:throw new s(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${V.length}`)}}function WZ(V){let $=IZ(V);return new Date($.sec*1000+$.nsec/1e6)}var p$={type:eQ,encode:JZ,decode:WZ};class v0{static defaultCodec=new v0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(p$)}register({type:V,encode:$,decode:Q}){if(V>=0)this.encoders[V]=$,this.decoders[V]=Q;else{let Z=-1-V;this.builtInEncoders[Z]=$,this.builtInDecoders[Z]=Q}}tryToEncode(V,$){for(let Q=0;Q<this.builtInEncoders.length;Q++){let Z=this.builtInEncoders[Q];if(Z!=null){let J=Z(V,$);if(J!=null){let I=-1-Q;return new g0(I,J)}}}for(let Q=0;Q<this.encoders.length;Q++){let Z=this.encoders[Q];if(Z!=null){let J=Z(V,$);if(J!=null)return new g0(Q,J)}}if(V instanceof g0)return V;return null}decode(V,$,Q){let Z=$<0?this.builtInDecoders[-1-$]:this.decoders[$];if(Z)return Z(V,$,Q);else return new g0($,V)}}function YZ(V){return V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer}function d0(V){if(V instanceof Uint8Array)return V;else if(ArrayBuffer.isView(V))return new Uint8Array(V.buffer,V.byteOffset,V.byteLength);else if(YZ(V))return new Uint8Array(V);else return Uint8Array.from(V)}var XZ=100,GZ=2048;class YV{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??v0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.maxDepth=V?.maxDepth??XZ,this.initialBufferSize=V?.initialBufferSize??GZ,this.sortKeys=V?.sortKeys??!1,this.forceFloat32=V?.forceFloat32??!1,this.ignoreUndefined=V?.ignoreUndefined??!1,this.forceIntegerToFloat=V?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new YV({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(V){if(this.entered)return this.clone().encodeSharedRef(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(V){if(this.entered)return this.clone().encode(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(V,$){if($>this.maxDepth)throw Error(`Too deep objects in depth ${$}`);if(V==null)this.encodeNil();else if(typeof V==="boolean")this.encodeBoolean(V);else if(typeof V==="number")if(!this.forceIntegerToFloat)this.encodeNumber(V);else this.encodeNumberAsFloat(V);else if(typeof V==="string")this.encodeString(V);else if(this.useBigInt64&&typeof V==="bigint")this.encodeBigInt64(V);else this.encodeObject(V,$)}ensureBufferSizeToWrite(V){let $=this.pos+V;if(this.view.byteLength<$)this.resizeBuffer($*2)}resizeBuffer(V){let $=new ArrayBuffer(V),Q=new Uint8Array($),Z=new DataView($);Q.set(this.bytes),this.view=Z,this.bytes=Q}encodeNil(){this.writeU8(192)}encodeBoolean(V){if(V===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber(V){if(!this.forceIntegerToFloat&&Number.isSafeInteger(V))if(V>=0)if(V<128)this.writeU8(V);else if(V<256)this.writeU8(204),this.writeU8(V);else if(V<65536)this.writeU8(205),this.writeU16(V);else if(V<4294967296)this.writeU8(206),this.writeU32(V);else if(!this.useBigInt64)this.writeU8(207),this.writeU64(V);else this.encodeNumberAsFloat(V);else if(V>=-32)this.writeU8(224|V+32);else if(V>=-128)this.writeU8(208),this.writeI8(V);else if(V>=-32768)this.writeU8(209),this.writeI16(V);else if(V>=-2147483648)this.writeU8(210),this.writeI32(V);else if(!this.useBigInt64)this.writeU8(211),this.writeI64(V);else this.encodeNumberAsFloat(V);else this.encodeNumberAsFloat(V)}encodeNumberAsFloat(V){if(this.forceFloat32)this.writeU8(202),this.writeF32(V);else this.writeU8(203),this.writeF64(V)}encodeBigInt64(V){if(V>=BigInt(0))this.writeU8(207),this.writeBigUint64(V);else this.writeU8(211),this.writeBigInt64(V)}writeStringHeader(V){if(V<32)this.writeU8(160+V);else if(V<256)this.writeU8(217),this.writeU8(V);else if(V<65536)this.writeU8(218),this.writeU16(V);else if(V<4294967296)this.writeU8(219),this.writeU32(V);else throw Error(`Too long string: ${V} bytes in UTF-8`)}encodeString(V){let Q=v$(V);this.ensureBufferSizeToWrite(5+Q),this.writeStringHeader(Q),u$(V,this.bytes,this.pos),this.pos+=Q}encodeObject(V,$){let Q=this.extensionCodec.tryToEncode(V,this.context);if(Q!=null)this.encodeExtension(Q);else if(Array.isArray(V))this.encodeArray(V,$);else if(ArrayBuffer.isView(V))this.encodeBinary(V);else if(typeof V==="object")this.encodeMap(V,$);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply(V)}`)}encodeBinary(V){let $=V.byteLength;if($<256)this.writeU8(196),this.writeU8($);else if($<65536)this.writeU8(197),this.writeU16($);else if($<4294967296)this.writeU8(198),this.writeU32($);else throw Error(`Too large binary: ${$}`);let Q=d0(V);this.writeU8a(Q)}encodeArray(V,$){let Q=V.length;if(Q<16)this.writeU8(144+Q);else if(Q<65536)this.writeU8(220),this.writeU16(Q);else if(Q<4294967296)this.writeU8(221),this.writeU32(Q);else throw Error(`Too large array: ${Q}`);for(let Z of V)this.doEncode(Z,$+1)}countWithoutUndefined(V,$){let Q=0;for(let Z of $)if(V[Z]!==void 0)Q++;return Q}encodeMap(V,$){let Q=Object.keys(V);if(this.sortKeys)Q.sort();let Z=this.ignoreUndefined?this.countWithoutUndefined(V,Q):Q.length;if(Z<16)this.writeU8(128+Z);else if(Z<65536)this.writeU8(222),this.writeU16(Z);else if(Z<4294967296)this.writeU8(223),this.writeU32(Z);else throw Error(`Too large map object: ${Z}`);for(let J of Q){let I=V[J];if(!(this.ignoreUndefined&&I===void 0))this.encodeString(J),this.doEncode(I,$+1)}}encodeExtension(V){if(typeof V.data==="function"){let Q=V.data(this.pos+6),Z=Q.length;if(Z>=4294967296)throw Error(`Too large extension object: ${Z}`);this.writeU8(201),this.writeU32(Z),this.writeI8(V.type),this.writeU8a(Q);return}let $=V.data.length;if($===1)this.writeU8(212);else if($===2)this.writeU8(213);else if($===4)this.writeU8(214);else if($===8)this.writeU8(215);else if($===16)this.writeU8(216);else if($<256)this.writeU8(199),this.writeU8($);else if($<65536)this.writeU8(200),this.writeU16($);else if($<4294967296)this.writeU8(201),this.writeU32($);else throw Error(`Too large extension object: ${$}`);this.writeI8(V.type),this.writeU8a(V.data)}writeU8(V){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,V),this.pos++}writeU8a(V){let $=V.length;this.ensureBufferSizeToWrite($),this.bytes.set(V,this.pos),this.pos+=$}writeI8(V){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,V),this.pos++}writeU16(V){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,V),this.pos+=2}writeI16(V){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,V),this.pos+=2}writeU32(V){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,V),this.pos+=4}writeI32(V){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,V),this.pos+=4}writeF32(V){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,V),this.pos+=4}writeF64(V){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,V),this.pos+=8}writeU64(V){this.ensureBufferSizeToWrite(8),y$(this.view,this.pos,V),this.pos+=8}writeI64(V){this.ensureBufferSizeToWrite(8),IV(this.view,this.pos,V),this.pos+=8}writeBigUint64(V){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,V),this.pos+=8}writeBigInt64(V){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,V),this.pos+=8}}function XV(V,$){return new YV($).encodeSharedRef(V)}function GV(V){return`${V<0?"-":""}0x${Math.abs(V).toString(16).padStart(2,"0")}`}var KZ=16,RZ=16;class iV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(V=KZ,$=RZ){this.maxKeyLength=V,this.maxLengthPerKey=$,this.caches=[];for(let Q=0;Q<this.maxKeyLength;Q++)this.caches.push([])}canBeCached(V){return V>0&&V<=this.maxKeyLength}find(V,$,Q){let Z=this.caches[Q-1];V:for(let J of Z){let I=J.bytes;for(let W=0;W<Q;W++)if(I[W]!==V[$+W])continue V;return J.str}return null}store(V,$){let Q=this.caches[V.length-1],Z={bytes:V,str:$};if(Q.length>=this.maxLengthPerKey)Q[Math.random()*Q.length|0]=Z;else Q.push(Z)}decode(V,$,Q){let Z=this.find(V,$,Q);if(Z!=null)return this.hit++,Z;this.miss++;let J=gV(V,$,Q),I=Uint8Array.prototype.slice.call(V,$,$+Q);return this.store(I,J),J}}var vV="array",a0="map_key",r$="map_value",wZ=(V)=>{if(typeof V==="string"||typeof V==="number")return V;throw new s("The type of key must be string or number but "+typeof V)};class h${stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(V){let $=this.getUninitializedStateFromPool();$.type=vV,$.position=0,$.size=V,$.array=Array(V)}pushMapState(V){let $=this.getUninitializedStateFromPool();$.type=a0,$.readCount=0,$.size=V,$.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let V={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(V)}return this.stack[this.stackHeadPosition]}release(V){if(this.stack[this.stackHeadPosition]!==V)throw Error("Invalid stack state. Released state is not on top of the stack.");if(V.type===vV){let Q=V;Q.size=0,Q.array=void 0,Q.position=0,Q.type=void 0}if(V.type===a0||V.type===r$){let Q=V;Q.size=0,Q.map=void 0,Q.readCount=0,Q.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var o0=-1,uV=new DataView(new ArrayBuffer(0)),NZ=new Uint8Array(uV.buffer);try{uV.getInt8(0)}catch(V){if(!(V instanceof RangeError))throw Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var l$=RangeError("Insufficient data"),MZ=new iV;class KV{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=uV;bytes=NZ;headByte=o0;stack=new h$;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??v0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.rawStrings=V?.rawStrings??!1,this.maxStrLength=V?.maxStrLength??i0,this.maxBinLength=V?.maxBinLength??i0,this.maxArrayLength=V?.maxArrayLength??i0,this.maxMapLength=V?.maxMapLength??i0,this.maxExtLength=V?.maxExtLength??i0,this.keyDecoder=V?.keyDecoder!==void 0?V.keyDecoder:MZ,this.mapKeyConverter=V?.mapKeyConverter??wZ}clone(){return new KV({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=o0,this.stack.reset()}setBuffer(V){let $=d0(V);this.bytes=$,this.view=new DataView($.buffer,$.byteOffset,$.byteLength),this.pos=0}appendBuffer(V){if(this.headByte===o0&&!this.hasRemaining(1))this.setBuffer(V);else{let $=this.bytes.subarray(this.pos),Q=d0(V),Z=new Uint8Array($.length+Q.length);Z.set($),Z.set(Q,$.length),this.setBuffer(Z)}}hasRemaining(V){return this.view.byteLength-this.pos>=V}createExtraByteError(V){let{view:$,pos:Q}=this;return RangeError(`Extra ${$.byteLength-Q} of ${$.byteLength} byte(s) found at buffer[${V}]`)}decode(V){if(this.entered)return this.clone().decode(V);try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);let $=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return $}finally{this.entered=!1}}*decodeMulti(V){if(this.entered){yield*this.clone().decodeMulti(V);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(V){if(this.entered)return this.clone().decodeAsync(V);try{this.entered=!0;let $=!1,Q;for await(let W of V){if($)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(W);try{Q=this.doDecodeSync(),$=!0}catch(Y){if(!(Y instanceof RangeError))throw Y}this.totalPos+=this.pos}if($){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Q}let{headByte:Z,pos:J,totalPos:I}=this;throw RangeError(`Insufficient data in parsing ${GV(Z)} at ${I} (${J} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(V){return this.decodeMultiAsync(V,!0)}decodeStream(V){return this.decodeMultiAsync(V,!1)}async*decodeMultiAsync(V,$){if(this.entered){yield*this.clone().decodeMultiAsync(V,$);return}try{this.entered=!0;let Q=$,Z=-1;for await(let J of V){if($&&Z===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(J),Q)Z=this.readArraySize(),Q=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--Z===0)break}catch(I){if(!(I instanceof RangeError))throw I}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){V:while(!0){let V=this.readHeadByte(),$;if(V>=224)$=V-256;else if(V<192)if(V<128)$=V;else if(V<144){let Z=V-128;if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V<160){let Z=V-144;if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else{let Z=V-160;$=this.decodeString(Z,0)}else if(V===192)$=null;else if(V===194)$=!1;else if(V===195)$=!0;else if(V===202)$=this.readF32();else if(V===203)$=this.readF64();else if(V===204)$=this.readU8();else if(V===205)$=this.readU16();else if(V===206)$=this.readU32();else if(V===207)if(this.useBigInt64)$=this.readU64AsBigInt();else $=this.readU64();else if(V===208)$=this.readI8();else if(V===209)$=this.readI16();else if(V===210)$=this.readI32();else if(V===211)if(this.useBigInt64)$=this.readI64AsBigInt();else $=this.readI64();else if(V===217){let Z=this.lookU8();$=this.decodeString(Z,1)}else if(V===218){let Z=this.lookU16();$=this.decodeString(Z,2)}else if(V===219){let Z=this.lookU32();$=this.decodeString(Z,4)}else if(V===220){let Z=this.readU16();if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else if(V===221){let Z=this.readU32();if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else if(V===222){let Z=this.readU16();if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V===223){let Z=this.readU32();if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V===196){let Z=this.lookU8();$=this.decodeBinary(Z,1)}else if(V===197){let Z=this.lookU16();$=this.decodeBinary(Z,2)}else if(V===198){let Z=this.lookU32();$=this.decodeBinary(Z,4)}else if(V===212)$=this.decodeExtension(1,0);else if(V===213)$=this.decodeExtension(2,0);else if(V===214)$=this.decodeExtension(4,0);else if(V===215)$=this.decodeExtension(8,0);else if(V===216)$=this.decodeExtension(16,0);else if(V===199){let Z=this.lookU8();$=this.decodeExtension(Z,1)}else if(V===200){let Z=this.lookU16();$=this.decodeExtension(Z,2)}else if(V===201){let Z=this.lookU32();$=this.decodeExtension(Z,4)}else throw new s(`Unrecognized type byte: ${GV(V)}`);this.complete();let Q=this.stack;while(Q.length>0){let Z=Q.top();if(Z.type===vV)if(Z.array[Z.position]=$,Z.position++,Z.position===Z.size)$=Z.array,Q.release(Z);else continue V;else if(Z.type===a0){if($==="__proto__")throw new s("The key __proto__ is not allowed");Z.key=this.mapKeyConverter($),Z.type=r$;continue V}else if(Z.map[Z.key]=$,Z.readCount++,Z.readCount===Z.size)$=Z.map,Q.release(Z);else{Z.key=null,Z.type=a0;continue V}}return $}}readHeadByte(){if(this.headByte===o0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=o0}readArraySize(){let V=this.readHeadByte();switch(V){case 220:return this.readU16();case 221:return this.readU32();default:if(V<160)return V-144;else throw new s(`Unrecognized array type byte: ${GV(V)}`)}}pushMapState(V){if(V>this.maxMapLength)throw new s(`Max length exceeded: map length (${V}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(V)}pushArrayState(V){if(V>this.maxArrayLength)throw new s(`Max length exceeded: array length (${V}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(V)}decodeString(V,$){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String(V,$);return this.decodeBinary(V,$)}decodeUtf8String(V,$){if(V>this.maxStrLength)throw new s(`Max length exceeded: UTF-8 byte length (${V}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+$+V)throw l$;let Q=this.pos+$,Z;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached(V))Z=this.keyDecoder.decode(this.bytes,Q,V);else Z=n$(this.bytes,Q,V);return this.pos+=$+V,Z}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===a0;return!1}decodeBinary(V,$){if(V>this.maxBinLength)throw new s(`Max length exceeded: bin length (${V}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(V+$))throw l$;let Q=this.pos+$,Z=this.bytes.subarray(Q,Q+V);return this.pos+=$+V,Z}decodeExtension(V,$){if(V>this.maxExtLength)throw new s(`Max length exceeded: ext length (${V}) > maxExtLength (${this.maxExtLength})`);let Q=this.view.getInt8(this.pos+$),Z=this.decodeBinary(V,$+1);return this.extensionCodec.decode(Z,Q,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let V=this.view.getUint8(this.pos);return this.pos++,V}readI8(){let V=this.view.getInt8(this.pos);return this.pos++,V}readU16(){let V=this.view.getUint16(this.pos);return this.pos+=2,V}readI16(){let V=this.view.getInt16(this.pos);return this.pos+=2,V}readU32(){let V=this.view.getUint32(this.pos);return this.pos+=4,V}readI32(){let V=this.view.getInt32(this.pos);return this.pos+=4,V}readU64(){let V=b$(this.view,this.pos);return this.pos+=8,V}readI64(){let V=WV(this.view,this.pos);return this.pos+=8,V}readU64AsBigInt(){let V=this.view.getBigUint64(this.pos);return this.pos+=8,V}readI64AsBigInt(){let V=this.view.getBigInt64(this.pos);return this.pos+=8,V}readF32(){let V=this.view.getFloat32(this.pos);return this.pos+=4,V}readF64(){let V=this.view.getFloat64(this.pos);return this.pos+=8,V}}function nV(V,$){return new KV($).decode(V)}class P0{listeners=new Map;addEventListener(V,$){let Q=this.listeners.get(V);if(!Q)Q=new Set,this.listeners.set(V,Q);return Q.add($),()=>{this.removeEventListener(V,$)}}removeEventListener(V,$){let Q=this.listeners.get(V);if(Q){if(Q.delete($),Q.size===0)this.listeners.delete(V)}}emit(V,$){let Q=this.listeners.get(V);if(Q){let Z=Array.from(Q);for(let J of Z)J($)}}emitAll(V){let $=Array.from(this.listeners.keys());for(let Q of $)this.emit(Q,V)}}class G0{getter;static eventName="update";emitter;constructor(V){this.getter=V;this.emitter=new P0}get=()=>this.getter();async emit(){let V=await this.getter();queueMicrotask(()=>this.emitter.emit(G0.eventName,V))}listen(V){return this.emitter.addEventListener(G0.eventName,V),()=>{this.emitter.removeEventListener(G0.eventName,V)}}}var C0=64;var c$=32,D0=8;var RV=32;var d$=30000,o$=512,_;((H)=>{H[H.Success=0]="Success";H[H.InvalidSignature=3]="InvalidSignature";H[H.ClockOutOfSync=4]="ClockOutOfSync";H[H.UserNotRegistered=5]="UserNotRegistered";H[H.ServerMisconfigured=6]="ServerMisconfigured";H[H.MissingBody=7]="MissingBody";H[H.ExtraBodyContent=8]="ExtraBodyContent";H[H.MissingParam=9]="MissingParam";H[H.InvalidParam=10]="InvalidParam";H[H.InvalidRequest=11]="InvalidRequest";H[H.InternalError=12]="InternalError";H[H.NotFound=13]="NotFound";H[H.InvalidMessage=14]="InvalidMessage";H[H.NoChange=15]="NoChange";H[H.DatabaseClosed=16]="DatabaseClosed";H[H.StorageError=17]="StorageError";H[H.DatabaseError=18]="DatabaseError";H[H.HashMismatch=19]="HashMismatch";H[H.DecryptionError=20]="DecryptionError";H[H.NotImplemented=21]="NotImplemented";H[H.MissingSeed=22]="MissingSeed";H[H.OutOfBounds=23]="OutOfBounds";H[H.HostError=24]="HostError";H[H.CommunicationError=25]="CommunicationError";H[H.VarLimitExceeded=26]="VarLimitExceeded";H[H.InvalidResponse=27]="InvalidResponse";H[H.ConnectionClosed=28]="ConnectionClosed"})(_||={});function O(V){return[V,0]}function w(V){return[void 0,V]}function zZ(V){if(V<0)console.info("N",V),console.trace();if(typeof V!=="bigint")V=BigInt(V);if(V<0n)return w(10);let $=[];while(V>0n){let Q=Number(V&0x7fn);if(V>>=7n,V>0n)$.push(Q|128);else $.push(Q)}if($.length===0)return O(new Uint8Array([0]));if($.length>8)return w(26);return O(new Uint8Array($))}function UZ(V,$=0){let Q=0n,Z=0,J=$;while(!0){if(J>=V.length)return w(14);let I=V[J++];if(I===void 0)return w(14);if(Q|=BigInt(I&127)<<BigInt(Z),(I&128)===0){if(J-$>8)return w(26);return O({value:Q>0x1fffffffffffffn?Q:Number(Q),bytesRead:J-$})}if(Z+=7,Z>=56)return w(26)}}class f{data;pos=0;constructor(V){this.data=V}static async fromResponse(V){let $=await V.arrayBuffer(),Q=new Uint8Array($);return new f(Q)}readBigInt(){if(this.pos+8>this.data.length)return w(7);let V=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,O(V)}readDate(){let[V,$]=this.readVarInt();if($!==0)return w($);return O(new Date(V))}readVarInt(){let[V,$]=UZ(this.data,this.pos);if($!==0)return w($);this.pos+=V.bytesRead;let Q=V.value;return O(typeof Q==="bigint"?Number(Q):Q)}readVarString(){let[V,$]=this.readVarInt();if($!==0)return w($);let[Q,Z]=this.readBytes(V);if(Z!==0)return w(Z);let J=new TextDecoder().decode(Q);return O(J)}readBytes(V){if(V<0)return w(10);if(this.pos+V>this.data.length)return w(23);let $=this.data.slice(this.pos,this.pos+V);return this.pos+=V,O($)}readVarBytes(){let[V,$]=this.readVarInt();if($!==0)return w($);return this.readBytes(V)}readStruct(V){return V.decode(this)}readStructs(V){let $=[];while(!this.done()){let[Q,Z]=this.readStruct(V);if(Z!==0)return w(Z);$.push(Q)}return O($)}readBytesSeq(V){let $=[];while(!this.done()){let[Q,Z]=this.readBytes(V);if(Z!==0)return w(Z);$.push(Q)}return O($)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class k{parts=[];writeBigInt(V){let $=new Uint8Array(8);new DataView($.buffer).setBigUint64(0,V,!1),this.parts.push($)}writeDate(V){let $=V.getTime();return this.writeVarInt($)}writeVarInt(V){let[$,Q]=zZ(V);if(Q!==0)return Q;return this.parts.push($),0}writeVarString(V){let $=new TextEncoder().encode(V),Q=this.writeVarInt($.length);if(Q!==0)return Q;return this.writeBytes($),0}prependBytes(V){this.parts.unshift(V)}writeBytes(V){this.parts.push(V)}writeVarBytes(V){let $=this.writeVarInt(V.length);if($!==0)return $;return this.writeBytes(V),0}writeStruct(V,$){return V.encode(this,$)}writeStructs(V,$){for(let Q of $){let Z=this.writeStruct(V,Q);if(Z!==0)return Z}return 0}writeBytesSeq(V){for(let $ of V)this.writeBytes($)}result(){let V=this.parts.reduce((Z,J)=>Z+J.length,0),$=new Uint8Array(V),Q=0;for(let Z of this.parts)$.set(Z,Q),Q+=Z.length;return $}*scan(){for(let V of this.parts)yield V}}async function yV(V,$,Q){let Z=new k,J=Z.writeDate($);if(J!==0)return w(J);let I=Z.result(),W=await Q.signEd25519(I,V.privateKey);return O({pubKey:V.publicKey,sig:W,timestamp:$})}async function T0(V,$,Q){let Z=Q.now().getTime(),J=V.timestamp.getTime();if(Math.abs(Z-J)>d$)return 4;let W=new k;W.writeDate(V.timestamp);let Y=W.result();if(!await $.checkSigEd25519(V.sig,Y,V.pubKey))return 3;return 0}var Q0={encode(V,$){let Q=V.writeVarBytes($.id);if(Q!==0)return Q;let Z=V.writeDate($.ts);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return w(Q);let[Z,J]=V.readDate();if(J!==0)return w(J);return O({id:$,ts:Z})}};function u0(V){let $=new k,Q=$.writeStruct(Q0,V);if(Q!==0)return w(Q);let Z=$.result();return O(Z)}async function FZ(V){return u0({id:V,ts:new Date(0)})}var Y0={encode(V,$){let Q=V.writeVarBytes($.eid);if(Q!==0)return Q;let Z=V.writeVarInt($.off);if(Z!==0)return Z;let J=V.writeVarInt($.ctr);if(J!==0)return J;let I=V.writeVarInt($.len);if(I!==0)return I;if($.hsh)V.writeBytes($.hsh);return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return w(Q);let Z=new f($),[,J]=Q0.decode(Z);if(J!==0)return w(J);let[I,W]=V.readVarInt();if(W!==0)return w(W);let[Y,X]=V.readVarInt();if(X!==0)return w(X);let[G,K]=V.readVarInt();if(K!==0)return w(K);let R;if(G>0){let[z,M]=V.readBytes(RV);if(M!==0)return w(M);R=z}return O({eid:$,off:I,ctr:Y,len:G,hsh:R})}};function o(V){return Array.from(V).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}function A0(V){if(V.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(V.length/2);for(let Q=0;Q<V.length;Q+=2)$[Q/2]=Number.parseInt(V.substr(Q,2),16);return $}function X0(V,$){if(V===$)return!0;if(V.byteLength!==$.byteLength)return!1;return V.every((Q,Z)=>Q===$[Z])}var g;if(typeof Uint8Array.prototype.toBase64==="function")g=(V)=>V.toBase64();else g=(V)=>btoa(String.fromCharCode(...V));var Z0;if(typeof Uint8Array.fromBase64==="function")Z0=(V)=>Uint8Array.fromBase64(V);else Z0=(V)=>Uint8Array.from(atob(V),($)=>$.charCodeAt(0));function s0(V,$){let Q=new Uint8Array(V.length+$.length);return Q.set(V,0),Q.set($,V.length),Q}function a$(V,$,Q){return Q.checkSigEd25519(V.sig,V.headCph,$)}async function bV(V,$,Q){let Z=s0($.privateKey,V);return(await Q.blake3(Z)).slice(0,D0)}async function s$(V,$,Q,Z){let J;if(V.bod&&V.len>0)J=await Q.blake3(V.bod);let I=new k,W=Y0.encode(I,{...V,hsh:J});if(W!==0)return w(W);let Y=I.result(),X=await bV(Y,$,Q),G=await Z.deriveFromKDM(X),K=await Q.encryptXSalsa20Poly1305Combined(Y,G),R=V.bod?await Q.encryptXSalsa20Poly1305Combined(V.bod,G):new Uint8Array(0),z=await Q.signEd25519(K,$.privateKey);return O({sig:z,kdm:X,headCph:K,bodyCph:R})}async function pV(V,$,Q,Z){let J=new f(V),[I,W]=Y0.decode(J);if(W!==0)return w(14);let Y;try{Y=$&&$.length>0?await Z.decryptXSalsa20Poly1305Combined($,Q):void 0}catch{return w(20)}let X=I.hsh&&Y===void 0,G=I.hsh===void 0&&Y!==void 0;if(X||G)return w(19);if(I.hsh&&Y){let R=await Z.blake3(Y);if(!X0(R,I.hsh))return w(19)}let K=await Z.blake3(V);return O({msgHead:I,bod:Y,headHash:K})}class M0{now(){return new Date}}function t$(V,$,Q,Z){let J=$.getTime()-V.getTime(),I=Q.getTime()-Z.getTime();return(J+I)/2}var t0={encode(V,$){if(V.writeVarInt($.quota),$.quota>0){if($.usage===void 0)return 9;V.writeVarInt($.usage)}return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return w(Q);let Z;if($>0){let[J,I]=V.readVarInt();if(I!==0)return w(I);Z=J}return O({quota:$,usage:Z})}};var lV={encode(V,$){V.writeBytes(new Uint8Array([$.status]));let Q=V.writeDate($.timeRcvd);if(Q!==0)return Q;let Z=V.writeDate($.timeSent);if(Z!==0)return Z;let J=V.writeVarInt($.subscription.term);if(J!==0)return J;let I=V.writeVarInt($.subscription.elapsed);if(I!==0)return I;let W=V.writeStruct(t0,$.subscription.stat);if(W!==0)return W;let Y=V.writeStruct(t0,$.subscription.dyn);if(Y!==0)return Y;return 0},decode(V){let[$,Q]=V.readBytes(1);if(Q!==0)return w(Q);let Z=$[0],[J,I]=V.readDate();if(I!==0)return w(I);let[W,Y]=V.readDate();if(Y!==0)return w(Y);let[X,G]=V.readVarInt();if(G!==0)return w(G);let[K,R]=V.readVarInt();if(R!==0)return w(R);let[z,M]=V.readStruct(t0);if(M!==0)return w(M);let[U,N]=V.readStruct(t0);if(N!==0)return w(N);return O({status:Z,timeRcvd:J,timeSent:W,subscription:{term:X,elapsed:K,stat:z,dyn:U}})}};async function rV(V,$,Q){let{crypto:Z,enclave:J}=V,I=await J.derive($,Q);return await Z.deriveEd25519KeyPair(I)}var hV={encode(V,$){let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarInt($.seq);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return w(Q);let[Z,J]=V.readVarInt();if(J!==0)return w(J);return O({headCph:$,seq:Z})}};var $0={encode(V,$){V.writeBytes($.pubKey),V.writeBytes($.sig);let Q=V.writeDate($.timestamp);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readBytes(c$);if(Q!==0)return w(Q);let[Z,J]=V.readBytes(C0);if(J!==0)return w(J);let[I,W]=V.readDate();if(W!==0)return w(W);return O({pubKey:$,sig:Z,timestamp:I})}};var e$={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct($0,Q);if(I!==0)return I;for(let W of Z)J.writeVarInt(W);return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct($0);if(Y!==0)return Y;let X=await T0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W,[K,R]=await I.hasUser(G);if(R!==0)return R;if(!K)return 5;let[z,M]=$.readVarInt();if(M!==0)return M;if(!$.done())return 8;let[U,N]=await I.listHeads(G,z);if(N!==0)return N;return Q.writeStructs(hV,U)},decodeResp(V){return V.readStructs(hV)}};var cV={encode(V,$){V.writeVarInt($.seq);let Q=V.writeVarBytes($.bodyCph);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return w(Q);let[Z,J]=V.readVarBytes();if(J!==0)return w(J);return O({seq:$,bodyCph:Z})}};var VQ={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct($0,Q);if(I!==0)return I;for(let W of Z){let Y=J.writeVarInt(W);if(Y!==0)return Y}return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct($0);if(Y!==0)return Y;let X=await T0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W,[K,R]=await I.hasUser(G);if(R!==0)return R;if(!K)return 5;let z=[];while(!$.done()){let[N,q]=$.readVarInt();if(q!==0)return q;z.push(N)}console.info(`PULL: ${z.length} bags`);let[M,U]=await I.getBodies(G,z);if(U!==0)return U;if(!M)return 17;for(let{seq:N,bodyCph:q}of M){let P={seq:N,bodyCph:q},C=Q.writeStruct(cV,P);if(C!==0)return C}return 0},decodeResp(V){return V.readStructs(cV)}};var dV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarBytes($.bodyCph);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readBytes(C0);if(Q!==0)return w(Q);let[Z,J]=V.readBytes(D0);if(J!==0)return w(J);let[I,W]=V.readVarBytes();if(W!==0)return w(W);let[Y,X]=V.readVarBytes();if(X!==0)return w(X);return O({sig:$,kdm:Z,headCph:I,bodyCph:Y})}};var wV={encode(V,$){let Q=V.writeVarInt($.seq);if(Q!==0)return Q;let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=$.bodyCph?$.bodyCph.length:0,I=V.writeVarInt(J);if(I!==0)return I;if(J>0){if(!$.bodyCph)return 10;V.writeBytes($.bodyCph)}return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return w(Q);let[Z,J]=V.readVarBytes();if(J!==0)return w(J);let[I,W]=V.readVarInt();if(W!==0)return w(W);let Y;if(I>0){let[X,G]=V.readBytes(I);if(G!==0)return w(G);Y=X}return O({seq:$,headCph:Z,bodyCph:Y})}};var NV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readBytes(C0);if(Q!==0)return w(Q);let[Z,J]=V.readBytes(D0);if(J!==0)return w(J);let[I,W]=V.readVarBytes();if(W!==0)return w(W);return O({sig:$,kdm:Z,headCph:I})}};var MV={encode(V,$){if(V.writeVarInt($.idx),V.writeBytes(new Uint8Array([$.status])),$.status===0)V.writeVarInt($.seq);return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return w(Q);let[Z,J]=V.readBytes(1);if(J!==0)return w(J);let I=Z[0];if(I!==0)return O({idx:$,status:I});let[W,Y]=V.readVarInt();if(Y!==0)return w(Y);return O({idx:$,status:I,seq:W})}};var $Q={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct($0,Q);if(I!==0)return I;let W=J.writeStructs(dV,Z);if(W!==0)return W;return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I,notifier:W}=V,[Y,X]=$.readStruct($0);if(X!==0)return X;let G=await T0(Y,J,Z);if(G!==0)return G;let{pubKey:K}=Y,[R,z]=await I.hasUser(K);if(z!==0)return z;if(!R)return 5;let[M,U]=$.readStructs(dV);if(U!==0)return U;console.info(`PUSH: ${M.length} bags`);let N=[],q=[];for(let F=0;F<M.length;F++){let A=M[F];if(!await a$(A,K,J)){let S={idx:F,status:3},E=Q.writeStruct(MV,S);if(E!==0)return E;continue}N.push(F),q.push(A)}let[P,C]=await I.setBags(K,q);if(C!==0)return C;if(!P||P.length!==q.length)return 17;let T=[];for(let F=0;F<q.length;F++){let A=q[F],j=N[F],S=P[F],E=new k,m=E.writeStruct(NV,A);if(m!==0)return m;let x=E.result(),H={seq:S,headCph:x};if(M.length===1&&A.bodyCph.length<=o$)H.bodyCph=A.bodyCph;T.push(H);let B={idx:j,status:0,seq:S},v=Q.writeStruct(MV,B);if(v!==0)return v}if(T.length>0){let F=new k,A=F.writeStructs(wV,T);if(A!==0)return A;let j=F.result();await Promise.resolve(W.push(K,j))}return 0},decodeResp(V){return V.readStructs(MV)}};var QQ={async encodeReq(V,$,Q,Z,J){return J.writeStruct($0,Q)},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct($0);if(Y!==0)return Y;let X=await T0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W;if(!$.done())return 8;let[K,R]=await I.addUser(G);if(R!==0)return R;return 0},decodeResp(V){return O(void 0)}};class oV{url;websocket;constructor(V){this.url=V}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(V,$,Q=()=>{},Z=()=>{}){let{url:J}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let I=new k;I.writeStruct($0,V);let W=I.result(),Y=o(W);return J.searchParams.set("t",Y),this.websocket=new WebSocket(J),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),Z()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Q()},this.websocket.onmessage=(X)=>{let G=new Uint8Array(X.data);$(G)},this.websocket.onerror=(X)=>{console.log(`ERROR: ${JSON.stringify(X)}`),this.websocket=void 0,Q()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var h={user:{path:"/user",endpoint:QQ,name:0},push:{path:"/push",endpoint:$Q,name:2},peek:{path:"/peek",endpoint:e$,name:1},pull:{path:"/pull",endpoint:VQ,name:3}},OZ={0:h.user,2:h.push,1:h.peek,3:h.pull},YY={[h.user.path]:h.user,[h.push.path]:h.push,[h.peek.path]:h.peek,[h.pull.path]:h.pull};class aV{url;listener;constructor(V){this.url=V;this.listener=new oV(V)}async call(V,$){let{path:Q}=OZ[V],Z=new URL(Q,this.url);try{return await qZ(Z,$)}catch{return w(25)}}}var zV=(V)=>{return new aV(V.handle)};async function qZ(V,$){let Q=await fetch(V,{method:"POST",body:$.result().slice()});if(!Q.ok)return w(24);let Z=await f.fromResponse(Q);return O(Z)}class UV{enclave;crypto;host;clock;transport;updateHostMeta;constructor(V,$,Q,Z,J,I){this.enclave=V;this.crypto=$;this.host=Q;this.clock=Z;this.transport=J;this.updateHostMeta=I}async call(V,$){let{clock:Q,crypto:Z,transport:J}=this,{endpoint:I,name:W}=V,Y=await this.keys(),X=Q.now(),[G,K]=await yV(Y,X,Z);if(K!==0)return w(K);let R=new k,z=await I.encodeReq(this,Y,G,$,R);if(z!==0)return w(z);let M=Q.now(),[U,N]=await J.call(W,R),q=Q.now();if(N!==0)return w(N);let[P,C]=U.readStruct(lV);if(C!==0)return w(C);if(P.status!==0)return w(P.status);let F={clockOffset:t$(M,P.timeRcvd,P.timeSent,q),subscription:P.subscription},A=await this.updateHostMeta(F);if(A!==0)return w(A);return I.decodeResp(U)}keys=()=>{let{host:V}=this;return rV(this,V.label,V.idx)};seal=async(V)=>{let{crypto:$,enclave:Q}=this,Z=await this.keys();return s$(V,Z,$,Q)};register=()=>this.call(h.user,[]);peek=(V)=>this.call(h.peek,[V]);push=(V)=>this.call(h.push,V);pull=(V)=>this.call(h.pull,V);listen=async(V,$,Q)=>{let{clock:Z,crypto:J,host:I,transport:W}=this,{listener:Y}=W,X=await rV(this,I.label,I.idx),G=Z.now(),[K,R]=await yV(X,G,J);if(R!==0)return R;return await Y.connect(K,V,$,Q)};isConnected(){let V=this.transport?.listener;if(V&&typeof V.connected==="function")return V.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var sV={encode(V,$){let Q=V.writeVarString($.lbl);if(Q!==0)return Q;let Z=V.writeVarInt($.idx);if(Z!==0)return Z;let J=V.writeVarInt($.num);if(J!==0)return J;return V.writeBytes($.hsh),V.writeBytes($.sig),0},decode(V){let[$,Q]=V.readVarString();if(Q!==0)return w(Q);let[Z,J]=V.readVarInt();if(J!==0)return w(J);let[I,W]=V.readVarInt();if(W!==0)return w(W);let[Y,X]=V.readBytes(RV);if(X!==0)return w(X);let[G,K]=V.readBytes(C0);if(K!==0)return w(K);return O({lbl:$,idx:Z,num:I,hsh:Y,sig:G})}};var tV={encode(V,$){let Q=V.writeStruct(sV,$.head);if(Q!==0)return Q;let Z=V.writeVarBytes($.indexEnc);if(Z!==0)return Z;let J=V.writeVarBytes($.bodyEnc);if(J!==0)return J;return 0},decode(V){let[$,Q]=V.readStruct(sV);if(Q!==0)return w(Q);let[Z,J]=V.readVarBytes();if(J!==0)return w(J);let[I,W]=V.readVarBytes();if(W!==0)return w(W);return O({head:$,indexEnc:Z,bodyEnc:I})}};var eV={encode(V,$){V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarInt($.lenBody);if(Z!==0)return Z;if($.lenBody>0&&$.offBody!==void 0){let J=V.writeVarInt($.offBody);if(J!==0)return J}return 0},decode(V){let[$,Q]=V.readBytes(D0);if(Q!==0)return w(Q);let[Z,J]=V.readVarBytes();if(J!==0)return w(J);let[I,W]=V.readVarInt();if(W!==0)return w(W);let Y;if(I>0){let[X,G]=V.readVarInt();if(G!==0)return w(G);Y=X}return O({kdm:$,headCph:Z,lenBody:I,offBody:Y})}};async function ZQ(V,$,Q,Z,J){let I=await J.derive(V,$),W=await Z.deriveEd25519KeyPair(I),Y=new k,X=new k,G=0,K=0;for(let C of Q){let T=new k,F=T.writeStruct(Y0,C.head);if(F!==0)return w(F);let A=T.result(),j=await bV(A,W,Z),S=await J.deriveFromKDM(j),E=await Z.encryptXSalsa20Poly1305Combined(A,S),m=C.body?await Z.encryptXSalsa20Poly1305Combined(C.body,S):new Uint8Array(0),x=C.head.len>0&&C.head.hsh!==void 0?m.length:0,H={kdm:j,headCph:E,lenBody:x,offBody:x>0?K:void 0},B=Y.writeStruct(eV,H);if(B!==0)return w(B);if(C.body)X.writeBytes(m),K+=m.length;G++}let R=X.result(),z=Y.result(),M=await Z.blake3(z),U=await Z.signEd25519(M,W.privateKey),N={lbl:V,idx:$,num:G,hsh:M,sig:U},q=new k;q.writeStruct(tV,{head:N,indexEnc:z,bodyEnc:R});let P=q.result();return O(P)}async function JQ(V,$,Q){let[Z,J]=tV.decode(new f(V));if(J!==0)return w(J);let{head:I,indexEnc:W,bodyEnc:Y}=Z,X=await Q.derive(I.lbl,I.idx),G=await $.deriveEd25519KeyPair(X);if(!await $.checkSigEd25519(I.sig,I.hsh,G.publicKey))return w(3);let R=await $.blake3(W);if(!X0(R,I.hsh))return w(19);let z=new f(W),M=[];for(let N=0;N<I.num;N++){let[q,P]=z.readStruct(eV);if(P!==0)return w(P);M.push(q)}if(M.length!==I.num)return w(14);let U=[];for(let N of M){let q=await Q.deriveFromKDM(N.kdm),P=await $.decryptXSalsa20Poly1305Combined(N.headCph,q),[C,T]=Y0.decode(new f(P));if(T!==0)return w(T);let F;if(N.lenBody>0&&N.offBody!==void 0){if(C.hsh===void 0)return w(14);let A=Y.slice(N.offBody,N.offBody+N.lenBody);F=await $.decryptXSalsa20Poly1305Combined(A,q);let j=await $.blake3(F);if(!X0(j,C.hsh))return w(19)}U.push({head:C,body:F})}return O(U)}async function IQ({now:V,bod:$,crypto:Q}){let Z=await Q.genRandomBytes(8),J=new k,I=J.writeStruct(Q0,{id:Z,ts:V});if(I!==0)return w(I);let W=J.result();return FV({now:V,eid:W,ctr:0,bod:$,crypto:Q})}async function FV({now:V,eid:$,ctr:Q,bod:Z,crypto:J}){let I=new f($),[W,Y]=Q0.decode(I);if(Y!==0)return w(Y);let X=V.getTime()-W.ts.getTime(),G,K=Z?.length??0;if(Z&&K>0)G=await J.blake3(Z);return O({eid:$,off:X,ctr:Q,len:K,hsh:G})}class OV{inflight=null;again=!1;run(V){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain(V),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain(V){try{this.again=!1;let $=await V();while(this.again)this.again=!1,$=await V();return $}finally{this.inflight=null}}}var qV=100;class e0{timer=null;delayMs;work;tail=new OV;constructor(V,$){this.delayMs=V<0?0:V,this.work=$}schedule(){if(this.delayMs<=0){this.fire();return}if(this.timer!==null)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=null,this.fire()},this.delayMs)}async flush(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null,this.fire();await this.tail.flush()}cancel(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null}fire(){return this.tail.run(this.work)}}var n0={phase:"idle"},VV=50;function y0(V,$,Q){if(V<=0||$<=0)return!1;if(V===1||V===$)return!0;return V%Q===0}function HV(V,$){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(V,$);return}let Q=URL.createObjectURL(V),Z=document.createElement("a");Z.href=Q,Z.download=$,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)}function WQ(V,$,Q){let Z=[],J=[],I=0;for(let W of V){let Y=$(W);if(J.length>0&&I+Y>Q)Z.push(J),J=[],I=0;if(J.push(W),I+=Y,I>=Q)Z.push(J),J=[],I=0}if(J.length>0)Z.push(J);return Z}async function V$(V,$,Q,Z){let J=new f(V.headCph),[I,W]=J.readStruct(NV);if(W!==0)return w(W);let{sig:Y,kdm:X,headCph:G}=I;if(!await Z.checkSigEd25519(Y,G,$.publicKey))return w(3);let R=await Q.deriveFromKDM(X),z;try{z=await Z.decryptXSalsa20Poly1305Combined(G,R)}catch{return w(20)}return O({kdm:X,headEnc:z})}var $$=1048576,Q$=1048576;function HZ(V){return V.sig.length+V.kdm.length+V.headCph.length+V.bodyCph.length}async function PZ(V,$,Q,Z,J){if(Z.length<1)return 0;let[I,W]=await V.push(Z);if(W!==0)return W;if(!I)return 27;for(let X of I){if(X.status!==0){console.error("push err",X);continue}let G=J[X.idx];if(!G){console.error("no hash",X);continue}await $.uploads.deq(Q,[G])}let Y=await $.hosts.get(Q);if(Y){let X=Y.lastSeq,G=X,K=[];for(let R of I)if(R.status===0)K.push(R.seq);K.sort((R,z)=>R-z);for(let R of K)if(R===X+1)X=R;if(X>G)await $.hosts.touch(Q,X)}return 0}async function YQ(V,$){if($.length<1)return O([]);let Q=new Map,Z=[];for(let Y of $)Q.set(Y.seq,Y),Z.push(Y.seq);let[J,I]=await V.pull(Z);if(I!==0)return w(I);if(!J)return w(27);let W=[];for(let{seq:Y,bodyCph:X}of J){let G=Q.get(Y);if(!G)continue;W.push({dl:G,bodyCph:X})}return O(W)}async function CZ(V,$,Q,Z){if(Z.length<1)return O({parts:[],hashes:[]});let J=[],I=[],W=[],Y=new Map;for(let{dl:G,bodyCph:K}of Z){let{head:R,kdm:z,seq:M,host:U}=G,N=new k;N.writeStruct(Y0,R);let q=N.result(),P=await Q.blake3(q),C=await $.deriveFromKDM(z),[T,F]=await pV(q,K,C,Q);if(F!==0){let S=Y.get(U)??[];S.push(M),Y.set(U,S);continue}let A={head:R,body:T.bod};W.push({key:P,data:RQ(A)}),J.push(A),I.push(P);let j=Y.get(U)??[];j.push(M),Y.set(U,j)}let X=await V.messages.add(W);for(let[G,K]of Y)await V.downloads.deq(G,K);for(let G=0;G<X.length;G++){let K=X[G];if(K!==0&&K!==15)console.error("ERR storing",_[K],"for message",G)}return O({parts:J,hashes:I})}async function XQ({conn:V,store:$,enclave:Q,host:Z,crypto:J,onProgress:I,peekProgressEvery:W}){let Y=await V.keys(),X=[],[G,K]=await V.peek(Z.lastSeq);if(K!==0)return K;let R=G.length,z=W??VV;if(I&&R>0)I({phase:"peek",host:Z.label,done:0,total:R});let M=0;for(let U of G){let[N,q]=await V$(U,Y,Q,J);if(q!==0){if(console.error("peek: decrypting item head",q),M+=1,I&&y0(M,R,z))I({phase:"peek",host:Z.label,done:M,total:R});continue}let P=await J.blake3(N.headEnc);if(await $.messages.has(P)){if(console.info("peek: skipping download enqueue"),await $.uploads.deq(Z.label,[P]),M+=1,I&&y0(M,R,z))I({phase:"peek",host:Z.label,done:M,total:R});continue}let T=new f(N.headEnc),[F,A]=T.readStruct(Y0);if(A!==0){if(console.error("peek: reading item head",A),M+=1,I&&y0(M,R,z))I({phase:"peek",host:Z.label,done:M,total:R});continue}if(X.push({kdm:N.kdm,head:F,seq:U.seq,host:Z.label}),M+=1,I&&y0(M,R,z))I({phase:"peek",host:Z.label,done:M,total:R})}if(await $.downloads.enq(X),G.length>0){let U=Math.max(...G.map((N)=>N.seq));await $.hosts.touch(Z.label,U)}if(I)I({phase:"peek",host:Z.label,done:R,total:R});return 0}async function GQ({conn:V,store:$,host:Q,maxPushBytes:Z,onProgress:J}){let I=Z??$$,W=await $.uploads.list(Q.label),Y=W.length,X=0;if(J&&Y>0)J({phase:"push",host:Q.label,done:0,total:Y});let G=[],K=[],R=0,z=async()=>{if(G.length<1)return 0;let M=G.length,U=await PZ(V,$,Q.label,G,K);if(G=[],K=[],R=0,U===0){if(X+=M,J)J({phase:"push",host:Q.label,done:X,total:Y})}return U};for(let M of W){let U=await $.messages.get(M);if(!U){X+=1;continue}let N={...U.head,bod:U.body},[q,P]=await V.seal(N);if(P!==0)return P;if(!q)return 12;let C=HZ(q);if(G.length>0&&R+C>I){let T=await z();if(T!==0)return T}if(G.push(q),K.push(M),R+=C,R>=I){let T=await z();if(T!==0)return T}}return z()}async function KQ({conn:V,store:$,enclave:Q,host:Z,crypto:J,maxPullBytes:I,onProgress:W},Y){let X=I??Q$,G=await $.downloads.list(),K=Array.from(G).filter((N)=>N.host===Z.label);if(K.length<1)return 15;let R=WQ(K,(N)=>N.head.len,X),z=K.length,M=0;if(W)W({phase:"pull",host:Z.label,done:0,total:z});let U=YQ(V,R[0]);for(let N=0;N<R.length;N++){let[q,P]=await U;if(P!==0||!q)return P;if(M+=R[N].length,W)W({phase:"pull",host:Z.label,done:M,total:z});let C=R[N+1];if(C)U=YQ(V,C);if(W)W({phase:"open",host:Z.label,done:M,total:z});let[,T]=await CZ($,Q,J,q);if(T!==0)return T;if(Y){if(W)W({phase:"exec",host:Z.label,done:M,total:z});await Y()}}return 0}function RQ({head:V,body:$}){return{eid:V.eid,...V.off!==0?{off:V.off}:{},...V.ctr!==0?{ctr:V.ctr}:{},body:$,apld:!1}}async function wQ(V,{conn:$,store:Q,enclave:Z,host:J,crypto:I,onProgress:W},Y){let X=J.label,G=await $.keys(),K=new f(V),[R,z]=K.readStructs(wV);if(z!==0){console.error("Failed decoding notif",_[z]);return}let M=!1,N=(await Q.hosts.get(X))?.lastSeq,q=[],P=!1;for(let F of R){let[A,j]=await V$({seq:F.seq,headCph:F.headCph},G,Z,I);if(j!==0){console.error("Failed decrypting notif",_[j]);continue}let S=await I.blake3(A.headEnc);if(await Q.messages.has(S))continue;let E=new f(A.headEnc),[m,x]=E.readStruct(Y0);if(x!==0){console.error("Failed to parse head",_[x]);continue}if(!F.bodyCph&&m.len>0)P=!0,await Q.downloads.enq([{seq:F.seq,host:X,kdm:A.kdm,head:m}]);else q.push({...A,head:m,bodyCph:F.bodyCph,headEncHash:S});if(N===void 0||F.seq!==N+1)console.log("out of seq",F.seq,N),M=!0;else N=F.seq}if(N!==void 0)await Q.hosts.touch(J.label,N);let C=[];for(let F of q){let A=await Z.deriveFromKDM(F.kdm),[j,S]=await pV(F.headEnc,F.bodyCph,A,I);if(S!==0){console.error("Failed to open body",_[S]);continue}C.push({key:F.headEncHash,data:RQ({head:F.head,body:j.bod})})}let T=await Q.messages.add(C);for(let F=0;F<T.length;F++){let A=T[F];if(A!==0&&A!==15)console.error("ERR storing",_[A],"for message",F)}if(W&&C.length>0)W({phase:"open",host:J.label,done:C.length,total:C.length});if(M||P||C.length>0)Y()}class _0{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new OV;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=VV;lastProgress=n0;scheduledSync;constructor(V,$,Q,Z,J,I=!0,W=$$,Y=Q$,X){this.clock=V;this.state=$;this.store=Q;this.transport=Z;this.crypto=J;this.forceSkewHandlingByDefault=I;this.onScheduleSync=X;this.maxPushBytes=W,this.maxPullBytes=Y,this.clientState=new G0(()=>this.getClientState()),this.xferState=new G0(()=>this.getXferState()),this.scheduledSync=new e0(qV,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(G){console.error("Debounced sync failed:",G)}})}emitProgress=(V)=>{this.lastProgress=V,this.xferState.emit()};async setSeed(V){await this.store.seed.save(V),this.clientState.emit()}async getClientState(){let{store:V,connections:$}=this,Q=await V.seed.load(),Z=await V.hosts.list(),J=!1;for(let I of $.values())if(I.isConnected()){J=!0;break}return{hasSeed:Q!==void 0,hasHost:Array.from(Z).length>0,connected:J}}async getXferState(){let{uploads:V,downloads:$}=this.store,Q=await V.count();return{numDownloads:await $.count(),numUploads:Q,progress:this.lastProgress}}apply=async(V,$={enqueueUpload:!0,triggerUpload:!0})=>{let Q=[],Z=[];for(let{head:I,body:W}of V){let Y=new k;Y.writeStruct(Y0,I);let X=Y.result(),G=await this.crypto.blake3(X),K={eid:I.eid,...I.off!==0?{off:I.off}:{},...I.ctr!==0?{ctr:I.ctr}:{},body:W,apld:!1};Q.push(G),Z.push({key:G,data:K})}await this.store.messages.add(Z);let J=await this.applyHashes(Q);if($.enqueueUpload){let I=[];for(let W=0;W<Q.length;W++){let Y=J[W];if(Y===0||Y===15)I.push(Q[W])}if(I.length>0){let W=await this.store.hosts.list();for(let Y of W)await this.store.uploads.enq(Y.label,I);this.xferState.emit()}}if($.triggerUpload)this.scheduleSync();return J};enqueueApplyJob(V){let $=this.applyChain.then(V,V);return this.applyChain=$.then(()=>{return},()=>{return}),$}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let V=await this.store.messages.listUnapplied();if(V.length<1)return[];return this.applyStored(V)}applyHashes=(V)=>{return this.enqueueApplyJob(async()=>{let $=[];for(let J of V){let I=await this.store.messages.get(J);if(I)$.push(I)}let Q=await this.applyStored($),Z=new Map;for(let J=0;J<$.length;J++)Z.set(g($[J].hash),Q[J]??12);return V.map((J)=>Z.get(g(J))??13)})};async applyStored(V){if(V.length<1)return[];let $=V.map((J)=>({...J.head,bod:J.body})),Q=await this.state.apply($),Z=[];for(let J=0;J<V.length;J++){let I=Q[J];if(I===0||I===15)Z.push(V[J].hash)}if(Z.length>0)await this.store.messages.markApplied(Z);return Q}async insertRaw(V){let{clock:$,crypto:Q}=this,[Z,J]=await IQ({now:$.now(),bod:V,crypto:Q});if(J!==0)return w(J);return await this.apply([{head:Z,body:V}]),O(Z)}async upsertRaw(V,$,Q=!1){let{clock:Z,crypto:J,store:I}=this,W=Z.now(),Y=await I.messages.last(V);if(Y){let M=new f(V),[U,N]=M.readStruct(Q0);if(N!==0)return w(N);if(U.ts.getTime()+Y.head.off>W.getTime()){if(Q===!1)return w(4);let P=Y.head.off+1,C=Y.head.ctr+1,T={eid:V,off:P,ctr:C,len:0},A=(await this.apply([{head:T,body:void 0}]))[0];if(A!==0)return w(A);if($===void 0)return O(T);let[j,S]=u0({id:U.id,ts:W});if(S!==0)return w(S);let E={now:W,eid:j,ctr:0,bod:$,crypto:J},[m,x]=await FV(E);if(x!==0)return w(x);let B=(await this.apply([{head:m,body:$}]))[0];if(B!==0)return w(B);return O(m)}}let X=(Y?.head.ctr??-1)+1,[G,K]=await FV({now:W,eid:V,ctr:X,bod:$,crypto:J});if(K!==0)return w(K);let z=(await this.apply([{head:G,body:$}]))[0];if(z!==0)return w(z);return O(G)}async insert(V){let{body:$,type:Q,gid:Z,pid:J}=V,W=XV({body:$,type:Q,gid:Z,pid:J});return this.insertRaw(W)}async upsert(V,$=this.forceSkewHandlingByDefault){let{eid:Q,body:Z,type:J,gid:I,pid:W}=V;if(Q===void 0)return this.insert(V);let X=XV({body:Z,type:J,gid:I,pid:W});return this.upsertRaw(Q,X,$)}async delete(V){return this.upsertRaw(V,void 0,!0)}async genEID(V){let{clock:$,crypto:Q}=this,Z=$.now();if(V!==void 0)return u0({id:V,ts:Z});let J=await Q.genRandomBytes(8);return u0({id:J,ts:Z})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:V,crypto:$,store:Q}=this,Z=await Q.seed.load();if(!Z)return 22;await this.drainApplyQueue();for(let[J,I]of V){let W=await Q.hosts.get(J);if(!W)continue;let Y={conn:I,store:Q,enclave:Z,host:W,crypto:$,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},X=await XQ(Y);if(X!==0)return console.error(`Failed to peek: ${X}`),X;this.xferState.emit();let G=await GQ(Y);if(G!==0)return console.error(`Failed to push: ${G}`),G;this.xferState.emit();let K=await KQ(Y,async()=>{await this.drainApplyQueue()});if(K!==0&&K!==15)return console.error(`Failed to pull: ${K}`),K;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async wipe(){this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush(),await this.store.wipe(),await this.state.clear(),this.lastProgress=n0,this.clientState.emit(),this.xferState.emit()}import=async(V,$)=>{let{crypto:Q,store:Z}=this,J=$?.onProgress,I=await Z.seed.load();if(!I)return 22;console.time("import: decoding file...");let W=await V.bytes(),[Y,X]=await JQ(W,Q,I);if(X!==0)return X;console.timeEnd("import: decoding file...");let G=0;while(G<Y.length){let K=0,R=0,z=G;for(let N=G;N<Y.length&&R<100&&K<102400;N++)K+=Y[N].head.len,R++,z=N+1;let M=Y.slice(G,z);console.time(`import: applying [${G}, ${z}]`);let U=await this.apply(M,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${G}, ${z}]`);for(let N=0;N<M.length;N++){let q=U[N];if(q!==0&&q!==15)console.warn(`failed to import msg ${G+N}: ${_[q]}`)}if(J)queueMicrotask(()=>J(z,Y.length,0));this.emitProgress({phase:"import",done:z,total:Y.length}),G=z}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:V,store:$}=this,Q=await $.seed.load();if(!Q)return w(22);let Z=await $.messages.list();return ZQ("export",0,Z,V,Q)}async export(V){let[$,Q]=await this.exportBytes();if(Q!==0)return Q;if(!$)return 12;let Z=new Blob([$.slice()]);return HV(Z,V),0}async link(V,$=!0){if(await this.store.hosts.add(V),this.clientState.emit(),$){let Q=await this.store.hosts.get(V.label);if(Q)await this.connectToHost(Q)}}async unlink(V){await this.store.hosts.del(V),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async(V,$=!0,Q=!0)=>{let{clock:Z,connections:J,crypto:I,store:W,transport:Y}=this,X=J.get(V.label);if(X){if(X.isConnected())return;try{X.closeListener()}catch{}J.delete(V.label)}let G=await W.seed.load();if(!G)return;console.info(`Connecting to ${V.handle} (${V.label})`);let K=new UV(G,I,V,Z,Y(V),(R)=>W.hosts.set(V.label,R));if(await K.register(),$)await K.listen(async(R)=>{let z={conn:K,store:W,enclave:G,host:V,crypto:I,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return wQ(R,z,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(J.set(V.label,K),this.clientState.emit(),Q)this.scheduleSync()};async connect(V=!0,$=!0){let{connectToHost:Q,scheduleSync:Z,store:J}=this;if(!await J.seed.load())return;await this.drainApplyQueue();let W=await J.hosts.list();for(let Y of W)await Q(Y,V,!1);if($)Z()}disconnect=async()=>{for(let V of this.connections.values())try{V.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var L0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function PV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function Z$(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function r(V,...$){if(!Z$(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function J$(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function NQ(V,$){r(V);let Q=$.outputLen;if(V.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function I$(V){if(typeof V!=="boolean")throw Error(`boolean expected, not ${V}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var z0=(V)=>new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4));var DZ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!DZ)throw Error("Non little-endian hardware is not supported");function TZ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function CV(V){if(typeof V==="string")V=TZ(V);else if(Z$(V))V=DV(V);else throw Error("Uint8Array expected, got "+typeof V);return V}function MQ(V,$){if($==null||typeof $!=="object")throw Error("options must be defined");return Object.assign(V,$)}function zQ(V,$){if(V.length!==$.length)return!1;let Q=0;for(let Z=0;Z<V.length;Z++)Q|=V[Z]^$[Z];return Q===0}var UQ=(V,$)=>{function Q(Z,...J){if(r(Z),V.nonceLength!==void 0){let K=J[0];if(!K)throw Error("nonce / iv required");if(V.varSizeNonce)r(K);else r(K,V.nonceLength)}let I=V.tagLength;if(I&&J[1]!==void 0)r(J[1]);let W=$(Z,...J),Y=(K,R)=>{if(R!==void 0){if(K!==2)throw Error("cipher output not supported");r(R)}},X=!1;return{encrypt(K,R){if(X)throw Error("cannot encrypt() twice with same key + nonce");return X=!0,r(K),Y(W.encrypt.length,R),W.encrypt(K,R)},decrypt(K,R){if(r(K),I&&K.length<I)throw Error("invalid ciphertext length: smaller than tagLength="+I);return Y(W.decrypt.length,R),W.decrypt(K,R)}}}return Object.assign(Q,V),Q};function W$(V,$,Q=!0){if($===void 0)return new Uint8Array(V);if($.length!==V)throw Error("invalid output length, expected "+V+", got: "+$.length);if(Q&&!AZ($))throw Error("invalid output, must be aligned");return $}function AZ(V){return V.byteOffset%4===0}function DV(V){return Uint8Array.from(V)}function K0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function TV(V=32){if(L0&&typeof L0.getRandomValues==="function")return L0.getRandomValues(new Uint8Array(V));if(L0&&typeof L0.randomBytes==="function")return L0.randomBytes(V);throw Error("crypto.getRandomValues must be defined")}var OQ=(V)=>Uint8Array.from(V.split("").map(($)=>$.charCodeAt(0))),_Z=OQ("expand 16-byte k"),LZ=OQ("expand 32-byte k"),jZ=z0(_Z),SZ=z0(LZ);function D(V,$){return V<<$|V>>>32-$}function Y$(V){return V.byteOffset%4===0}var AV=64,mZ=16,qQ=4294967295,FQ=new Uint32Array;function EZ(V,$,Q,Z,J,I,W,Y){let X=J.length,G=new Uint8Array(AV),K=z0(G),R=Y$(J)&&Y$(I),z=R?z0(J):FQ,M=R?z0(I):FQ;for(let U=0;U<X;W++){if(V($,Q,Z,K,W,Y),W>=qQ)throw Error("arx: counter overflow");let N=Math.min(AV,X-U);if(R&&N===AV){let q=U/4;if(U%4!==0)throw Error("arx: invalid block position");for(let P=0,C;P<mZ;P++)C=q+P,M[C]=z[C]^K[P];U+=AV;continue}for(let q=0,P;q<N;q++)P=U+q,I[P]=J[P]^G[q];U+=N}}function HQ(V,$){let{allowShortKeys:Q,extendNonceFn:Z,counterLength:J,counterRight:I,rounds:W}=MQ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},$);if(typeof V!=="function")throw Error("core must be a function");return PV(J),PV(W),I$(I),I$(Q),(Y,X,G,K,R=0)=>{r(Y),r(X),r(G);let z=G.length;if(K===void 0)K=new Uint8Array(z);if(r(K),PV(R),R<0||R>=qQ)throw Error("arx: counter overflow");if(K.length<z)throw Error(`arx: output (${K.length}) is shorter than data (${z})`);let M=[],U=Y.length,N,q;if(U===32)M.push(N=DV(Y)),q=SZ;else if(U===16&&Q)N=new Uint8Array(32),N.set(Y),N.set(Y,16),q=jZ,M.push(N);else throw Error(`arx: invalid 32-byte key, got length=${U}`);if(!Y$(X))M.push(X=DV(X));let P=z0(N);if(Z){if(X.length!==24)throw Error("arx: extended nonce must be 24 bytes");Z(q,P,z0(X.subarray(0,16)),P),X=X.subarray(16)}let C=16-J;if(C!==X.length)throw Error(`arx: nonce must be ${C} or 16 bytes`);if(C!==12){let F=new Uint8Array(12);F.set(X,I?0:12-X.length),X=F,M.push(X)}let T=z0(X);return EZ(V,q,P,T,G,K,R,W),K0(...M),K}}var c=(V,$)=>V[$++]&255|(V[$++]&255)<<8;class PQ{constructor(V){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,V=CV(V),r(V,32);let $=c(V,0),Q=c(V,2),Z=c(V,4),J=c(V,6),I=c(V,8),W=c(V,10),Y=c(V,12),X=c(V,14);this.r[0]=$&8191,this.r[1]=($>>>13|Q<<3)&8191,this.r[2]=(Q>>>10|Z<<6)&7939,this.r[3]=(Z>>>7|J<<9)&8191,this.r[4]=(J>>>4|I<<12)&255,this.r[5]=I>>>1&8190,this.r[6]=(I>>>14|W<<2)&8191,this.r[7]=(W>>>11|Y<<5)&8065,this.r[8]=(Y>>>8|X<<8)&8191,this.r[9]=X>>>5&127;for(let G=0;G<8;G++)this.pad[G]=c(V,16+2*G)}process(V,$,Q=!1){let Z=Q?0:2048,{h:J,r:I}=this,W=I[0],Y=I[1],X=I[2],G=I[3],K=I[4],R=I[5],z=I[6],M=I[7],U=I[8],N=I[9],q=c(V,$+0),P=c(V,$+2),C=c(V,$+4),T=c(V,$+6),F=c(V,$+8),A=c(V,$+10),j=c(V,$+12),S=c(V,$+14),E=J[0]+(q&8191),m=J[1]+((q>>>13|P<<3)&8191),x=J[2]+((P>>>10|C<<6)&8191),H=J[3]+((C>>>7|T<<9)&8191),B=J[4]+((T>>>4|F<<12)&8191),v=J[5]+(F>>>1&8191),y=J[6]+((F>>>14|A<<2)&8191),b=J[7]+((A>>>11|j<<5)&8191),p=J[8]+((j>>>8|S<<8)&8191),l=J[9]+(S>>>5|Z),L=0,d=L+E*W+m*(5*N)+x*(5*U)+H*(5*M)+B*(5*z);L=d>>>13,d&=8191,d+=v*(5*R)+y*(5*K)+b*(5*G)+p*(5*X)+l*(5*Y),L+=d>>>13,d&=8191;let a=L+E*Y+m*W+x*(5*N)+H*(5*U)+B*(5*M);L=a>>>13,a&=8191,a+=v*(5*z)+y*(5*R)+b*(5*K)+p*(5*G)+l*(5*X),L+=a>>>13,a&=8191;let V0=L+E*X+m*Y+x*W+H*(5*N)+B*(5*U);L=V0>>>13,V0&=8191,V0+=v*(5*M)+y*(5*z)+b*(5*R)+p*(5*K)+l*(5*G),L+=V0>>>13,V0&=8191;let i=L+E*G+m*X+x*Y+H*W+B*(5*N);L=i>>>13,i&=8191,i+=v*(5*U)+y*(5*M)+b*(5*z)+p*(5*R)+l*(5*K),L+=i>>>13,i&=8191;let N0=L+E*K+m*G+x*X+H*Y+B*W;L=N0>>>13,N0&=8191,N0+=v*(5*N)+y*(5*U)+b*(5*M)+p*(5*z)+l*(5*R),L+=N0>>>13,N0&=8191;let E0=L+E*R+m*K+x*G+H*X+B*Y;L=E0>>>13,E0&=8191,E0+=v*W+y*(5*N)+b*(5*U)+p*(5*M)+l*(5*z),L+=E0>>>13,E0&=8191;let k0=L+E*z+m*R+x*K+H*G+B*X;L=k0>>>13,k0&=8191,k0+=v*Y+y*W+b*(5*N)+p*(5*U)+l*(5*M),L+=k0>>>13,k0&=8191;let x0=L+E*M+m*z+x*R+H*K+B*G;L=x0>>>13,x0&=8191,x0+=v*X+y*Y+b*W+p*(5*N)+l*(5*U),L+=x0>>>13,x0&=8191;let f0=L+E*U+m*M+x*z+H*R+B*K;L=f0>>>13,f0&=8191,f0+=v*G+y*X+b*Y+p*W+l*(5*N),L+=f0>>>13,f0&=8191;let B0=L+E*N+m*U+x*M+H*z+B*R;L=B0>>>13,B0&=8191,B0+=v*K+y*G+b*X+p*Y+l*W,L+=B0>>>13,B0&=8191,L=(L<<2)+L|0,L=L+d|0,d=L&8191,L=L>>>13,a+=L,J[0]=d,J[1]=a,J[2]=V0,J[3]=i,J[4]=N0,J[5]=E0,J[6]=k0,J[7]=x0,J[8]=f0,J[9]=B0}finalize(){let{h:V,pad:$}=this,Q=new Uint16Array(10),Z=V[1]>>>13;V[1]&=8191;for(let W=2;W<10;W++)V[W]+=Z,Z=V[W]>>>13,V[W]&=8191;V[0]+=Z*5,Z=V[0]>>>13,V[0]&=8191,V[1]+=Z,Z=V[1]>>>13,V[1]&=8191,V[2]+=Z,Q[0]=V[0]+5,Z=Q[0]>>>13,Q[0]&=8191;for(let W=1;W<10;W++)Q[W]=V[W]+Z,Z=Q[W]>>>13,Q[W]&=8191;Q[9]-=8192;let J=(Z^1)-1;for(let W=0;W<10;W++)Q[W]&=J;J=~J;for(let W=0;W<10;W++)V[W]=V[W]&J|Q[W];V[0]=(V[0]|V[1]<<13)&65535,V[1]=(V[1]>>>3|V[2]<<10)&65535,V[2]=(V[2]>>>6|V[3]<<7)&65535,V[3]=(V[3]>>>9|V[4]<<4)&65535,V[4]=(V[4]>>>12|V[5]<<1|V[6]<<14)&65535,V[5]=(V[6]>>>2|V[7]<<11)&65535,V[6]=(V[7]>>>5|V[8]<<8)&65535,V[7]=(V[8]>>>8|V[9]<<5)&65535;let I=V[0]+$[0];V[0]=I&65535;for(let W=1;W<8;W++)I=(V[W]+$[W]|0)+(I>>>16)|0,V[W]=I&65535;K0(Q)}update(V){J$(this);let{buffer:$,blockLen:Q}=this;V=CV(V);let Z=V.length;for(let J=0;J<Z;){let I=Math.min(Q-this.pos,Z-J);if(I===Q){for(;Q<=Z-J;J+=Q)this.process(V,J);continue}if($.set(V.subarray(J,J+I),this.pos),this.pos+=I,J+=I,this.pos===Q)this.process($,0,!1),this.pos=0}return this}destroy(){K0(this.h,this.r,this.buffer,this.pad)}digestInto(V){J$(this),NQ(V,this),this.finished=!0;let{buffer:$,h:Q}=this,{pos:Z}=this;if(Z){$[Z++]=1;for(;Z<16;Z++)$[Z]=0;this.process($,0,!0)}this.finalize();let J=0;for(let I=0;I<8;I++)V[J++]=Q[I]>>>0,V[J++]=Q[I]>>>8;return V}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Q=V.slice(0,$);return this.destroy(),Q}}function kZ(V){let $=(Z,J)=>V(J).update(CV(Z)).digest(),Q=V(new Uint8Array(32));return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=(Z)=>V(Z),$}var X$=kZ((V)=>new PQ(V));function xZ(V,$,Q,Z,J,I=20){let W=V[0],Y=$[0],X=$[1],G=$[2],K=$[3],R=V[1],z=Q[0],M=Q[1],U=J,N=0,q=V[2],P=$[4],C=$[5],T=$[6],F=$[7],A=V[3],j=W,S=Y,E=X,m=G,x=K,H=R,B=z,v=M,y=U,b=N,p=q,l=P,L=C,d=T,a=F,V0=A;for(let N0=0;N0<I;N0+=2)x^=D(j+L|0,7),y^=D(x+j|0,9),L^=D(y+x|0,13),j^=D(L+y|0,18),b^=D(H+S|0,7),d^=D(b+H|0,9),S^=D(d+b|0,13),H^=D(S+d|0,18),a^=D(p+B|0,7),E^=D(a+p|0,9),B^=D(E+a|0,13),p^=D(B+E|0,18),m^=D(V0+l|0,7),v^=D(m+V0|0,9),l^=D(v+m|0,13),V0^=D(l+v|0,18),S^=D(j+m|0,7),E^=D(S+j|0,9),m^=D(E+S|0,13),j^=D(m+E|0,18),B^=D(H+x|0,7),v^=D(B+H|0,9),x^=D(v+B|0,13),H^=D(x+v|0,18),l^=D(p+b|0,7),y^=D(l+p|0,9),b^=D(y+l|0,13),p^=D(b+y|0,18),L^=D(V0+a|0,7),d^=D(L+V0|0,9),a^=D(d+L|0,13),V0^=D(a+d|0,18);let i=0;Z[i++]=W+j|0,Z[i++]=Y+S|0,Z[i++]=X+E|0,Z[i++]=G+m|0,Z[i++]=K+x|0,Z[i++]=R+H|0,Z[i++]=z+B|0,Z[i++]=M+v|0,Z[i++]=U+y|0,Z[i++]=N+b|0,Z[i++]=q+p|0,Z[i++]=P+l|0,Z[i++]=C+L|0,Z[i++]=T+d|0,Z[i++]=F+a|0,Z[i++]=A+V0|0}function fZ(V,$,Q,Z){let J=V[0],I=$[0],W=$[1],Y=$[2],X=$[3],G=V[1],K=Q[0],R=Q[1],z=Q[2],M=Q[3],U=V[2],N=$[4],q=$[5],P=$[6],C=$[7],T=V[3];for(let A=0;A<20;A+=2)X^=D(J+q|0,7),z^=D(X+J|0,9),q^=D(z+X|0,13),J^=D(q+z|0,18),M^=D(G+I|0,7),P^=D(M+G|0,9),I^=D(P+M|0,13),G^=D(I+P|0,18),C^=D(U+K|0,7),W^=D(C+U|0,9),K^=D(W+C|0,13),U^=D(K+W|0,18),Y^=D(T+N|0,7),R^=D(Y+T|0,9),N^=D(R+Y|0,13),T^=D(N+R|0,18),I^=D(J+Y|0,7),W^=D(I+J|0,9),Y^=D(W+I|0,13),J^=D(Y+W|0,18),K^=D(G+X|0,7),R^=D(K+G|0,9),X^=D(R+K|0,13),G^=D(X+R|0,18),N^=D(U+M|0,7),z^=D(N+U|0,9),M^=D(z+N|0,13),U^=D(M+z|0,18),q^=D(T+C|0,7),P^=D(q+T|0,9),C^=D(P+q|0,13),T^=D(C+P|0,18);let F=0;Z[F++]=J,Z[F++]=G,Z[F++]=U,Z[F++]=T,Z[F++]=K,Z[F++]=R,Z[F++]=z,Z[F++]=M}var G$=HQ(xZ,{counterRight:!0,extendNonceFn:fZ}),K$=UQ({blockSize:64,nonceLength:24,tagLength:16},(V,$)=>{return{encrypt(Q,Z){Z=W$(Q.length+32,Z,!1);let J=Z.subarray(0,32),I=Z.subarray(32);Z.set(Q,32),K0(J),G$(V,$,Z,Z);let W=X$(I,J);return Z.set(W,16),K0(Z.subarray(0,16),W),Z.subarray(16)},decrypt(Q,Z){r(Q),Z=W$(Q.length+32,Z,!1);let J=Z.subarray(0,32),I=Z.subarray(32,48),W=Z.subarray(48);Z.set(Q,32),K0(J);let Y=G$(V,$,J,J),X=X$(W,Y);if(!zQ(I,X))throw Error("invalid tag");return G$(V,$,Z.subarray(16),Z.subarray(16)),K0(J,I,X),W}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function BZ(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function $V(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function j0(V,...$){if(!BZ(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function QV(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function _V(V,$){j0(V);let Q=$.outputLen;if(V.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function CQ(V){return new Uint8Array(V.buffer,V.byteOffset,V.byteLength)}function b0(V){return new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4))}function p0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function ZV(V,$){return V<<32-$|V>>>$}var DQ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function TQ(V){return V<<24&4278190080|V<<8&16711680|V>>>8&65280|V>>>24&255}var AQ=DQ?(V)=>V:(V)=>TQ(V);function gZ(V){for(let $=0;$<V.length;$++)V[$]=TQ(V[$]);return V}var t=DQ?(V)=>V:gZ;function iZ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function l0(V){if(typeof V==="string")V=iZ(V);return j0(V),V}class R${}function _Q(V){let $=(Z,J)=>V(J).update(l0(Z)).digest(),Q=V({});return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=(Z)=>V(Z),$}var LQ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var LV=BigInt(4294967295),jQ=BigInt(32);function w$(V,$=!1){if($)return{h:Number(V&LV),l:Number(V>>jQ&LV)};return{h:Number(V>>jQ&LV)|0,l:Number(V&LV)|0}}function U0(V,$,Q,Z,J){return V=V+$+J|0,Z=ZV(Z^V,16),Q=Q+Z|0,$=ZV($^Q,12),{a:V,b:$,c:Q,d:Z}}function F0(V,$,Q,Z,J){return V=V+$+J|0,Z=ZV(Z^V,8),Q=Q+Z|0,$=ZV($^Q,7),{a:V,b:$,c:Q,d:Z}}class N$ extends R${constructor(V,$){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,$V(V),$V($),this.blockLen=V,this.outputLen=$,this.buffer=new Uint8Array(V),this.buffer32=b0(this.buffer)}update(V){QV(this),V=l0(V),j0(V);let{blockLen:$,buffer:Q,buffer32:Z}=this,J=V.length,I=V.byteOffset,W=V.buffer;for(let Y=0;Y<J;){if(this.pos===$)t(Z),this.compress(Z,0,!1),t(Z),this.pos=0;let X=Math.min($-this.pos,J-Y),G=I+Y;if(X===$&&!(G%4)&&Y+X<J){let K=new Uint32Array(W,G,Math.floor((J-Y)/4));t(K);for(let R=0;Y+$<J;R+=Z.length,Y+=$)this.length+=$,this.compress(K,R,!1);t(K);continue}Q.set(V.subarray(Y,Y+X),this.pos),this.pos+=X,this.length+=X,Y+=X}return this}digestInto(V){QV(this),_V(V,this);let{pos:$,buffer32:Q}=this;this.finished=!0,p0(this.buffer.subarray($)),t(Q),this.compress(Q,0,!0),t(Q);let Z=b0(V);this.get().forEach((J,I)=>Z[I]=AQ(J))}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Q=V.slice(0,$);return this.destroy(),Q}_cloneInto(V){let{buffer:$,length:Q,finished:Z,destroyed:J,outputLen:I,pos:W}=this;return V||(V=new this.constructor({dkLen:I})),V.set(...this.get()),V.buffer.set($),V.destroyed=J,V.finished=Z,V.length=Q,V.pos=W,V.outputLen=I,V}clone(){return this._cloneInto()}}function M$(V,$,Q,Z,J,I,W,Y,X,G,K,R,z,M,U,N,q,P,C,T){let F=0;for(let A=0;A<Z;A++)({a:J,b:X,c:z,d:q}=U0(J,X,z,q,Q[$+V[F++]])),{a:J,b:X,c:z,d:q}=F0(J,X,z,q,Q[$+V[F++]]),{a:I,b:G,c:M,d:P}=U0(I,G,M,P,Q[$+V[F++]]),{a:I,b:G,c:M,d:P}=F0(I,G,M,P,Q[$+V[F++]]),{a:W,b:K,c:U,d:C}=U0(W,K,U,C,Q[$+V[F++]]),{a:W,b:K,c:U,d:C}=F0(W,K,U,C,Q[$+V[F++]]),{a:Y,b:R,c:N,d:T}=U0(Y,R,N,T,Q[$+V[F++]]),{a:Y,b:R,c:N,d:T}=F0(Y,R,N,T,Q[$+V[F++]]),{a:J,b:G,c:U,d:T}=U0(J,G,U,T,Q[$+V[F++]]),{a:J,b:G,c:U,d:T}=F0(J,G,U,T,Q[$+V[F++]]),{a:I,b:K,c:N,d:q}=U0(I,K,N,q,Q[$+V[F++]]),{a:I,b:K,c:N,d:q}=F0(I,K,N,q,Q[$+V[F++]]),{a:W,b:R,c:z,d:P}=U0(W,R,z,P,Q[$+V[F++]]),{a:W,b:R,c:z,d:P}=F0(W,R,z,P,Q[$+V[F++]]),{a:Y,b:X,c:M,d:C}=U0(Y,X,M,C,Q[$+V[F++]]),{a:Y,b:X,c:M,d:C}=F0(Y,X,M,C,Q[$+V[F++]]);return{v0:J,v1:I,v2:W,v3:Y,v4:X,v5:G,v6:K,v7:R,v8:z,v9:M,v10:U,v11:N,v12:q,v13:P,v14:C,v15:T}}var R0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},O0=LQ.slice(),SQ=(()=>{let V=Array.from({length:16},(Z,J)=>J),$=(Z)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((J)=>Z[J]),Q=[];for(let Z=0,J=V;Z<7;Z++,J=$(J))Q.push(...J);return Uint8Array.from(Q)})();class z$ extends N${constructor(V={},$=0){super(64,V.dkLen===void 0?32:V.dkLen);this.chunkPos=0,this.chunksDone=0,this.flags=0,this.stack=[],this.posOut=0,this.bufferOut32=new Uint32Array(16),this.chunkOut=0,this.enableXOF=!0;let{key:Q,context:Z}=V,J=Z!==void 0;if(Q!==void 0){if(J)throw Error('Only "key" or "context" can be specified at same time');let I=l0(Q).slice();j0(I,32),this.IV=b0(I),t(this.IV),this.flags=$|R0.KEYED_HASH}else if(J){let I=l0(Z),W=new z$({dkLen:32},R0.DERIVE_KEY_CONTEXT).update(I).digest();this.IV=b0(W),t(this.IV),this.flags=$|R0.DERIVE_KEY_MATERIAL}else this.IV=O0.slice(),this.flags=$;this.state=this.IV.slice(),this.bufferOut=CQ(this.bufferOut32)}get(){return[]}set(){}b2Compress(V,$,Q,Z=0){let{state:J,pos:I}=this,{h:W,l:Y}=w$(BigInt(V),!0),{v0:X,v1:G,v2:K,v3:R,v4:z,v5:M,v6:U,v7:N,v8:q,v9:P,v10:C,v11:T,v12:F,v13:A,v14:j,v15:S}=M$(SQ,Z,Q,7,J[0],J[1],J[2],J[3],J[4],J[5],J[6],J[7],O0[0],O0[1],O0[2],O0[3],W,Y,I,$);J[0]=X^q,J[1]=G^P,J[2]=K^C,J[3]=R^T,J[4]=z^F,J[5]=M^A,J[6]=U^j,J[7]=N^S}compress(V,$=0,Q=!1){let Z=this.flags;if(!this.chunkPos)Z|=R0.CHUNK_START;if(this.chunkPos===15||Q)Z|=R0.CHUNK_END;if(!Q)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,Z,V,$),this.chunkPos+=1,this.chunkPos===16||Q){let J=this.state;this.state=this.IV.slice();for(let I,W=this.chunksDone+1;Q||!(W&1);W>>=1){if(!(I=this.stack.pop()))break;this.buffer32.set(I,0),this.buffer32.set(J,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|R0.PARENT,this.buffer32,0),J=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(J)}this.pos=0}_cloneInto(V){V=super._cloneInto(V);let{IV:$,flags:Q,state:Z,chunkPos:J,posOut:I,chunkOut:W,stack:Y,chunksDone:X}=this;return V.state.set(Z.slice()),V.stack=Y.map((G)=>Uint32Array.from(G)),V.IV.set($),V.flags=Q,V.chunkPos=J,V.chunksDone=X,V.posOut=I,V.chunkOut=W,V.enableXOF=this.enableXOF,V.bufferOut32.set(this.bufferOut32),V}destroy(){this.destroyed=!0,p0(this.state,this.buffer32,this.IV,this.bufferOut32),p0(...this.stack)}b2CompressOut(){let{state:V,pos:$,flags:Q,buffer32:Z,bufferOut32:J}=this,{h:I,l:W}=w$(BigInt(this.chunkOut++));t(Z);let{v0:Y,v1:X,v2:G,v3:K,v4:R,v5:z,v6:M,v7:U,v8:N,v9:q,v10:P,v11:C,v12:T,v13:F,v14:A,v15:j}=M$(SQ,0,Z,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],O0[0],O0[1],O0[2],O0[3],W,I,$,Q);J[0]=Y^N,J[1]=X^q,J[2]=G^P,J[3]=K^C,J[4]=R^T,J[5]=z^F,J[6]=M^A,J[7]=U^j,J[8]=V[0]^N,J[9]=V[1]^q,J[10]=V[2]^P,J[11]=V[3]^C,J[12]=V[4]^T,J[13]=V[5]^F,J[14]=V[6]^A,J[15]=V[7]^j,t(Z),t(J),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,p0(this.buffer.subarray(this.pos));let V=this.flags|R0.ROOT;if(this.stack.length)V|=R0.PARENT,t(this.buffer32),this.compress(this.buffer32,0,!0),t(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else V|=(!this.chunkPos?R0.CHUNK_START:0)|R0.CHUNK_END;this.flags=V,this.b2CompressOut()}writeInto(V){QV(this,!1),j0(V),this.finish();let{blockLen:$,bufferOut:Q}=this;for(let Z=0,J=V.length;Z<J;){if(this.posOut>=$)this.b2CompressOut();let I=Math.min($-this.posOut,J-Z);V.set(Q.subarray(this.posOut,this.posOut+I),Z),this.posOut+=I,Z+=I}return V}xofInto(V){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(V)}xof(V){return $V(V),this.xofInto(new Uint8Array(V))}digestInto(V){if(_V(V,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto(V),this.destroy(),V}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var mQ=_Q((V)=>new z$(V));var U$=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function EQ(V){let $=new Uint8Array(U$.length+32);return $.set(U$),$.set(V.subarray(0,32),U$.length),$}function kQ(V){return typeof V==="string"?new TextEncoder().encode(V):V}function r0(V){let $=new ArrayBuffer(V.byteLength);return new Uint8Array($).set(V),$}class F${verifyKeys=new Map;signKeys=new Map;async genRandomBytes(V){return TV(V)}async gen256BitSecureRandomSeed(){return TV(32)}async encryptXSalsa20Poly1305Combined(V,$){let Q=TV(24),J=K$($,Q).encrypt(V);return new Uint8Array([...Q,...J])}async decryptXSalsa20Poly1305Combined(V,$){let Q=V.slice(0,24),Z=V.slice(24);return K$($,Q).decrypt(Z)}async deriveEd25519KeyPair(V){let $=V,Q=EQ($),Z=await globalThis.crypto.subtle.importKey("pkcs8",r0(Q),{name:"Ed25519"},!0,["sign"]),J=await globalThis.crypto.subtle.exportKey("jwk",Z);if(typeof J.x!=="string")throw Error("Ed25519 JWK missing x");let I=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:J.x},{name:"Ed25519"},!0,["verify"]),W=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",I)),Y=new Uint8Array(64);return Y.set($,0),Y.set(W,32),this.signKeys.set(o($),Z),this.verifyKeys.set(o(W),I),{keyType:"ed25519",privateKey:Y,publicKey:W}}async importSignKey(V){let $=V.subarray(0,32),Q=o($),Z=this.signKeys.get(Q);if(Z)return Z;let J=EQ($),I=await globalThis.crypto.subtle.importKey("pkcs8",r0(J),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Q,I),I}async importVerifyKey(V){let $=o(V),Q=this.verifyKeys.get($);if(Q)return Q;let Z=await globalThis.crypto.subtle.importKey("raw",r0(V),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set($,Z),Z}async signEd25519(V,$){let Q=kQ(V),Z=await this.importSignKey($),J=await globalThis.crypto.subtle.sign({name:"Ed25519"},Z,r0(Q));return new Uint8Array(J)}async checkSigEd25519(V,$,Q){let Z=kQ($);try{let J=await this.importVerifyKey(Q);return await globalThis.crypto.subtle.verify({name:"Ed25519"},J,r0(V),r0(Z))}catch{return!1}}async blake3(V){return mQ(V)}}var vZ=new F$,J0=vZ;var A8=Symbol("EntityID");function xQ(V){return"type"in V}var _8=Symbol("MasterSeed"),L8=Symbol("DerivationSeed"),j8=Symbol("PublicKey"),S8=Symbol("PrivateKey"),m8=Symbol("HostSpecificKeyPair"),E8=Symbol("Hash");function uZ(V){if(!V)return!1;if(typeof V!=="object")return!1;if("body"in V===!1)return!1;if("type"in V===!1)return!1;return!0}function nZ(V){if(!V.bod||V.bod.length===0){let Z={off:V.off,ctr:V.ctr,eid:V.eid};return O(Z)}let $=nV(V.bod);if(uZ($)===!1)return console.warn("msg body invalid",$),w(14);let Q={off:V.off,ctr:V.ctr,eid:V.eid,gid:$.gid,pid:$.pid,type:$.type,body:$.body};return O(Q)}class jV{applier;emitter=new P0;clearer;onTypes;constructor(V,$,Q){this.applier=V;this.clearer=$,this.onTypes=Q}apply=async(V)=>{let $=[],Q=[];for(let W of V){let[Y,X]=nZ(W);if(Q.push(X),X!==0)continue;$.push(Y)}let{stats:Z,types:J}=await this.applier($),I=[];for(let W=0;W<V.length;W++){let Y=Q[W],X=Z[W];if(Y!==0){I.push(Y);continue}if(X!==0){I.push(X);continue}I.push(0)}for(let W of J)this.emitter.emit(W,null);if(J.size>0)this.onTypes?.(J);return I};clear=async()=>{let V=await this.clearer();if(V!==0)return V;return this.emitter.emitAll(null),V};notify=(V)=>{for(let $ of V)this.emitter.emit($,null)};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}var O$={apply:async function(V){return V.map(()=>0)},clear:async function(){return 0},notify:function(V){},on:function(V,$){},off:function(V,$){}};function q$(V){return new jV(($)=>V.apply($),()=>V.clear())}function SV(V,$){let Q=new f($.eid),[Z,J]=Q.readStruct(Q0);if(J!==0)return w(J);let I=new Date(Z.ts.getTime()+$.off);if(V!==void 0&&I<=V.updatedAt)return w(15);if(xQ($))return O({eid:$.eid,gid:$.gid,pid:$.pid,type:$.type,createdAt:Z.ts,updatedAt:I,ctr:$.ctr,body:$.body});else return O(void 0)}var yZ={getEnt:async()=>w(21),getEntities:async(V)=>w(21),countEntities:async()=>w(21),apply:async(V)=>({stats:V.map(()=>21),types:new Set}),clear:async()=>21};var n="entities",mV="entity_type_created_at",H$="entity_type_updated_at",P$="entity_type_group_id",C$="entity_type_parent_id";function bZ(V){let $={bod:V.body,crd:V.createdAt,...V.ctr!==0?{ctr:V.ctr}:{},eid:g(V.eid),gid:V.gid,pid:V.pid?g(V.pid):void 0,typ:V.type,upd:V.updatedAt};if($.gid===void 0)delete $.gid;if($.pid===void 0)delete $.pid;if($.ctr===void 0)delete $.ctr;return $}function h0(V){return{body:V.bod,createdAt:V.crd,updatedAt:V.upd,ctr:V.ctr??0,type:V.typ,eid:Z0(V.eid),gid:V.gid,pid:V.pid?Z0(V.pid):void 0}}class D${db;async init(){this.db=await new Promise((V,$)=>{let Q=indexedDB.open("db",11);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!J)throw Error("Transaction is null during upgrade");if(!Z.objectStoreNames.contains(n))Z.createObjectStore(n,{keyPath:"eid",autoIncrement:!1});let I=J.objectStore(n);if(!I.indexNames.contains(mV))I.createIndex(mV,["typ","crd"],{unique:!1});if(!I.indexNames.contains(H$))I.createIndex(H$,["typ","upd"],{unique:!1});if(!I.indexNames.contains(P$))I.createIndex(P$,["typ","gid"],{unique:!1});if(!I.indexNames.contains(C$))I.createIndex(C$,["typ","pid"],{unique:!1})},Q.onsuccess=()=>V(Q.result),Q.onerror=()=>$(Q.error)})}apply=async(V)=>{let $=new Set;if(!this.db)return{stats:V.map(()=>16),types:$};let Q=this.db.transaction(n,"readwrite"),Z=Q.objectStore(n);return new Promise((J)=>{let I=Array(V.length).fill(0);if(V.length<1){J({stats:[],types:$});return}Q.oncomplete=()=>{J({stats:I,types:$})},Q.onerror=()=>{for(let Y=0;Y<I.length;Y++)if(I[Y]===void 0)I[Y]=18;J({stats:I,types:$})};let W=new Map;for(let Y=0;Y<V.length;Y++){let X=V[Y],G=g(X.eid),K={op:X,index:Y},R=W.get(G);if(R)R.push(K);else W.set(G,[K])}for(let[Y,X]of W){if(X.length<1)continue;let G=Z.get(Y);G.onsuccess=()=>{let K=G.result,R=K?h0(K):void 0;for(let{op:z,index:M}of X){let[U,N]=SV(R,z);if(N!==0){I[M]=N;continue}if(U)$.add(U.type);else if(R)$.add(R.type);R=U}if(R){let z=bZ(R),M=Z.put(z);M.onerror=(U)=>{U.preventDefault();for(let{index:N}of X)I[N]=18}}else{let z=Z.delete(Y);z.onerror=()=>{for(let{index:M}of X)I[M]=18}}},G.onerror=()=>{for(let{index:K}of X)I[K]=18}}})};async clear(){if(!this.db)return 16;let V=this.db.transaction(n,"readwrite"),$=V.objectStore(n);return new Promise((Q)=>{V.oncomplete=()=>Q(0),V.onerror=()=>Q(18),$.clear()})}async getEnt(V){if(!this.db)return w(16);let $=g(V),Z=this.db.transaction(n,"readonly").objectStore(n);return new Promise((J)=>{let I=Z.get($);I.onsuccess=()=>{let W=I.result;if(!W)J(O(void 0));else{let Y=h0(W);J(O(Y))}},I.onerror=()=>J(w(18))})}async getAllOfTypeUpdatedBetween(V,$,Q){if(!this.db)return w(16);let J=this.db.transaction(n,"readonly").objectStore(n).index(H$);return new Promise((I)=>{let W=J.getAll(IDBKeyRange.bound([V,$],[V,Q]));W.onsuccess=()=>{let Y=W.result;I(O(Y.map(h0)))},W.onerror=()=>I(w(18))})}async getGroupMembers(V,$){if(!this.db)return w(16);let Z=this.db.transaction(n,"readonly").objectStore(n).index(P$);return new Promise((J)=>{let I=Z.getAll(IDBKeyRange.only([V,$]));I.onsuccess=()=>{let W=I.result;J(O(W.map(h0)))},I.onerror=()=>J(w(18))})}async getAllOfType(V){if(!this.db)return w(16);let Q=this.db.transaction(n,"readonly").objectStore(n).index(mV);return new Promise((Z)=>{let J=Q.getAll(IDBKeyRange.bound([V],[V,[]]));J.onsuccess=()=>{let I=J.result;Z(O(I.map(h0)))},J.onerror=()=>Z(w(18))})}async getAllEntities(V){if(!this.db)return w(16);if("pid"in V){let $=g(V.pid),Z=this.db.transaction(n,"readonly").objectStore(n).index(C$);return new Promise((J)=>{let I=Z.getAll(IDBKeyRange.only([V.type,$]));I.onsuccess=()=>{let Y=I.result.map(h0);J(O(Y))},I.onerror=()=>J(w(18))})}else if("gid"in V)return await this.getGroupMembers(V.type,V.gid);else if("updatedBetween"in V)return await this.getAllOfTypeUpdatedBetween(V.type,V.updatedBetween.start,V.updatedBetween.end);return await this.getAllOfType(V.type)}async getEntities(V){let[$,Q]=await this.getAllEntities(V);if(Q!==0)return w(Q);return O($)}async countEntities({type:V}){if(!this.db)return w(16);let Q=this.db.transaction(n,"readonly").objectStore(n).index(mV);return new Promise((Z)=>{let J=IDBKeyRange.bound([V],[V,[]]),I=Q.count(J);I.onsuccess=()=>Z(O(I.result)),I.onerror=()=>Z(w(18))})}}async function T$(){let V=new D$;return await V.init(),V}class fQ{ents=new Map;constructor(V=[]){for(let $ of V){let Q=g($.eid);this.ents.set(Q,$)}}async apply(V){let $=new Set,Q=[];for(let Z of V){let J=g(Z.eid),I=this.ents.get(J),[W,Y]=SV(I,Z);if(Y!==0){Q.push(Y);continue}if(W)$.add(W.type);else if(I)$.add(I.type);if(W)this.ents.set(J,W);else this.ents.delete(J);Q.push(0)}return{stats:Q,types:$}}async clear(){return this.ents.clear(),0}async getEnt(V){let $=g(V),Q=this.ents.get($);return O(Q)}async getAllEntities({type:V,gid:$,pid:Q,updatedBetween:Z}){let J=[];if(Q!==void 0){for(let I of this.ents.values())if(I.type===V&&I.pid&&X0(I.pid,Q))J.push(I)}else if($!==void 0){for(let I of this.ents.values())if(I.type===V&&(typeof I.gid==="string"&&I.gid===$))J.push(I)}else if(Z!==void 0){for(let I of this.ents.values())if(I.type===V&&I.updatedAt>=Z.start&&I.updatedAt<=Z.end)J.push(I)}else for(let I of this.ents.values())if(I.type===V)J.push(I);return O(J)}async getEntities(V){let[$,Q]=await this.getAllEntities(V);if(Q!==0)return w(Q);return O($)}async countEntities({type:V}){let $=0;for(let Q of this.ents.values())if(Q.type===V)$+=1;return O($)}}import{useEffect as BV,useState as k$}from"react";class A${db;constructor(V){this.db=V}async enq(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(I0,"readwrite"),Z=Q.objectStore(I0);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=`${W.host}:${W.seq}`;Z.put(W,Y)}})}async deq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(I0,"readwrite"),J=Z.objectStore(I0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=`${V}:${Y}`;J.delete(X)}})}async list(){let $=this.db.transaction(I0,"readonly").objectStore(I0);return new Promise((Q,Z)=>{let J=$.getAll();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async count(){let $=this.db.transaction(I0,"readonly").objectStore(I0);return new Promise((Q,Z)=>{let J=$.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(I0,"readwrite"),$=V.objectStore(I0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}function BQ(V){return{label:V.label,handle:new URL(V.handle),idx:V.idx,lastSeq:V.lastSeq||0,clockOffset:V.clockOffset,subscription:V.subscription}}class _${db;constructor(V){this.db=V}async add(V){return this.put(V)}async put(V){let $={...V,handle:V.handle.toString(),lastSeq:V.lastSeq??0},Q=this.db.transaction(e,"readwrite"),Z=Q.objectStore(e);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error),Z.put($)})}async touch(V,$){let Q=this.db.transaction(e,"readwrite"),Z=Q.objectStore(e);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)return;let X=Y.lastSeq||0;if($<=X)return;Z.put({...Y,lastSeq:$})}})}async get(V){let Q=this.db.transaction(e,"readonly").objectStore(e);return new Promise((Z,J)=>{let I=Q.get(V);I.onsuccess=()=>{let W=I.result;if(!W)Z(void 0);else Z(BQ(W))},I.onerror=()=>J(I.error)})}async set(V,$){let Q=await this.get(V);if(!Q)return 13;try{return await this.put({...Q,...$}),0}catch{return 18}}async del(V){let $=this.db.transaction(e,"readwrite"),Q=$.objectStore(e);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),Q.delete(V)})}async list(){let $=this.db.transaction(e,"readonly").objectStore(e);return new Promise((Q,Z)=>{let J=$.getAll();J.onsuccess=()=>{let I=J.result;Q(I.map(BQ))},J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(e,"readwrite"),$=V.objectStore(e);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}function pZ(V){return V===!0||V==="t"}function S0(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld===void 0?!1:pZ(V.apld)}}function L$(V){return S0(V).apld===!1}async function w0(V,$,Q){let Z=S0($),J=Z.body?.length??0,I;if(Z.body&&J>0)I=await Q.blake3(Z.body);let W={eid:Z.eid,off:Z.off??0,ctr:Z.ctr??0,len:J,hsh:I};return{hash:V,head:W,body:Z.body,applied:Z.apld}}function gQ(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld?"t":"f"}}class j${crypto;db;constructor(V,$){this.crypto=$;this.db=V}async add(V){let $=this.db.transaction(u,"readwrite"),Q=$.objectStore(u);return new Promise((Z)=>{if(V.length===0){Z([]);return}let J=Array(V.length).fill(0);$.oncomplete=()=>Z(J),$.onerror=()=>{for(let I=0;I<J.length;I++)J[I]=18;Z(J)};for(let I=0;I<V.length;I++){let{key:W,data:Y}=V[I],X=g(W),G=Q.put(gQ(Y),X);G.onerror=(K)=>{K.preventDefault(),J[I]=18}}})}async del(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=g(W);Z.delete(Y)}})}async get(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let I=g(V),W=Q.get(I);W.onsuccess=async()=>{let Y=W.result;if(Y)Z(await w0(V,Y,this.crypto));else Z(void 0)},W.onerror=()=>J(W.error)})}async has(V){return await this.get(V)!==void 0}async list(){let $=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Q,Z)=>{let J=[],I=$.openCursor();I.onsuccess=async(W)=>{let Y=W.target.result;if(Y){let{key:X,value:G}=Y,K=Z0(X),R=await w0(K,G,this.crypto);J.push(R),Y.continue()}else Q(J)},I.onerror=()=>Z(I.error)})}async last(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let I,W=Q.openCursor();W.onsuccess=async(Y)=>{let X=Y.target.result;if(X){let{key:G,value:K}=X;if(X0(V,K.eid)){if(!I||(K.ctr??0)>(I.data.ctr??0)||(K.ctr??0)===(I.data.ctr??0)&&(K.off??0)>(I.data.off??0))I={key:G,data:K}}X.continue()}else if(I){let G=Z0(I.key);Z(await w0(G,I.data,this.crypto))}else Z(void 0)},W.onerror=()=>J(W.error)})}async listUnapplied(){let Q=this.db.transaction(u,"readonly").objectStore(u).index(EV);return new Promise((Z,J)=>{let I=[],W=Q.openCursor(IDBKeyRange.only("f"));W.onsuccess=(Y)=>{let X=Y.target.result;if(X){let{primaryKey:G,value:K}=X;I.push({hash:Z0(G),data:K}),X.continue()}else Promise.all(I.map(({hash:G,data:K})=>w0(G,K,this.crypto))).then(Z).catch(J)},W.onerror=()=>J(W.error)})}async markApplied(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=g(W),X=Z.get(Y);X.onsuccess=()=>{let G=X.result;if(!G)return;let K=S0(G);Z.put(gQ({...K,apld:!0}),Y)},X.onerror=(G)=>{G.preventDefault()}}})}async wipe(){let V=this.db.transaction(u,"readwrite"),$=V.objectStore(u);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}class c0{seed;crypto;constructor(V,$){this.seed=V,this.crypto=$}async deriveFromKDM(V){let $=s0(this.seed,V);return await this.crypto.blake3($)}async derive(V,$=0){let Q=new TextEncoder().encode(V),Z=new Uint8Array(8);new DataView(Z.buffer).setBigUint64(0,BigInt($),!1);let J=s0(Q,Z);return await this.deriveFromKDM(J)}}class S${enclave;db;constructor(V){this.db=V}async save(V){let $=o(V),Q=this.db.transaction(q0,"readwrite"),Z=Q.objectStore(q0);return new Promise((J,I)=>{Q.oncomplete=()=>{this.enclave=new c0(V,J0),J(this.enclave)},Q.onerror=()=>I(Q.error),Z.put($,"seed")})}async load(){if(this.enclave)return this.enclave;let $=this.db.transaction(q0,"readonly").objectStore(q0);return new Promise((Q,Z)=>{let J=$.get("seed");J.onsuccess=()=>{let I=J.result;if(!I)Q(void 0);else{let W=A0(I);this.enclave=new c0(W,J0),Q(this.enclave)}},J.onerror=()=>Z(J.error)})}async wipe(){this.enclave=void 0;let V=this.db.transaction(q0,"readwrite"),$=V.objectStore(q0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.delete("seed")})}}class m${db;constructor(V){this.db=V}async enq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=o(Y);J.put({host:V,hash:X})}})}async deq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=o(Y);J.delete([V,X])}})}async list(V){let Q=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Z,J)=>{let I=Q.getAll();I.onsuccess=()=>{let Y=I.result.filter((X)=>X.host===V).map((X)=>X.hash);Z(Y.map((X)=>A0(X)))},I.onerror=()=>J(I.error)})}async count(){let $=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Q,Z)=>{let J=$.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(W0,"readwrite"),$=V.objectStore(W0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}var q0="seedMeta",e="hosts",W0="uploadQueue",I0="downloadQueue",u="messages",EV="apld",lZ=3;class E${seed;hosts;uploads;downloads;messages;db;constructor(V,$){this.db=V,this.seed=new S$(V),this.hosts=new _$(V),this.uploads=new m$(V),this.downloads=new A$(V),this.messages=new j$(V,$)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function rZ(){return new Promise((V,$)=>{let Q=indexedDB.open("diplomatic-store-db",lZ);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!Z.objectStoreNames.contains(q0))Z.createObjectStore(q0);if(!Z.objectStoreNames.contains(e))Z.createObjectStore(e,{keyPath:"label"});if(!Z.objectStoreNames.contains(W0))Z.createObjectStore(W0,{keyPath:["host","hash"]});if(!Z.objectStoreNames.contains(I0))Z.createObjectStore(I0);let I;if(!Z.objectStoreNames.contains(u))I=Z.createObjectStore(u);else{if(!J)throw Error("missing upgrade transaction for messages store");I=J.objectStore(u)}if(!I.indexNames.contains(EV))I.createIndex(EV,"apld",{unique:!1})},Q.onsuccess=()=>V(Q.result),Q.onerror=()=>$(Q.error)})}async function kV(V){let $=await rZ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new E$($,V)}function iQ(V){if(!V||typeof V!=="object")return!1;if(!("kind"in V))return!1;return typeof V.kind==="string"}function vQ(V){if(typeof V!=="number")return;return V}var H0="[DIPLOMATIC]";class JV{worker;state;local;nextId=1;pending=new Map;ready;resolveReady;rejectReady;scheduledSync;cachedClientState={hasSeed:!1,hasHost:!1,connected:!1};cachedXferState={numUploads:0,numDownloads:0,progress:n0};clientState;xferState;constructor(V,$,Q,Z,J){this.worker=V,this.state=$,this.clientState=new G0(async()=>this.cachedClientState),this.xferState=new G0(async()=>this.cachedXferState),this.scheduledSync=new e0(J,async()=>{try{await this.request({id:this.allocId(),op:"sync"})}catch(I){console.error(`${H0} worker sync after local write failed`,I)}}),this.local=new _0(Z,$,Q,()=>{throw Error(`${H0} local writer has no transport (use worker for network)`)},J0,!0,void 0,void 0,()=>{this.scheduledSync.schedule()}),this.ready=new Promise((I,W)=>{this.resolveReady=I,this.rejectReady=W}),this.worker.onmessage=(I)=>{this.onMessage(I.data)},this.worker.onerror=(I)=>{console.error(`${H0} worker error`,I),this.failReady(Error(`${H0} worker failed to load`))},this.worker.onmessageerror=()=>{this.failReady(Error(`${H0} worker message error`))}}failReady(V){let $=this.rejectReady;if(this.rejectReady=void 0,this.resolveReady=void 0,$)$(V)}async flushScheduledSync(){await this.scheduledSync.flush()}static async connect(V,$,Q){let Z=Q.clock??new M0,J=Q.syncDebounceMs??qV,I=new JV(Q.worker,V,$,Z,J),W=Q.readyTimeoutMs??15000,Y;try{let X=I.probeReady();await Promise.race([I.ready,X,new Promise((G,K)=>{Y=setTimeout(()=>{K(Error(`${H0} worker ready timeout after ${W}ms`))},W)})]),X.catch(()=>{})}catch(X){throw I.terminate(),X}finally{if(Y!==void 0)clearTimeout(Y)}return I}markReady(){let V=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V()}probeReady(){return new Promise((V,$)=>{let Q=this.allocId();this.pending.set(Q,{resolve:(Z)=>{if(Z==="pong"){this.markReady(),V();return}$(Error(`${H0} worker probe ping failed`))},reject:$}),this.worker.postMessage({id:Q,op:"ping"})})}async ping(){if(await this.ready,await this.request({id:this.allocId(),op:"ping"})!=="pong")throw Error(`${H0} worker ping failed`)}terminate(){this.scheduledSync.cancel(),this.worker.terminate();for(let[,V]of this.pending)V.reject(Error(`${H0} worker terminated`));this.pending.clear()}onMessage(V){if(!iQ(V))return;let $=V;switch($.kind){case"ready":{this.markReady();return}case"clientState":{this.cachedClientState=$.state,this.clientState.emit();return}case"xferState":{this.cachedXferState=$.state,this.xferState.emit();return}case"dirty":{this.state.notify($.types);return}case"wiped":{this.state.clear();return}case"reply":{let Q=this.pending.get($.id);if(!Q)return;if(this.pending.delete($.id),$.ok)Q.resolve($.result);else Q.reject(new xV($.status));return}default:return}}allocId(){let V=this.nextId;return this.nextId+=1,V}request(V,$){return new Promise((Q,Z)=>{if(this.pending.set(V.id,{resolve:Q,reject:Z}),$&&$.length>0)this.worker.postMessage(V,$);else this.worker.postMessage(V)})}async requestStatus(V,$){try{let Q=await this.request(V,$),Z=vQ(Q);if(Z!==void 0)return Z;return 0}catch(Q){if(Q instanceof xV)return Q.status;return 12}}serializeHost(V){return{handle:V.handle.href,label:V.label,idx:V.idx??0}}async setSeed(V){await this.ready,await this.local.setSeed(V);let $=V.slice();await this.request({id:this.allocId(),op:"setSeed",seed:$},[$.buffer])}async link(V,$=!0){await this.ready,await this.local.link(V,!1),await this.request({id:this.allocId(),op:"link",host:this.serializeHost(V),connect:$})}async unlink(V){await this.ready,await this.local.unlink(V),await this.request({id:this.allocId(),op:"unlink",label:V})}async hosts(){return await this.ready,this.local.hosts()}async connect(V=!0,$=!0){await this.ready,await this.request({id:this.allocId(),op:"connect",listen:V,sync:$})}async disconnect(){await this.ready,await this.request({id:this.allocId(),op:"disconnect"})}async insertRaw(V){return await this.ready,this.local.insertRaw(V)}async upsertRaw(V,$,Q){return await this.ready,this.local.upsertRaw(V,$,Q)}async insert(V){return await this.ready,this.local.insert(V)}async upsert(V,$){return await this.ready,this.local.upsert(V,$)}async delete(V){return await this.ready,this.local.delete(V)}async genEID(V){return await this.ready,this.local.genEID(V)}async sync(){return await this.ready,this.requestStatus({id:this.allocId(),op:"sync"})}async wipe(){await this.ready,await this.request({id:this.allocId(),op:"wipe"})}async import(V){await this.ready;let $=new Uint8Array(await V.arrayBuffer());return this.requestStatus({id:this.allocId(),op:"import",bytes:$},[$.buffer])}async export(V,$){await this.ready;try{let Q=await this.request({id:this.allocId(),op:"export"});if(!(Q instanceof Uint8Array))return 12;let Z=new Blob([Q.slice()]);return HV(Z,V),0}catch(Q){if(Q instanceof xV)return Q.status;return 12}}}class xV extends Error{status;constructor(V){super(`WorkerReplyError: ${_[V]}`);this.status=V;this.name="WorkerReplyError"}}var m0="[DIPLOMATIC]";async function fV(V){let $=V.clock??new M0;if(V.worker!==void 0&&hZ(V)!==void 0)throw Error(`${m0} worker path requires IndexedDB on both sides; do not pass store (got a custom store)`);if(V.worker===void 0){console.info(`${m0} sync on main thread `+"(no worker — app did not request a worker)");let J=await uQ(V.store);return cZ($,V.state,J)}if(typeof Worker>"u")throw Error(`${m0} worker was provided but Worker API is unavailable`);let Q=await uQ(void 0);console.info(`${m0} attaching app-provided sync worker…`);let Z=await JV.connect(V.state,Q,{worker:V.worker,readyTimeoutMs:V.readyTimeoutMs,clock:$,syncDebounceMs:V.syncDebounceMs});return await Z.ping(),console.info(`${m0} sync worker active (network + EntDB writes off main; local mutates on main; dirty signals only)`),{client:Z,mode:"worker",dispose:()=>{console.info(`${m0} terminating sync worker`),Z.terminate()}}}function hZ(V){if("store"in V)return V.store;return}async function cZ(V,$,Q){let Z=new _0(V,$,Q,zV,J0);return{client:Z,mode:"main",dispose:()=>{Z.disconnect()}}}async function uQ(V){if(V!==void 0)return V;if(typeof indexedDB>"u")throw Error(`${m0} IndexedDB is unavailable; pass store explicitly (e.g. new MemoryStore(crypto))`);return kV(J0)}function dZ(V){let[$,Q]=k$();return BV(()=>{async function Z(){let I=await V.clientState.get();Q(I)}let J=V.clientState.listen(Z);return Z(),()=>{J()}},[V]),$}function oZ(V){let[$,Q]=k$();return BV(()=>{async function Z(){let I=await V.xferState.get();Q(I)}let J=V.xferState.listen(Z);return Z(),()=>{J()}},[V]),$}function aZ(V){BV(()=>{async function $(){try{await V.connect(),await V.sync()}catch(I){console.error("reconnectAndSync failed",I)}}function Q(){$()}function Z(){if(typeof document<"u"&&document.visibilityState==="visible")$()}function J(){$()}if(globalThis.addEventListener("online",Q),typeof document<"u")document.addEventListener("visibilitychange",Z);return globalThis.addEventListener("focus",J),globalThis.addEventListener("pageshow",J),()=>{if(globalThis.removeEventListener("online",Q),typeof document<"u")document.removeEventListener("visibilitychange",Z);globalThis.removeEventListener("focus",J),globalThis.removeEventListener("pageshow",J)}},[V])}function sZ(V={}){let $=V.clock??new M0,{seed:Q,host:Z,readyTimeoutMs:J}=V,I=V.worker,W="store"in V?V.store:void 0,[Y,X]=k$({stateMgr:O$});return BV(()=>{let G=!1,K;return(async()=>{let R=await T$();if(G)return;let z=q$(R),M=I!==void 0?await fV({state:z,clock:$,worker:I,readyTimeoutMs:J}):await fV({state:z,clock:$,store:W,readyTimeoutMs:J});if(G){M.dispose();return}K=M.dispose;let{client:U,mode:N}=M;if(Q)await U.setSeed(Q);if(Z)await U.link(Z);if(G){K();return}X({client:U,entDB:R,stateMgr:z,mode:N,error:void 0})})().catch((R)=>{let z=R instanceof Error?R:Error(String(R));if(console.error("[DIPLOMATIC] useClient init failed",z),!G)X((M)=>({...M,client:void 0,error:z}))}),()=>{G=!0,K?.()}},[$,Q,Z,I,W,J]),Y}import{use as tZ,useEffect as nQ,useRef as eZ,useState as VJ}from"react";function yQ(V,$,Q){let[Z,J]=VJ();return nQ(()=>{async function I(){let W=await Q();J(W)}return I(),V.on($,I),()=>{V.off($,I)}},[V,$,Q]),Z}function $J(V,$,Q){let Z=eZ(Q());return nQ(()=>{async function J(){Z.current=Q()}return V.on($,J),()=>{V.off($,J)}},[V,$,Q]),tZ(Z.current)}function bQ(V,$){return`${V}:${$}`}class x${queue=new Map;async enq(V){for(let $ of V){let Q=bQ($.host,$.seq);this.queue.set(Q,$)}}async deq(V,$){for(let Q of $){let Z=bQ(V,Q);this.queue.delete(Z)}}async list(){let V=[];for(let $ of this.queue.values())V.push($);return V}async count(){return this.queue.size}async wipe(){this.queue.clear()}}class f${hosts=new Map;async add(V){let $={...V,lastSeq:0};this.hosts.set(V.label,$)}async touch(V,$){let Q=this.hosts.get(V);if(!Q||$<=Q.lastSeq)return;this.hosts.set(V,{...Q,lastSeq:$})}async get(V){return this.hosts.get(V)}async set(V,$){let Q=this.hosts.get(V);if(!Q)return 13;return this.hosts.set(V,{...Q,...$}),0}async del(V){this.hosts.delete(V)}async list(){return this.hosts.values()}async wipe(){this.hosts.clear()}}class B${crypto;messages=new Map;constructor(V){this.crypto=V}async add(V){let $=[];for(let{key:Q,data:Z}of V)this.messages.set(g(Q),Z),$.push(0);return $}async del(V){for(let $ of V)this.messages.delete(g($))}async get(V){let $=this.messages.get(g(V));if($)return await w0(V,$,this.crypto);return}async has(V){return this.messages.has(g(V))}async list(){let V=Array.from(this.messages.entries());return await Promise.all(V.map(([Q,Z])=>{let J=Z0(Q);return w0(J,Z,this.crypto)}))}async last(V){let $;for(let[Q,Z]of this.messages){if(X0(V,Z.eid)===!1)continue;let J=Z0(Q);if($===void 0)$={hash:J,data:Z};else if((Z.ctr??0)>($.data.ctr??0)||(Z.ctr??0)===($.data.ctr??0)&&(Z.off??0)>($.data.off??0))$={hash:J,data:Z}}if($)return await w0($.hash,$.data,this.crypto);return}async listUnapplied(){let V=[];for(let[$,Q]of this.messages){if(!L$(Q))continue;let Z=Z0($);V.push(await w0(Z,Q,this.crypto))}return V}async markApplied(V){for(let $ of V){let Q=g($),Z=this.messages.get(Q);if(!Z)continue;this.messages.set(Q,{...S0(Z),apld:!0})}}async wipe(){this.messages.clear()}}class g${enclave;async save(V){return this.enclave=new c0(V,J0),this.enclave}async load(){return this.enclave}async wipe(){this.enclave=void 0}}class i${queue=new Map;async enq(V,$){let Q=this.queue.get(V)||new Set;this.queue.set(V,Q);for(let Z of $)Q.add(o(Z))}async deq(V,$){let Q=this.queue.get(V);if(Q)for(let Z of $)Q.delete(o(Z))}async list(V){let $=this.queue.get(V);if(!$)return[];let Q=[];for(let Z of $)Q.push(A0(Z));return Q}async count(){let V=0;for(let $ of this.queue.values())V+=$.size;return V}async wipe(){this.queue.clear()}}class pQ{seed=new g$;hosts=new f$;uploads=new i$;downloads=new x$;messages;constructor(V){this.messages=new B$(V)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}class lQ{singletonType;latest;latestOff=-1;emitter=new P0;constructor(V){this.singletonType=V}async apply(V){for(let $ of V){let Q=new f($.eid),[Z,J]=Q.readStruct(Q0);if(J!==0)continue;let I=new k;I.writeVarString(this.singletonType);let W=I.result();if(Z.id.length===W.length&&Z.id.every((Y,X)=>Y===W[X])){if(this.latest===void 0||$.off>this.latestOff)this.latestOff=$.off,this.latest=$.bod,this.emitter.emit(this.singletonType,null)}}return V.map(()=>0)}clear=async()=>{return this.latest=void 0,this.latestOff=-1,this.emitter.emit(this.singletonType,null),0};notify=(V)=>{for(let $ of V)if($===this.singletonType)this.emitter.emit(this.singletonType,null)};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}async function vR(V,$){let Q=await kV(J0),Z=new _0(new M0,V,Q,zV,J0);return{client:Z,setSeed:async(I)=>{let W=A0(I);await Q.seed.save(W),await Q.hosts.add({handle:$,label:"host",idx:0}),await Z.connect()}}}export{aZ as useSyncOnResume,$J as useStateWatcherSuspense,yQ as useStateWatcher,oZ as useClientXferState,dZ as useClientState,sZ as useClient,y0 as shouldEmitItemProgress,kV as openIDBStore,T$ as openEntIDB,fV as openDiplomaticClient,O$ as nullStateManager,yZ as nullEntDB,S0 as normalizeStoredMessageData,L$ as isPendingApply,n0 as idleProgress,A0 as htob,zV as hostHTTPTransport,vR as genWebClient,FZ as genSingletonEID,q$ as entStateManager,Q0 as eidCodec,VV as defaultPeekProgressEvery,J0 as crypto,o as btoh,JV as WorkerClient,P0 as TypedEventEmitter,_0 as SyncClient,_ as Status,jV as StateManager,lQ as SingletonStateManager,pQ as MemoryStore,E$ as IDBStore,aV as HTTPTransport,D$ as EntIDB,fQ as EntDBMemory,k as Encoder,f as Decoder,M0 as Clock};
|
|
1
|
+
function v$(V){let $=V.length,Q=0,Z=0;while(Z<$){let J=V.charCodeAt(Z++);if((J&4294967168)===0){Q++;continue}else if((J&4294965248)===0)Q+=2;else{if(J>=55296&&J<=56319){if(Z<$){let I=V.charCodeAt(Z);if((I&64512)===56320)++Z,J=((J&1023)<<10)+(I&1023)+65536}}if((J&4294901760)===0)Q+=3;else Q+=4}}return Q}function hQ(V,$,Q){let Z=V.length,J=Q,I=0;while(I<Z){let W=V.charCodeAt(I++);if((W&4294967168)===0){$[J++]=W;continue}else if((W&4294965248)===0)$[J++]=W>>6&31|192;else{if(W>=55296&&W<=56319){if(I<Z){let Y=V.charCodeAt(I);if((Y&64512)===56320)++I,W=((W&1023)<<10)+(Y&1023)+65536}}if((W&4294901760)===0)$[J++]=W>>12&15|224,$[J++]=W>>6&63|128;else $[J++]=W>>18&7|240,$[J++]=W>>12&63|128,$[J++]=W>>6&63|128}$[J++]=W&63|128}}var cQ=new TextEncoder,dQ=50;function oQ(V,$,Q){cQ.encodeInto(V,$.subarray(Q))}function u$(V,$,Q){if(V.length>dQ)oQ(V,$,Q);else hQ(V,$,Q)}var aQ=4096;function BV(V,$,Q){let Z=$,J=Z+Q,I=[],W="";while(Z<J){let Y=V[Z++];if((Y&128)===0)I.push(Y);else if((Y&224)===192){let X=V[Z++]&63;I.push((Y&31)<<6|X)}else if((Y&240)===224){let X=V[Z++]&63,G=V[Z++]&63;I.push((Y&31)<<12|X<<6|G)}else if((Y&248)===240){let X=V[Z++]&63,G=V[Z++]&63,K=V[Z++]&63,R=(Y&7)<<18|X<<12|G<<6|K;if(R>65535)R-=65536,I.push(R>>>10&1023|55296),R=56320|R&1023;I.push(R)}else I.push(Y);if(I.length>=aQ)W+=String.fromCharCode(...I),I.length=0}if(I.length>0)W+=String.fromCharCode(...I);return W}var sQ=new TextDecoder,tQ=200;function eQ(V,$,Q){let Z=V.subarray($,$+Q);return sQ.decode(Z)}function n$(V,$,Q){if(Q>tQ)return eQ(V,$,Q);else return BV(V,$,Q)}class g0{type;data;constructor(V,$){this.type=V,this.data=$}}class s extends Error{constructor(V){super(V);let $=Object.create(s.prototype);Object.setPrototypeOf(this,$),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:s.name})}}var i0=4294967295;function y$(V,$,Q){let Z=Q/4294967296,J=Q;V.setUint32($,Z),V.setUint32($+4,J)}function JV(V,$,Q){let Z=Math.floor(Q/4294967296),J=Q;V.setUint32($,Z),V.setUint32($+4,J)}function IV(V,$){let Q=V.getInt32($),Z=V.getUint32($+4);return Q*4294967296+Z}function b$(V,$){let Q=V.getUint32($),Z=V.getUint32($+4);return Q*4294967296+Z}var VZ=-1,$Z=4294967295,QZ=17179869183;function ZZ({sec:V,nsec:$}){if(V>=0&&$>=0&&V<=QZ)if($===0&&V<=$Z){let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,V),Q}else{let Q=V/4294967296,Z=V&4294967295,J=new Uint8Array(8),I=new DataView(J.buffer);return I.setUint32(0,$<<2|Q&3),I.setUint32(4,Z),J}else{let Q=new Uint8Array(12),Z=new DataView(Q.buffer);return Z.setUint32(0,$),JV(Z,4,V),Q}}function JZ(V){let $=V.getTime(),Q=Math.floor($/1000),Z=($-Q*1000)*1e6,J=Math.floor(Z/1e9);return{sec:Q+J,nsec:Z-J*1e9}}function IZ(V){if(V instanceof Date){let $=JZ(V);return ZZ($)}else return null}function WZ(V){let $=new DataView(V.buffer,V.byteOffset,V.byteLength);switch(V.byteLength){case 4:{let Q=$.getUint32(0),Z=0;return{sec:Q,nsec:0}}case 8:{let Q=$.getUint32(0),Z=$.getUint32(4),J=(Q&3)*4294967296+Z,I=Q>>>2;return{sec:J,nsec:I}}case 12:{let Q=IV($,4),Z=$.getUint32(0);return{sec:Q,nsec:Z}}default:throw new s(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${V.length}`)}}function YZ(V){let $=WZ(V);return new Date($.sec*1000+$.nsec/1e6)}var p$={type:VZ,encode:IZ,decode:YZ};class v0{static defaultCodec=new v0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(p$)}register({type:V,encode:$,decode:Q}){if(V>=0)this.encoders[V]=$,this.decoders[V]=Q;else{let Z=-1-V;this.builtInEncoders[Z]=$,this.builtInDecoders[Z]=Q}}tryToEncode(V,$){for(let Q=0;Q<this.builtInEncoders.length;Q++){let Z=this.builtInEncoders[Q];if(Z!=null){let J=Z(V,$);if(J!=null){let I=-1-Q;return new g0(I,J)}}}for(let Q=0;Q<this.encoders.length;Q++){let Z=this.encoders[Q];if(Z!=null){let J=Z(V,$);if(J!=null)return new g0(Q,J)}}if(V instanceof g0)return V;return null}decode(V,$,Q){let Z=$<0?this.builtInDecoders[-1-$]:this.decoders[$];if(Z)return Z(V,$,Q);else return new g0($,V)}}function XZ(V){return V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer}function c0(V){if(V instanceof Uint8Array)return V;else if(ArrayBuffer.isView(V))return new Uint8Array(V.buffer,V.byteOffset,V.byteLength);else if(XZ(V))return new Uint8Array(V);else return Uint8Array.from(V)}var GZ=100,KZ=2048;class WV{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??v0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.maxDepth=V?.maxDepth??GZ,this.initialBufferSize=V?.initialBufferSize??KZ,this.sortKeys=V?.sortKeys??!1,this.forceFloat32=V?.forceFloat32??!1,this.ignoreUndefined=V?.ignoreUndefined??!1,this.forceIntegerToFloat=V?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new WV({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(V){if(this.entered)return this.clone().encodeSharedRef(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(V){if(this.entered)return this.clone().encode(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(V,$){if($>this.maxDepth)throw Error(`Too deep objects in depth ${$}`);if(V==null)this.encodeNil();else if(typeof V==="boolean")this.encodeBoolean(V);else if(typeof V==="number")if(!this.forceIntegerToFloat)this.encodeNumber(V);else this.encodeNumberAsFloat(V);else if(typeof V==="string")this.encodeString(V);else if(this.useBigInt64&&typeof V==="bigint")this.encodeBigInt64(V);else this.encodeObject(V,$)}ensureBufferSizeToWrite(V){let $=this.pos+V;if(this.view.byteLength<$)this.resizeBuffer($*2)}resizeBuffer(V){let $=new ArrayBuffer(V),Q=new Uint8Array($),Z=new DataView($);Q.set(this.bytes),this.view=Z,this.bytes=Q}encodeNil(){this.writeU8(192)}encodeBoolean(V){if(V===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber(V){if(!this.forceIntegerToFloat&&Number.isSafeInteger(V))if(V>=0)if(V<128)this.writeU8(V);else if(V<256)this.writeU8(204),this.writeU8(V);else if(V<65536)this.writeU8(205),this.writeU16(V);else if(V<4294967296)this.writeU8(206),this.writeU32(V);else if(!this.useBigInt64)this.writeU8(207),this.writeU64(V);else this.encodeNumberAsFloat(V);else if(V>=-32)this.writeU8(224|V+32);else if(V>=-128)this.writeU8(208),this.writeI8(V);else if(V>=-32768)this.writeU8(209),this.writeI16(V);else if(V>=-2147483648)this.writeU8(210),this.writeI32(V);else if(!this.useBigInt64)this.writeU8(211),this.writeI64(V);else this.encodeNumberAsFloat(V);else this.encodeNumberAsFloat(V)}encodeNumberAsFloat(V){if(this.forceFloat32)this.writeU8(202),this.writeF32(V);else this.writeU8(203),this.writeF64(V)}encodeBigInt64(V){if(V>=BigInt(0))this.writeU8(207),this.writeBigUint64(V);else this.writeU8(211),this.writeBigInt64(V)}writeStringHeader(V){if(V<32)this.writeU8(160+V);else if(V<256)this.writeU8(217),this.writeU8(V);else if(V<65536)this.writeU8(218),this.writeU16(V);else if(V<4294967296)this.writeU8(219),this.writeU32(V);else throw Error(`Too long string: ${V} bytes in UTF-8`)}encodeString(V){let Q=v$(V);this.ensureBufferSizeToWrite(5+Q),this.writeStringHeader(Q),u$(V,this.bytes,this.pos),this.pos+=Q}encodeObject(V,$){let Q=this.extensionCodec.tryToEncode(V,this.context);if(Q!=null)this.encodeExtension(Q);else if(Array.isArray(V))this.encodeArray(V,$);else if(ArrayBuffer.isView(V))this.encodeBinary(V);else if(typeof V==="object")this.encodeMap(V,$);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply(V)}`)}encodeBinary(V){let $=V.byteLength;if($<256)this.writeU8(196),this.writeU8($);else if($<65536)this.writeU8(197),this.writeU16($);else if($<4294967296)this.writeU8(198),this.writeU32($);else throw Error(`Too large binary: ${$}`);let Q=c0(V);this.writeU8a(Q)}encodeArray(V,$){let Q=V.length;if(Q<16)this.writeU8(144+Q);else if(Q<65536)this.writeU8(220),this.writeU16(Q);else if(Q<4294967296)this.writeU8(221),this.writeU32(Q);else throw Error(`Too large array: ${Q}`);for(let Z of V)this.doEncode(Z,$+1)}countWithoutUndefined(V,$){let Q=0;for(let Z of $)if(V[Z]!==void 0)Q++;return Q}encodeMap(V,$){let Q=Object.keys(V);if(this.sortKeys)Q.sort();let Z=this.ignoreUndefined?this.countWithoutUndefined(V,Q):Q.length;if(Z<16)this.writeU8(128+Z);else if(Z<65536)this.writeU8(222),this.writeU16(Z);else if(Z<4294967296)this.writeU8(223),this.writeU32(Z);else throw Error(`Too large map object: ${Z}`);for(let J of Q){let I=V[J];if(!(this.ignoreUndefined&&I===void 0))this.encodeString(J),this.doEncode(I,$+1)}}encodeExtension(V){if(typeof V.data==="function"){let Q=V.data(this.pos+6),Z=Q.length;if(Z>=4294967296)throw Error(`Too large extension object: ${Z}`);this.writeU8(201),this.writeU32(Z),this.writeI8(V.type),this.writeU8a(Q);return}let $=V.data.length;if($===1)this.writeU8(212);else if($===2)this.writeU8(213);else if($===4)this.writeU8(214);else if($===8)this.writeU8(215);else if($===16)this.writeU8(216);else if($<256)this.writeU8(199),this.writeU8($);else if($<65536)this.writeU8(200),this.writeU16($);else if($<4294967296)this.writeU8(201),this.writeU32($);else throw Error(`Too large extension object: ${$}`);this.writeI8(V.type),this.writeU8a(V.data)}writeU8(V){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,V),this.pos++}writeU8a(V){let $=V.length;this.ensureBufferSizeToWrite($),this.bytes.set(V,this.pos),this.pos+=$}writeI8(V){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,V),this.pos++}writeU16(V){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,V),this.pos+=2}writeI16(V){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,V),this.pos+=2}writeU32(V){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,V),this.pos+=4}writeI32(V){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,V),this.pos+=4}writeF32(V){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,V),this.pos+=4}writeF64(V){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,V),this.pos+=8}writeU64(V){this.ensureBufferSizeToWrite(8),y$(this.view,this.pos,V),this.pos+=8}writeI64(V){this.ensureBufferSizeToWrite(8),JV(this.view,this.pos,V),this.pos+=8}writeBigUint64(V){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,V),this.pos+=8}writeBigInt64(V){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,V),this.pos+=8}}function YV(V,$){return new WV($).encodeSharedRef(V)}function XV(V){return`${V<0?"-":""}0x${Math.abs(V).toString(16).padStart(2,"0")}`}var wZ=16,RZ=16;class gV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(V=wZ,$=RZ){this.maxKeyLength=V,this.maxLengthPerKey=$,this.caches=[];for(let Q=0;Q<this.maxKeyLength;Q++)this.caches.push([])}canBeCached(V){return V>0&&V<=this.maxKeyLength}find(V,$,Q){let Z=this.caches[Q-1];V:for(let J of Z){let I=J.bytes;for(let W=0;W<Q;W++)if(I[W]!==V[$+W])continue V;return J.str}return null}store(V,$){let Q=this.caches[V.length-1],Z={bytes:V,str:$};if(Q.length>=this.maxLengthPerKey)Q[Math.random()*Q.length|0]=Z;else Q.push(Z)}decode(V,$,Q){let Z=this.find(V,$,Q);if(Z!=null)return this.hit++,Z;this.miss++;let J=BV(V,$,Q),I=Uint8Array.prototype.slice.call(V,$,$+Q);return this.store(I,J),J}}var iV="array",o0="map_key",l$="map_value",MZ=(V)=>{if(typeof V==="string"||typeof V==="number")return V;throw new s("The type of key must be string or number but "+typeof V)};class h${stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(V){let $=this.getUninitializedStateFromPool();$.type=iV,$.position=0,$.size=V,$.array=Array(V)}pushMapState(V){let $=this.getUninitializedStateFromPool();$.type=o0,$.readCount=0,$.size=V,$.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let V={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(V)}return this.stack[this.stackHeadPosition]}release(V){if(this.stack[this.stackHeadPosition]!==V)throw Error("Invalid stack state. Released state is not on top of the stack.");if(V.type===iV){let Q=V;Q.size=0,Q.array=void 0,Q.position=0,Q.type=void 0}if(V.type===o0||V.type===l$){let Q=V;Q.size=0,Q.map=void 0,Q.readCount=0,Q.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var d0=-1,vV=new DataView(new ArrayBuffer(0)),NZ=new Uint8Array(vV.buffer);try{vV.getInt8(0)}catch(V){if(!(V instanceof RangeError))throw Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var r$=RangeError("Insufficient data"),zZ=new gV;class GV{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=vV;bytes=NZ;headByte=d0;stack=new h$;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??v0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.rawStrings=V?.rawStrings??!1,this.maxStrLength=V?.maxStrLength??i0,this.maxBinLength=V?.maxBinLength??i0,this.maxArrayLength=V?.maxArrayLength??i0,this.maxMapLength=V?.maxMapLength??i0,this.maxExtLength=V?.maxExtLength??i0,this.keyDecoder=V?.keyDecoder!==void 0?V.keyDecoder:zZ,this.mapKeyConverter=V?.mapKeyConverter??MZ}clone(){return new GV({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=d0,this.stack.reset()}setBuffer(V){let $=c0(V);this.bytes=$,this.view=new DataView($.buffer,$.byteOffset,$.byteLength),this.pos=0}appendBuffer(V){if(this.headByte===d0&&!this.hasRemaining(1))this.setBuffer(V);else{let $=this.bytes.subarray(this.pos),Q=c0(V),Z=new Uint8Array($.length+Q.length);Z.set($),Z.set(Q,$.length),this.setBuffer(Z)}}hasRemaining(V){return this.view.byteLength-this.pos>=V}createExtraByteError(V){let{view:$,pos:Q}=this;return RangeError(`Extra ${$.byteLength-Q} of ${$.byteLength} byte(s) found at buffer[${V}]`)}decode(V){if(this.entered)return this.clone().decode(V);try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);let $=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return $}finally{this.entered=!1}}*decodeMulti(V){if(this.entered){yield*this.clone().decodeMulti(V);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(V){if(this.entered)return this.clone().decodeAsync(V);try{this.entered=!0;let $=!1,Q;for await(let W of V){if($)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(W);try{Q=this.doDecodeSync(),$=!0}catch(Y){if(!(Y instanceof RangeError))throw Y}this.totalPos+=this.pos}if($){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Q}let{headByte:Z,pos:J,totalPos:I}=this;throw RangeError(`Insufficient data in parsing ${XV(Z)} at ${I} (${J} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(V){return this.decodeMultiAsync(V,!0)}decodeStream(V){return this.decodeMultiAsync(V,!1)}async*decodeMultiAsync(V,$){if(this.entered){yield*this.clone().decodeMultiAsync(V,$);return}try{this.entered=!0;let Q=$,Z=-1;for await(let J of V){if($&&Z===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(J),Q)Z=this.readArraySize(),Q=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--Z===0)break}catch(I){if(!(I instanceof RangeError))throw I}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){V:while(!0){let V=this.readHeadByte(),$;if(V>=224)$=V-256;else if(V<192)if(V<128)$=V;else if(V<144){let Z=V-128;if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V<160){let Z=V-144;if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else{let Z=V-160;$=this.decodeString(Z,0)}else if(V===192)$=null;else if(V===194)$=!1;else if(V===195)$=!0;else if(V===202)$=this.readF32();else if(V===203)$=this.readF64();else if(V===204)$=this.readU8();else if(V===205)$=this.readU16();else if(V===206)$=this.readU32();else if(V===207)if(this.useBigInt64)$=this.readU64AsBigInt();else $=this.readU64();else if(V===208)$=this.readI8();else if(V===209)$=this.readI16();else if(V===210)$=this.readI32();else if(V===211)if(this.useBigInt64)$=this.readI64AsBigInt();else $=this.readI64();else if(V===217){let Z=this.lookU8();$=this.decodeString(Z,1)}else if(V===218){let Z=this.lookU16();$=this.decodeString(Z,2)}else if(V===219){let Z=this.lookU32();$=this.decodeString(Z,4)}else if(V===220){let Z=this.readU16();if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else if(V===221){let Z=this.readU32();if(Z!==0){this.pushArrayState(Z),this.complete();continue V}else $=[]}else if(V===222){let Z=this.readU16();if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V===223){let Z=this.readU32();if(Z!==0){this.pushMapState(Z),this.complete();continue V}else $={}}else if(V===196){let Z=this.lookU8();$=this.decodeBinary(Z,1)}else if(V===197){let Z=this.lookU16();$=this.decodeBinary(Z,2)}else if(V===198){let Z=this.lookU32();$=this.decodeBinary(Z,4)}else if(V===212)$=this.decodeExtension(1,0);else if(V===213)$=this.decodeExtension(2,0);else if(V===214)$=this.decodeExtension(4,0);else if(V===215)$=this.decodeExtension(8,0);else if(V===216)$=this.decodeExtension(16,0);else if(V===199){let Z=this.lookU8();$=this.decodeExtension(Z,1)}else if(V===200){let Z=this.lookU16();$=this.decodeExtension(Z,2)}else if(V===201){let Z=this.lookU32();$=this.decodeExtension(Z,4)}else throw new s(`Unrecognized type byte: ${XV(V)}`);this.complete();let Q=this.stack;while(Q.length>0){let Z=Q.top();if(Z.type===iV)if(Z.array[Z.position]=$,Z.position++,Z.position===Z.size)$=Z.array,Q.release(Z);else continue V;else if(Z.type===o0){if($==="__proto__")throw new s("The key __proto__ is not allowed");Z.key=this.mapKeyConverter($),Z.type=l$;continue V}else if(Z.map[Z.key]=$,Z.readCount++,Z.readCount===Z.size)$=Z.map,Q.release(Z);else{Z.key=null,Z.type=o0;continue V}}return $}}readHeadByte(){if(this.headByte===d0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=d0}readArraySize(){let V=this.readHeadByte();switch(V){case 220:return this.readU16();case 221:return this.readU32();default:if(V<160)return V-144;else throw new s(`Unrecognized array type byte: ${XV(V)}`)}}pushMapState(V){if(V>this.maxMapLength)throw new s(`Max length exceeded: map length (${V}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(V)}pushArrayState(V){if(V>this.maxArrayLength)throw new s(`Max length exceeded: array length (${V}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(V)}decodeString(V,$){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String(V,$);return this.decodeBinary(V,$)}decodeUtf8String(V,$){if(V>this.maxStrLength)throw new s(`Max length exceeded: UTF-8 byte length (${V}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+$+V)throw r$;let Q=this.pos+$,Z;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached(V))Z=this.keyDecoder.decode(this.bytes,Q,V);else Z=n$(this.bytes,Q,V);return this.pos+=$+V,Z}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===o0;return!1}decodeBinary(V,$){if(V>this.maxBinLength)throw new s(`Max length exceeded: bin length (${V}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(V+$))throw r$;let Q=this.pos+$,Z=this.bytes.subarray(Q,Q+V);return this.pos+=$+V,Z}decodeExtension(V,$){if(V>this.maxExtLength)throw new s(`Max length exceeded: ext length (${V}) > maxExtLength (${this.maxExtLength})`);let Q=this.view.getInt8(this.pos+$),Z=this.decodeBinary(V,$+1);return this.extensionCodec.decode(Z,Q,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let V=this.view.getUint8(this.pos);return this.pos++,V}readI8(){let V=this.view.getInt8(this.pos);return this.pos++,V}readU16(){let V=this.view.getUint16(this.pos);return this.pos+=2,V}readI16(){let V=this.view.getInt16(this.pos);return this.pos+=2,V}readU32(){let V=this.view.getUint32(this.pos);return this.pos+=4,V}readI32(){let V=this.view.getInt32(this.pos);return this.pos+=4,V}readU64(){let V=b$(this.view,this.pos);return this.pos+=8,V}readI64(){let V=IV(this.view,this.pos);return this.pos+=8,V}readU64AsBigInt(){let V=this.view.getBigUint64(this.pos);return this.pos+=8,V}readI64AsBigInt(){let V=this.view.getBigInt64(this.pos);return this.pos+=8,V}readF32(){let V=this.view.getFloat32(this.pos);return this.pos+=4,V}readF64(){let V=this.view.getFloat64(this.pos);return this.pos+=8,V}}function uV(V,$){return new GV($).decode(V)}class P0{listeners=new Map;addEventListener(V,$){let Q=this.listeners.get(V);if(!Q)Q=new Set,this.listeners.set(V,Q);return Q.add($),()=>{this.removeEventListener(V,$)}}removeEventListener(V,$){let Q=this.listeners.get(V);if(Q){if(Q.delete($),Q.size===0)this.listeners.delete(V)}}emit(V,$){let Q=this.listeners.get(V);if(Q){let Z=Array.from(Q);for(let J of Z)J($)}}emitAll(V){let $=Array.from(this.listeners.keys());for(let Q of $)this.emit(Q,V)}}class G0{getter;static eventName="update";emitter;constructor(V){this.getter=V;this.emitter=new P0}get=()=>this.getter();async emit(){let V=await this.getter();queueMicrotask(()=>this.emitter.emit(G0.eventName,V))}listen(V){return this.emitter.addEventListener(G0.eventName,V),()=>{this.emitter.removeEventListener(G0.eventName,V)}}}var C0=64;var c$=32,D0=8;var KV=32;var d$=30000,o$=512,_;((C)=>{C[C.Success=0]="Success";C[C.InvalidSignature=3]="InvalidSignature";C[C.ClockOutOfSync=4]="ClockOutOfSync";C[C.UserNotRegistered=5]="UserNotRegistered";C[C.ServerMisconfigured=6]="ServerMisconfigured";C[C.MissingBody=7]="MissingBody";C[C.ExtraBodyContent=8]="ExtraBodyContent";C[C.MissingParam=9]="MissingParam";C[C.InvalidParam=10]="InvalidParam";C[C.InvalidRequest=11]="InvalidRequest";C[C.InternalError=12]="InternalError";C[C.NotFound=13]="NotFound";C[C.InvalidMessage=14]="InvalidMessage";C[C.NoChange=15]="NoChange";C[C.DatabaseClosed=16]="DatabaseClosed";C[C.StorageError=17]="StorageError";C[C.DatabaseError=18]="DatabaseError";C[C.HashMismatch=19]="HashMismatch";C[C.DecryptionError=20]="DecryptionError";C[C.NotImplemented=21]="NotImplemented";C[C.MissingSeed=22]="MissingSeed";C[C.OutOfBounds=23]="OutOfBounds";C[C.HostError=24]="HostError";C[C.CommunicationError=25]="CommunicationError";C[C.VarLimitExceeded=26]="VarLimitExceeded";C[C.InvalidResponse=27]="InvalidResponse";C[C.ConnectionClosed=28]="ConnectionClosed"})(_||={});function O(V){return[V,0]}function w(V){return[void 0,V]}function UZ(V){if(V<0)console.info("N",V),console.trace();if(typeof V!=="bigint")V=BigInt(V);if(V<0n)return w(10);let $=[];while(V>0n){let Q=Number(V&0x7fn);if(V>>=7n,V>0n)$.push(Q|128);else $.push(Q)}if($.length===0)return O(new Uint8Array([0]));if($.length>8)return w(26);return O(new Uint8Array($))}function FZ(V,$=0){let Q=0n,Z=0,J=$;while(!0){if(J>=V.length)return w(14);let I=V[J++];if(I===void 0)return w(14);if(Q|=BigInt(I&127)<<BigInt(Z),(I&128)===0){if(J-$>8)return w(26);return O({value:Q>0x1fffffffffffffn?Q:Number(Q),bytesRead:J-$})}if(Z+=7,Z>=56)return w(26)}}class f{data;pos=0;constructor(V){this.data=V}static async fromResponse(V){let $=await V.arrayBuffer(),Q=new Uint8Array($);return new f(Q)}readBigInt(){if(this.pos+8>this.data.length)return w(7);let V=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,O(V)}readDate(){let[V,$]=this.readVarInt();if($!==0)return w($);return O(new Date(V))}readVarInt(){let[V,$]=FZ(this.data,this.pos);if($!==0)return w($);this.pos+=V.bytesRead;let Q=V.value;return O(typeof Q==="bigint"?Number(Q):Q)}readVarString(){let[V,$]=this.readVarInt();if($!==0)return w($);let[Q,Z]=this.readBytes(V);if(Z!==0)return w(Z);let J=new TextDecoder().decode(Q);return O(J)}readBytes(V){if(V<0)return w(10);if(this.pos+V>this.data.length)return w(23);let $=this.data.slice(this.pos,this.pos+V);return this.pos+=V,O($)}readVarBytes(){let[V,$]=this.readVarInt();if($!==0)return w($);return this.readBytes(V)}readStruct(V){return V.decode(this)}readStructs(V){let $=[];while(!this.done()){let[Q,Z]=this.readStruct(V);if(Z!==0)return w(Z);$.push(Q)}return O($)}readBytesSeq(V){let $=[];while(!this.done()){let[Q,Z]=this.readBytes(V);if(Z!==0)return w(Z);$.push(Q)}return O($)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class x{parts=[];writeBigInt(V){let $=new Uint8Array(8);new DataView($.buffer).setBigUint64(0,V,!1),this.parts.push($)}writeDate(V){let $=V.getTime();return this.writeVarInt($)}writeVarInt(V){let[$,Q]=UZ(V);if(Q!==0)return Q;return this.parts.push($),0}writeVarString(V){let $=new TextEncoder().encode(V),Q=this.writeVarInt($.length);if(Q!==0)return Q;return this.writeBytes($),0}prependBytes(V){this.parts.unshift(V)}writeBytes(V){this.parts.push(V)}writeVarBytes(V){let $=this.writeVarInt(V.length);if($!==0)return $;return this.writeBytes(V),0}writeStruct(V,$){return V.encode(this,$)}writeStructs(V,$){for(let Q of $){let Z=this.writeStruct(V,Q);if(Z!==0)return Z}return 0}writeBytesSeq(V){for(let $ of V)this.writeBytes($)}result(){let V=this.parts.reduce((Z,J)=>Z+J.length,0),$=new Uint8Array(V),Q=0;for(let Z of this.parts)$.set(Z,Q),Q+=Z.length;return $}*scan(){for(let V of this.parts)yield V}}async function nV(V,$,Q){let Z=new x,J=Z.writeDate($);if(J!==0)return w(J);let I=Z.result(),W=await Q.signEd25519(I,V.privateKey);return O({pubKey:V.publicKey,sig:W,timestamp:$})}async function T0(V,$,Q){let Z=Q.now().getTime(),J=V.timestamp.getTime();if(Math.abs(Z-J)>d$)return 4;let W=new x;W.writeDate(V.timestamp);let Y=W.result();if(!await $.checkSigEd25519(V.sig,Y,V.pubKey))return 3;return 0}var Q0={encode(V,$){let Q=V.writeVarBytes($.id);if(Q!==0)return Q;let Z=V.writeDate($.ts);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return w(Q);let[Z,J]=V.readDate();if(J!==0)return w(J);return O({id:$,ts:Z})}};function u0(V){let $=new x,Q=$.writeStruct(Q0,V);if(Q!==0)return w(Q);let Z=$.result();return O(Z)}async function OZ(V){return u0({id:V,ts:new Date(0)})}var Y0={encode(V,$){let Q=V.writeVarBytes($.eid);if(Q!==0)return Q;let Z=V.writeVarInt($.off);if(Z!==0)return Z;let J=V.writeVarInt($.ctr);if(J!==0)return J;let I=V.writeVarInt($.len);if(I!==0)return I;if($.hsh)V.writeBytes($.hsh);return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return w(Q);let Z=new f($),[,J]=Q0.decode(Z);if(J!==0)return w(J);let[I,W]=V.readVarInt();if(W!==0)return w(W);let[Y,X]=V.readVarInt();if(X!==0)return w(X);let[G,K]=V.readVarInt();if(K!==0)return w(K);let R;if(G>0){let[N,z]=V.readBytes(KV);if(z!==0)return w(z);R=N}return O({eid:$,off:I,ctr:Y,len:G,hsh:R})}};function o(V){return Array.from(V).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}function A0(V){if(V.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(V.length/2);for(let Q=0;Q<V.length;Q+=2)$[Q/2]=Number.parseInt(V.substr(Q,2),16);return $}function X0(V,$){if(V===$)return!0;if(V.byteLength!==$.byteLength)return!1;return V.every((Q,Z)=>Q===$[Z])}var g;if(typeof Uint8Array.prototype.toBase64==="function")g=(V)=>V.toBase64();else g=(V)=>btoa(String.fromCharCode(...V));var Z0;if(typeof Uint8Array.fromBase64==="function")Z0=(V)=>Uint8Array.fromBase64(V);else Z0=(V)=>Uint8Array.from(atob(V),($)=>$.charCodeAt(0));function a0(V,$){let Q=new Uint8Array(V.length+$.length);return Q.set(V,0),Q.set($,V.length),Q}function a$(V,$,Q){return Q.checkSigEd25519(V.sig,V.headCph,$)}async function yV(V,$,Q){let Z=a0($.privateKey,V);return(await Q.blake3(Z)).slice(0,D0)}async function s$(V,$,Q,Z){let J;if(V.bod&&V.len>0)J=await Q.blake3(V.bod);let I=new x,W=Y0.encode(I,{...V,hsh:J});if(W!==0)return w(W);let Y=I.result(),X=await yV(Y,$,Q),G=await Z.deriveFromKDM(X),K=await Q.encryptXSalsa20Poly1305Combined(Y,G),R=V.bod?await Q.encryptXSalsa20Poly1305Combined(V.bod,G):new Uint8Array(0),N=await Q.signEd25519(K,$.privateKey);return O({sig:N,kdm:X,headCph:K,bodyCph:R})}async function bV(V,$,Q,Z){let J=new f(V),[I,W]=Y0.decode(J);if(W!==0)return w(14);let Y;try{Y=$&&$.length>0?await Z.decryptXSalsa20Poly1305Combined($,Q):void 0}catch{return w(20)}let X=I.hsh&&Y===void 0,G=I.hsh===void 0&&Y!==void 0;if(X||G)return w(19);if(I.hsh&&Y){let R=await Z.blake3(Y);if(!X0(R,I.hsh))return w(19)}let K=await Z.blake3(V);return O({msgHead:I,bod:Y,headHash:K})}class N0{now(){return new Date}}function t$(V,$,Q,Z){let J=$.getTime()-V.getTime(),I=Q.getTime()-Z.getTime();return(J+I)/2}var s0={encode(V,$){if(V.writeVarInt($.quota),$.quota>0){if($.usage===void 0)return 9;V.writeVarInt($.usage)}return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return w(Q);let Z;if($>0){let[J,I]=V.readVarInt();if(I!==0)return w(I);Z=J}return O({quota:$,usage:Z})}};var pV={encode(V,$){V.writeBytes(new Uint8Array([$.status]));let Q=V.writeDate($.timeRcvd);if(Q!==0)return Q;let Z=V.writeDate($.timeSent);if(Z!==0)return Z;let J=V.writeVarInt($.subscription.term);if(J!==0)return J;let I=V.writeVarInt($.subscription.elapsed);if(I!==0)return I;let W=V.writeStruct(s0,$.subscription.stat);if(W!==0)return W;let Y=V.writeStruct(s0,$.subscription.dyn);if(Y!==0)return Y;return 0},decode(V){let[$,Q]=V.readBytes(1);if(Q!==0)return w(Q);let Z=$[0],[J,I]=V.readDate();if(I!==0)return w(I);let[W,Y]=V.readDate();if(Y!==0)return w(Y);let[X,G]=V.readVarInt();if(G!==0)return w(G);let[K,R]=V.readVarInt();if(R!==0)return w(R);let[N,z]=V.readStruct(s0);if(z!==0)return w(z);let[U,M]=V.readStruct(s0);if(M!==0)return w(M);return O({status:Z,timeRcvd:J,timeSent:W,subscription:{term:X,elapsed:K,stat:N,dyn:U}})}};async function rV(V,$,Q){let{crypto:Z,enclave:J}=V,I=await J.derive($,Q);return await Z.deriveEd25519KeyPair(I)}var lV={encode(V,$){let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarInt($.seq);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readVarBytes();if(Q!==0)return w(Q);let[Z,J]=V.readVarInt();if(J!==0)return w(J);return O({headCph:$,seq:Z})}};var $0={encode(V,$){V.writeBytes($.pubKey),V.writeBytes($.sig);let Q=V.writeDate($.timestamp);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readBytes(c$);if(Q!==0)return w(Q);let[Z,J]=V.readBytes(C0);if(J!==0)return w(J);let[I,W]=V.readDate();if(W!==0)return w(W);return O({pubKey:$,sig:Z,timestamp:I})}};var e$={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct($0,Q);if(I!==0)return I;for(let W of Z)J.writeVarInt(W);return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct($0);if(Y!==0)return Y;let X=await T0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W,[K,R]=await I.hasUser(G);if(R!==0)return R;if(!K)return 5;let[N,z]=$.readVarInt();if(z!==0)return z;if(!$.done())return 8;let[U,M]=await I.listHeads(G,N);if(M!==0)return M;return Q.writeStructs(lV,U)},decodeResp(V){return V.readStructs(lV)}};var hV={encode(V,$){V.writeVarInt($.seq);let Q=V.writeVarBytes($.bodyCph);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return w(Q);let[Z,J]=V.readVarBytes();if(J!==0)return w(J);return O({seq:$,bodyCph:Z})}};var VQ={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct($0,Q);if(I!==0)return I;for(let W of Z){let Y=J.writeVarInt(W);if(Y!==0)return Y}return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct($0);if(Y!==0)return Y;let X=await T0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W,[K,R]=await I.hasUser(G);if(R!==0)return R;if(!K)return 5;let N=[];while(!$.done()){let[M,H]=$.readVarInt();if(H!==0)return H;N.push(M)}console.info(`PULL: ${N.length} bags`);let[z,U]=await I.getBodies(G,N);if(U!==0)return U;if(!z)return 17;for(let{seq:M,bodyCph:H}of z){let q={seq:M,bodyCph:H},P=Q.writeStruct(hV,q);if(P!==0)return P}return 0},decodeResp(V){return V.readStructs(hV)}};var cV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarBytes($.bodyCph);if(Z!==0)return Z;return 0},decode(V){let[$,Q]=V.readBytes(C0);if(Q!==0)return w(Q);let[Z,J]=V.readBytes(D0);if(J!==0)return w(J);let[I,W]=V.readVarBytes();if(W!==0)return w(W);let[Y,X]=V.readVarBytes();if(X!==0)return w(X);return O({sig:$,kdm:Z,headCph:I,bodyCph:Y})}};var wV={encode(V,$){let Q=V.writeVarInt($.seq);if(Q!==0)return Q;let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=$.bodyCph?$.bodyCph.length:0,I=V.writeVarInt(J);if(I!==0)return I;if(J>0){if(!$.bodyCph)return 10;V.writeBytes($.bodyCph)}return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return w(Q);let[Z,J]=V.readVarBytes();if(J!==0)return w(J);let[I,W]=V.readVarInt();if(W!==0)return w(W);let Y;if(I>0){let[X,G]=V.readBytes(I);if(G!==0)return w(G);Y=X}return O({seq:$,headCph:Z,bodyCph:Y})}};var RV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;return 0},decode(V){let[$,Q]=V.readBytes(C0);if(Q!==0)return w(Q);let[Z,J]=V.readBytes(D0);if(J!==0)return w(J);let[I,W]=V.readVarBytes();if(W!==0)return w(W);return O({sig:$,kdm:Z,headCph:I})}};var MV={encode(V,$){if(V.writeVarInt($.idx),V.writeBytes(new Uint8Array([$.status])),$.status===0)V.writeVarInt($.seq);return 0},decode(V){let[$,Q]=V.readVarInt();if(Q!==0)return w(Q);let[Z,J]=V.readBytes(1);if(J!==0)return w(J);let I=Z[0];if(I!==0)return O({idx:$,status:I});let[W,Y]=V.readVarInt();if(Y!==0)return w(Y);return O({idx:$,status:I,seq:W})}};var $Q={async encodeReq(V,$,Q,Z,J){let I=J.writeStruct($0,Q);if(I!==0)return I;let W=J.writeStructs(cV,Z);if(W!==0)return W;return 0},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I,notifier:W}=V,[Y,X]=$.readStruct($0);if(X!==0)return X;let G=await T0(Y,J,Z);if(G!==0)return G;let{pubKey:K}=Y,[R,N]=await I.hasUser(K);if(N!==0)return N;if(!R)return 5;let[z,U]=$.readStructs(cV);if(U!==0)return U;console.info(`PUSH: ${z.length} bags`);let M=[],H=[];for(let F=0;F<z.length;F++){let A=z[F];if(!await a$(A,K,J)){let m={idx:F,status:3},E=Q.writeStruct(MV,m);if(E!==0)return E;continue}M.push(F),H.push(A)}let[q,P]=await I.setBags(K,H);if(P!==0)return P;if(!q||q.length!==H.length)return 17;let T=[];for(let F=0;F<H.length;F++){let A=H[F],j=M[F],m=q[F],E=new x,S=E.writeStruct(RV,A);if(S!==0)return S;let k=E.result(),C={seq:m,headCph:k};if(z.length===1&&A.bodyCph.length<=o$)C.bodyCph=A.bodyCph;T.push(C);let B={idx:j,status:0,seq:m},v=Q.writeStruct(MV,B);if(v!==0)return v}if(T.length>0){let F=new x,A=F.writeStructs(wV,T);if(A!==0)return A;let j=F.result();await Promise.resolve(W.push(K,j))}return 0},decodeResp(V){return V.readStructs(MV)}};var QQ={async encodeReq(V,$,Q,Z,J){return J.writeStruct($0,Q)},async handleReq(V,$,Q){let{clock:Z,crypto:J,storage:I}=V,[W,Y]=$.readStruct($0);if(Y!==0)return Y;let X=await T0(W,J,Z);if(X!==0)return X;let{pubKey:G}=W;if(!$.done())return 8;let[K,R]=await I.addUser(G);if(R!==0)return R;return 0},decodeResp(V){return O(void 0)}};class dV{url;websocket;constructor(V){this.url=V}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(V,$,Q=()=>{},Z=()=>{}){let{url:J}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let I=new x;I.writeStruct($0,V);let W=I.result(),Y=o(W);return J.searchParams.set("t",Y),this.websocket=new WebSocket(J),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),Z()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Q()},this.websocket.onmessage=(X)=>{let G=new Uint8Array(X.data);$(G)},this.websocket.onerror=(X)=>{console.log(`ERROR: ${JSON.stringify(X)}`),this.websocket=void 0,Q()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var h={user:{path:"/user",endpoint:QQ,name:0},push:{path:"/push",endpoint:$Q,name:2},peek:{path:"/peek",endpoint:e$,name:1},pull:{path:"/pull",endpoint:VQ,name:3}},qZ={0:h.user,2:h.push,1:h.peek,3:h.pull},GY={[h.user.path]:h.user,[h.push.path]:h.push,[h.peek.path]:h.peek,[h.pull.path]:h.pull};class oV{url;listener;constructor(V){this.url=V;this.listener=new dV(V)}async call(V,$){let{path:Q}=qZ[V],Z=new URL(Q,this.url);try{return await HZ(Z,$)}catch{return w(25)}}}var NV=(V)=>{return new oV(V.handle)};async function HZ(V,$){let Q=await fetch(V,{method:"POST",body:$.result().slice()});if(!Q.ok)return w(24);let Z=await f.fromResponse(Q);return O(Z)}class zV{enclave;crypto;host;clock;transport;updateHostMeta;constructor(V,$,Q,Z,J,I){this.enclave=V;this.crypto=$;this.host=Q;this.clock=Z;this.transport=J;this.updateHostMeta=I}async call(V,$){let{clock:Q,crypto:Z,transport:J}=this,{endpoint:I,name:W}=V,Y=await this.keys(),X=Q.now(),[G,K]=await nV(Y,X,Z);if(K!==0)return w(K);let R=new x,N=await I.encodeReq(this,Y,G,$,R);if(N!==0)return w(N);let z=Q.now(),[U,M]=await J.call(W,R),H=Q.now();if(M!==0)return w(M);let[q,P]=U.readStruct(pV);if(P!==0)return w(P);if(q.status!==0)return w(q.status);let F={clockOffset:t$(z,q.timeRcvd,q.timeSent,H),subscription:q.subscription},A=await this.updateHostMeta(F);if(A!==0)return w(A);return I.decodeResp(U)}keys=()=>{let{host:V}=this;return rV(this,V.label,V.idx)};seal=async(V)=>{let{crypto:$,enclave:Q}=this,Z=await this.keys();return s$(V,Z,$,Q)};register=()=>this.call(h.user,[]);peek=(V)=>this.call(h.peek,[V]);push=(V)=>this.call(h.push,V);pull=(V)=>this.call(h.pull,V);listen=async(V,$,Q)=>{let{clock:Z,crypto:J,host:I,transport:W}=this,{listener:Y}=W,X=await rV(this,I.label,I.idx),G=Z.now(),[K,R]=await nV(X,G,J);if(R!==0)return R;return await Y.connect(K,V,$,Q)};isConnected(){let V=this.transport?.listener;if(V&&typeof V.connected==="function")return V.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var aV={encode(V,$){let Q=V.writeVarString($.lbl);if(Q!==0)return Q;let Z=V.writeVarInt($.idx);if(Z!==0)return Z;let J=V.writeVarInt($.num);if(J!==0)return J;return V.writeBytes($.hsh),V.writeBytes($.sig),0},decode(V){let[$,Q]=V.readVarString();if(Q!==0)return w(Q);let[Z,J]=V.readVarInt();if(J!==0)return w(J);let[I,W]=V.readVarInt();if(W!==0)return w(W);let[Y,X]=V.readBytes(KV);if(X!==0)return w(X);let[G,K]=V.readBytes(C0);if(K!==0)return w(K);return O({lbl:$,idx:Z,num:I,hsh:Y,sig:G})}};var sV={encode(V,$){let Q=V.writeStruct(aV,$.head);if(Q!==0)return Q;let Z=V.writeVarBytes($.indexEnc);if(Z!==0)return Z;let J=V.writeVarBytes($.bodyEnc);if(J!==0)return J;return 0},decode(V){let[$,Q]=V.readStruct(aV);if(Q!==0)return w(Q);let[Z,J]=V.readVarBytes();if(J!==0)return w(J);let[I,W]=V.readVarBytes();if(W!==0)return w(W);return O({head:$,indexEnc:Z,bodyEnc:I})}};var tV={encode(V,$){V.writeBytes($.kdm);let Q=V.writeVarBytes($.headCph);if(Q!==0)return Q;let Z=V.writeVarInt($.lenBody);if(Z!==0)return Z;if($.lenBody>0&&$.offBody!==void 0){let J=V.writeVarInt($.offBody);if(J!==0)return J}return 0},decode(V){let[$,Q]=V.readBytes(D0);if(Q!==0)return w(Q);let[Z,J]=V.readVarBytes();if(J!==0)return w(J);let[I,W]=V.readVarInt();if(W!==0)return w(W);let Y;if(I>0){let[X,G]=V.readVarInt();if(G!==0)return w(G);Y=X}return O({kdm:$,headCph:Z,lenBody:I,offBody:Y})}};async function ZQ(V,$,Q,Z,J){let I=await J.derive(V,$),W=await Z.deriveEd25519KeyPair(I),Y=new x,X=new x,G=0,K=0;for(let P of Q){let T=new x,F=T.writeStruct(Y0,P.head);if(F!==0)return w(F);let A=T.result(),j=await yV(A,W,Z),m=await J.deriveFromKDM(j),E=await Z.encryptXSalsa20Poly1305Combined(A,m),S=P.body?await Z.encryptXSalsa20Poly1305Combined(P.body,m):new Uint8Array(0),k=P.head.len>0&&P.head.hsh!==void 0?S.length:0,C={kdm:j,headCph:E,lenBody:k,offBody:k>0?K:void 0},B=Y.writeStruct(tV,C);if(B!==0)return w(B);if(P.body)X.writeBytes(S),K+=S.length;G++}let R=X.result(),N=Y.result(),z=await Z.blake3(N),U=await Z.signEd25519(z,W.privateKey),M={lbl:V,idx:$,num:G,hsh:z,sig:U},H=new x;H.writeStruct(sV,{head:M,indexEnc:N,bodyEnc:R});let q=H.result();return O(q)}async function JQ(V,$,Q){let[Z,J]=sV.decode(new f(V));if(J!==0)return w(J);let{head:I,indexEnc:W,bodyEnc:Y}=Z,X=await Q.derive(I.lbl,I.idx),G=await $.deriveEd25519KeyPair(X);if(!await $.checkSigEd25519(I.sig,I.hsh,G.publicKey))return w(3);let R=await $.blake3(W);if(!X0(R,I.hsh))return w(19);let N=new f(W),z=[];for(let M=0;M<I.num;M++){let[H,q]=N.readStruct(tV);if(q!==0)return w(q);z.push(H)}if(z.length!==I.num)return w(14);let U=[];for(let M of z){let H=await Q.deriveFromKDM(M.kdm),q=await $.decryptXSalsa20Poly1305Combined(M.headCph,H),[P,T]=Y0.decode(new f(q));if(T!==0)return w(T);let F;if(M.lenBody>0&&M.offBody!==void 0){if(P.hsh===void 0)return w(14);let A=Y.slice(M.offBody,M.offBody+M.lenBody);F=await $.decryptXSalsa20Poly1305Combined(A,H);let j=await $.blake3(F);if(!X0(j,P.hsh))return w(19)}U.push({head:P,body:F})}return O(U)}async function IQ({now:V,bod:$,crypto:Q}){let Z=await Q.genRandomBytes(8),J=new x,I=J.writeStruct(Q0,{id:Z,ts:V});if(I!==0)return w(I);let W=J.result();return UV({now:V,eid:W,ctr:0,bod:$,crypto:Q})}async function UV({now:V,eid:$,ctr:Q,bod:Z,crypto:J}){let I=new f($),[W,Y]=Q0.decode(I);if(Y!==0)return w(Y);let X=V.getTime()-W.ts.getTime(),G,K=Z?.length??0;if(Z&&K>0)G=await J.blake3(Z);return O({eid:$,off:X,ctr:Q,len:K,hsh:G})}class FV{inflight=null;again=!1;run(V){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain(V),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain(V){try{this.again=!1;let $=await V();while(this.again)this.again=!1,$=await V();return $}finally{this.inflight=null}}}var OV=100;class t0{timer=null;delayMs;work;tail=new FV;constructor(V,$){this.delayMs=V<0?0:V,this.work=$}schedule(){if(this.delayMs<=0){this.fire();return}if(this.timer!==null)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=null,this.fire()},this.delayMs)}async flush(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null,this.fire();await this.tail.flush()}cancel(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null}fire(){return this.tail.run(this.work)}}var n0={phase:"idle"},e0=50;function eV(V,$,Q){if(V<=0||$<=0)return!1;if(V===1||V===$)return!0;return V%Q===0}function qV(V,$){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(V,$);return}let Q=URL.createObjectURL(V),Z=document.createElement("a");Z.href=Q,Z.download=$,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)}function WQ(V,$,Q){let Z=[],J=[],I=0;for(let W of V){let Y=$(W);if(J.length>0&&I+Y>Q)Z.push(J),J=[],I=0;if(J.push(W),I+=Y,I>=Q)Z.push(J),J=[],I=0}if(J.length>0)Z.push(J);return Z}async function YQ(V,$,Q){let Z=V.length;if(Z<1)return[];let J=Array(Z),I=0,W=Math.min(Math.max(1,$),Z),Y=async()=>{while(!0){let G=I;if(I+=1,G>=Z)return;J[G]=await Q(V[G],G)}},X=[];for(let G=0;G<W;G++)X.push(Y());return await Promise.all(X),J}async function V$(V,$,Q,Z){let J=new f(V.headCph),[I,W]=J.readStruct(RV);if(W!==0)return w(W);let{sig:Y,kdm:X,headCph:G}=I;if(!await Z.checkSigEd25519(Y,G,$.publicKey))return w(3);let R=await Q.deriveFromKDM(X),N;try{N=await Z.decryptXSalsa20Poly1305Combined(G,R)}catch{return w(20)}return O({kdm:X,headEnc:N})}var $$=1048576,Q$=1048576,PZ=64;function CZ(V){return V.sig.length+V.kdm.length+V.headCph.length+V.bodyCph.length}async function DZ(V,$,Q,Z,J){if(Z.length<1)return 0;let[I,W]=await V.push(Z);if(W!==0)return W;if(!I)return 27;for(let X of I){if(X.status!==0){console.error("push err",X);continue}let G=J[X.idx];if(!G){console.error("no hash",X);continue}await $.uploads.deq(Q,[G])}let Y=await $.hosts.get(Q);if(Y){let X=Y.lastSeq,G=X,K=[];for(let R of I)if(R.status===0)K.push(R.seq);K.sort((R,N)=>R-N);for(let R of K)if(R===X+1)X=R;if(X>G)await $.hosts.touch(Q,X)}return 0}async function XQ(V,$){if($.length<1)return O([]);let Q=new Map,Z=[];for(let Y of $)Q.set(Y.seq,Y),Z.push(Y.seq);let[J,I]=await V.pull(Z);if(I!==0)return w(I);if(!J)return w(27);let W=[];for(let{seq:Y,bodyCph:X}of J){let G=Q.get(Y);if(!G)continue;W.push({dl:G,bodyCph:X})}return O(W)}async function TZ(V,$,Q,Z){if(Z.length<1)return O({parts:[],hashes:[]});let J=[],I=[],W=[],Y=new Map;for(let{dl:G,bodyCph:K}of Z){let{head:R,kdm:N,seq:z,host:U}=G,M=new x;M.writeStruct(Y0,R);let H=M.result(),q=await Q.blake3(H),P=await $.deriveFromKDM(N),[T,F]=await bV(H,K,P,Q);if(F!==0){let m=Y.get(U)??[];m.push(z),Y.set(U,m);continue}let A={head:R,body:T.bod};W.push({key:q,data:RQ(A)}),J.push(A),I.push(q);let j=Y.get(U)??[];j.push(z),Y.set(U,j)}let X=await V.messages.add(W);for(let[G,K]of Y)await V.downloads.deq(G,K);for(let G=0;G<X.length;G++){let K=X[G];if(K!==0&&K!==15)console.error("ERR storing",_[K],"for message",G)}return O({parts:J,hashes:I})}async function GQ({conn:V,store:$,enclave:Q,host:Z,crypto:J,onProgress:I,peekProgressEvery:W,peekConcurrency:Y}){let X=await V.keys(),G=[],[K,R]=await V.peek(Z.lastSeq);if(R!==0)return R;let N=K.length,z=W??e0,U=Y??PZ;if(I&&N>0)I({phase:"peek",host:Z.label,done:0,total:N});let M=0,H=await YQ(K,U,async(q)=>{let[P,T]=await V$(q,X,Q,J),F;if(T!==0||!P)F={ok:!1,seq:q.seq,stat:T};else{let A=await J.blake3(P.headEnc);F={ok:!0,seq:q.seq,kdm:P.kdm,headEnc:P.headEnc,headEncHash:A}}if(M+=1,I&&eV(M,N,z))I({phase:"peek",host:Z.label,done:M,total:N});return F});for(let q of H){if(!q.ok){console.error("peek: decrypting item head",q.stat);continue}if(await $.messages.has(q.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await $.uploads.deq(Z.label,[q.headEncHash]);continue}let T=new f(q.headEnc),[F,A]=T.readStruct(Y0);if(A!==0){console.error("peek: reading item head",A);continue}G.push({kdm:q.kdm,head:F,seq:q.seq,host:Z.label})}if(await $.downloads.enq(G),K.length>0){let q=Math.max(...K.map((P)=>P.seq));await $.hosts.touch(Z.label,q)}if(I)I({phase:"peek",host:Z.label,done:N,total:N});return 0}async function KQ({conn:V,store:$,host:Q,maxPushBytes:Z,onProgress:J}){let I=Z??$$,W=await $.uploads.list(Q.label),Y=W.length,X=0;if(J&&Y>0)J({phase:"push",host:Q.label,done:0,total:Y});let G=[],K=[],R=0,N=async()=>{if(G.length<1)return 0;let z=G.length,U=await DZ(V,$,Q.label,G,K);if(G=[],K=[],R=0,U===0){if(X+=z,J)J({phase:"push",host:Q.label,done:X,total:Y})}return U};for(let z of W){let U=await $.messages.get(z);if(!U){X+=1;continue}let M={...U.head,bod:U.body},[H,q]=await V.seal(M);if(q!==0)return q;if(!H)return 12;let P=CZ(H);if(G.length>0&&R+P>I){let T=await N();if(T!==0)return T}if(G.push(H),K.push(z),R+=P,R>=I){let T=await N();if(T!==0)return T}}return N()}async function wQ({conn:V,store:$,enclave:Q,host:Z,crypto:J,maxPullBytes:I,onProgress:W},Y){let X=I??Q$,G=await $.downloads.list(),K=Array.from(G).filter((M)=>M.host===Z.label);if(K.length<1)return 15;let R=WQ(K,(M)=>M.head.len,X),N=K.length,z=0;if(W)W({phase:"pull",host:Z.label,done:0,total:N});let U=XQ(V,R[0]);for(let M=0;M<R.length;M++){let[H,q]=await U;if(q!==0||!H)return q;if(z+=R[M].length,W)W({phase:"pull",host:Z.label,done:z,total:N});let P=R[M+1];if(P)U=XQ(V,P);if(W)W({phase:"open",host:Z.label,done:z,total:N});let[,T]=await TZ($,Q,J,H);if(T!==0)return T;if(Y){if(W)W({phase:"exec",host:Z.label,done:z,total:N});await Y()}}return 0}function RQ({head:V,body:$}){return{eid:V.eid,...V.off!==0?{off:V.off}:{},...V.ctr!==0?{ctr:V.ctr}:{},body:$,apld:!1}}async function MQ(V,{conn:$,store:Q,enclave:Z,host:J,crypto:I,onProgress:W},Y){let X=J.label,G=await $.keys(),K=new f(V),[R,N]=K.readStructs(wV);if(N!==0){console.error("Failed decoding notif",_[N]);return}let z=!1,M=(await Q.hosts.get(X))?.lastSeq,H=[],q=!1;for(let F of R){let[A,j]=await V$({seq:F.seq,headCph:F.headCph},G,Z,I);if(j!==0){console.error("Failed decrypting notif",_[j]);continue}let m=await I.blake3(A.headEnc);if(await Q.messages.has(m))continue;let E=new f(A.headEnc),[S,k]=E.readStruct(Y0);if(k!==0){console.error("Failed to parse head",_[k]);continue}if(!F.bodyCph&&S.len>0)q=!0,await Q.downloads.enq([{seq:F.seq,host:X,kdm:A.kdm,head:S}]);else H.push({...A,head:S,bodyCph:F.bodyCph,headEncHash:m});if(M===void 0||F.seq!==M+1)console.log("out of seq",F.seq,M),z=!0;else M=F.seq}if(M!==void 0)await Q.hosts.touch(J.label,M);let P=[];for(let F of H){let A=await Z.deriveFromKDM(F.kdm),[j,m]=await bV(F.headEnc,F.bodyCph,A,I);if(m!==0){console.error("Failed to open body",_[m]);continue}P.push({key:F.headEncHash,data:RQ({head:F.head,body:j.bod})})}let T=await Q.messages.add(P);for(let F=0;F<T.length;F++){let A=T[F];if(A!==0&&A!==15)console.error("ERR storing",_[A],"for message",F)}if(W&&P.length>0)W({phase:"open",host:J.label,done:P.length,total:P.length});if(z||q||P.length>0)Y()}class _0{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new FV;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=e0;lastProgress=n0;scheduledSync;constructor(V,$,Q,Z,J,I=!0,W=$$,Y=Q$,X){this.clock=V;this.state=$;this.store=Q;this.transport=Z;this.crypto=J;this.forceSkewHandlingByDefault=I;this.onScheduleSync=X;this.maxPushBytes=W,this.maxPullBytes=Y,this.clientState=new G0(()=>this.getClientState()),this.xferState=new G0(()=>this.getXferState()),this.scheduledSync=new t0(OV,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(G){console.error("Debounced sync failed:",G)}})}emitProgress=(V)=>{this.lastProgress=V,this.xferState.emit()};async setSeed(V){await this.store.seed.save(V),this.clientState.emit()}async getClientState(){let{store:V,connections:$}=this,Q=await V.seed.load(),Z=await V.hosts.list(),J=!1;for(let I of $.values())if(I.isConnected()){J=!0;break}return{hasSeed:Q!==void 0,hasHost:Array.from(Z).length>0,connected:J}}async getXferState(){let{uploads:V,downloads:$}=this.store,Q=await V.count();return{numDownloads:await $.count(),numUploads:Q,progress:this.lastProgress}}apply=async(V,$={enqueueUpload:!0,triggerUpload:!0})=>{let Q=[],Z=[];for(let{head:I,body:W}of V){let Y=new x;Y.writeStruct(Y0,I);let X=Y.result(),G=await this.crypto.blake3(X),K={eid:I.eid,...I.off!==0?{off:I.off}:{},...I.ctr!==0?{ctr:I.ctr}:{},body:W,apld:!1};Q.push(G),Z.push({key:G,data:K})}await this.store.messages.add(Z);let J=await this.applyHashes(Q);if($.enqueueUpload){let I=[];for(let W=0;W<Q.length;W++){let Y=J[W];if(Y===0||Y===15)I.push(Q[W])}if(I.length>0){let W=await this.store.hosts.list();for(let Y of W)await this.store.uploads.enq(Y.label,I);this.xferState.emit()}}if($.triggerUpload)this.scheduleSync();return J};enqueueApplyJob(V){let $=this.applyChain.then(V,V);return this.applyChain=$.then(()=>{return},()=>{return}),$}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let V=await this.store.messages.listUnapplied();if(V.length<1)return[];return this.applyStored(V)}applyHashes=(V)=>{return this.enqueueApplyJob(async()=>{let $=[];for(let J of V){let I=await this.store.messages.get(J);if(I)$.push(I)}let Q=await this.applyStored($),Z=new Map;for(let J=0;J<$.length;J++)Z.set(g($[J].hash),Q[J]??12);return V.map((J)=>Z.get(g(J))??13)})};async applyStored(V){if(V.length<1)return[];let $=V.map((J)=>({...J.head,bod:J.body})),Q=await this.state.apply($),Z=[];for(let J=0;J<V.length;J++){let I=Q[J];if(I===0||I===15)Z.push(V[J].hash)}if(Z.length>0)await this.store.messages.markApplied(Z);return Q}async insertRaw(V){let{clock:$,crypto:Q}=this,[Z,J]=await IQ({now:$.now(),bod:V,crypto:Q});if(J!==0)return w(J);return await this.apply([{head:Z,body:V}]),O(Z)}async upsertRaw(V,$,Q=!1){let{clock:Z,crypto:J,store:I}=this,W=Z.now(),Y=await I.messages.last(V);if(Y){let z=new f(V),[U,M]=z.readStruct(Q0);if(M!==0)return w(M);if(U.ts.getTime()+Y.head.off>W.getTime()){if(Q===!1)return w(4);let q=Y.head.off+1,P=Y.head.ctr+1,T={eid:V,off:q,ctr:P,len:0},A=(await this.apply([{head:T,body:void 0}]))[0];if(A!==0)return w(A);if($===void 0)return O(T);let[j,m]=u0({id:U.id,ts:W});if(m!==0)return w(m);let E={now:W,eid:j,ctr:0,bod:$,crypto:J},[S,k]=await UV(E);if(k!==0)return w(k);let B=(await this.apply([{head:S,body:$}]))[0];if(B!==0)return w(B);return O(S)}}let X=(Y?.head.ctr??-1)+1,[G,K]=await UV({now:W,eid:V,ctr:X,bod:$,crypto:J});if(K!==0)return w(K);let N=(await this.apply([{head:G,body:$}]))[0];if(N!==0)return w(N);return O(G)}async insert(V){let{body:$,type:Q,gid:Z,pid:J}=V,W=YV({body:$,type:Q,gid:Z,pid:J});return this.insertRaw(W)}async upsert(V,$=this.forceSkewHandlingByDefault){let{eid:Q,body:Z,type:J,gid:I,pid:W}=V;if(Q===void 0)return this.insert(V);let X=YV({body:Z,type:J,gid:I,pid:W});return this.upsertRaw(Q,X,$)}async delete(V){return this.upsertRaw(V,void 0,!0)}async genEID(V){let{clock:$,crypto:Q}=this,Z=$.now();if(V!==void 0)return u0({id:V,ts:Z});let J=await Q.genRandomBytes(8);return u0({id:J,ts:Z})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:V,crypto:$,store:Q}=this,Z=await Q.seed.load();if(!Z)return 22;await this.drainApplyQueue();for(let[J,I]of V){let W=await Q.hosts.get(J);if(!W)continue;let Y={conn:I,store:Q,enclave:Z,host:W,crypto:$,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},X=await GQ(Y);if(X!==0)return console.error(`Failed to peek: ${X}`),X;this.xferState.emit();let G=await KQ(Y);if(G!==0)return console.error(`Failed to push: ${G}`),G;this.xferState.emit();let K=await wQ(Y,async()=>{await this.drainApplyQueue()});if(K!==0&&K!==15)return console.error(`Failed to pull: ${K}`),K;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async wipe(){this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush(),await this.store.wipe(),await this.state.clear(),this.lastProgress=n0,this.clientState.emit(),this.xferState.emit()}import=async(V,$)=>{let{crypto:Q,store:Z}=this,J=$?.onProgress,I=await Z.seed.load();if(!I)return 22;console.time("import: decoding file...");let W=await V.bytes(),[Y,X]=await JQ(W,Q,I);if(X!==0)return X;console.timeEnd("import: decoding file...");let G=0;while(G<Y.length){let K=0,R=0,N=G;for(let M=G;M<Y.length&&R<100&&K<102400;M++)K+=Y[M].head.len,R++,N=M+1;let z=Y.slice(G,N);console.time(`import: applying [${G}, ${N}]`);let U=await this.apply(z,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${G}, ${N}]`);for(let M=0;M<z.length;M++){let H=U[M];if(H!==0&&H!==15)console.warn(`failed to import msg ${G+M}: ${_[H]}`)}if(J)queueMicrotask(()=>J(N,Y.length,0));this.emitProgress({phase:"import",done:N,total:Y.length}),G=N}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:V,store:$}=this,Q=await $.seed.load();if(!Q)return w(22);let Z=await $.messages.list();return ZQ("export",0,Z,V,Q)}async export(V){let[$,Q]=await this.exportBytes();if(Q!==0)return Q;if(!$)return 12;let Z=new Blob([$.slice()]);return qV(Z,V),0}async link(V,$=!0){if(await this.store.hosts.add(V),this.clientState.emit(),$){let Q=await this.store.hosts.get(V.label);if(Q)await this.connectToHost(Q)}}async unlink(V){await this.store.hosts.del(V),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async(V,$=!0,Q=!0)=>{let{clock:Z,connections:J,crypto:I,store:W,transport:Y}=this,X=J.get(V.label);if(X){if(X.isConnected())return;try{X.closeListener()}catch{}J.delete(V.label)}let G=await W.seed.load();if(!G)return;console.info(`Connecting to ${V.handle} (${V.label})`);let K=new zV(G,I,V,Z,Y(V),(R)=>W.hosts.set(V.label,R));if(await K.register(),$)await K.listen(async(R)=>{let N={conn:K,store:W,enclave:G,host:V,crypto:I,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return MQ(R,N,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(J.set(V.label,K),this.clientState.emit(),Q)this.scheduleSync()};async connect(V=!0,$=!0){let{connectToHost:Q,scheduleSync:Z,store:J}=this;if(!await J.seed.load())return;await this.drainApplyQueue();let W=await J.hosts.list();for(let Y of W)await Q(Y,V,!1);if($)Z()}disconnect=async()=>{for(let V of this.connections.values())try{V.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var L0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function HV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function Z$(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function l(V,...$){if(!Z$(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function J$(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function NQ(V,$){l(V);let Q=$.outputLen;if(V.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function I$(V){if(typeof V!=="boolean")throw Error(`boolean expected, not ${V}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var z0=(V)=>new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4));var AZ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!AZ)throw Error("Non little-endian hardware is not supported");function _Z(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function PV(V){if(typeof V==="string")V=_Z(V);else if(Z$(V))V=CV(V);else throw Error("Uint8Array expected, got "+typeof V);return V}function zQ(V,$){if($==null||typeof $!=="object")throw Error("options must be defined");return Object.assign(V,$)}function UQ(V,$){if(V.length!==$.length)return!1;let Q=0;for(let Z=0;Z<V.length;Z++)Q|=V[Z]^$[Z];return Q===0}var FQ=(V,$)=>{function Q(Z,...J){if(l(Z),V.nonceLength!==void 0){let K=J[0];if(!K)throw Error("nonce / iv required");if(V.varSizeNonce)l(K);else l(K,V.nonceLength)}let I=V.tagLength;if(I&&J[1]!==void 0)l(J[1]);let W=$(Z,...J),Y=(K,R)=>{if(R!==void 0){if(K!==2)throw Error("cipher output not supported");l(R)}},X=!1;return{encrypt(K,R){if(X)throw Error("cannot encrypt() twice with same key + nonce");return X=!0,l(K),Y(W.encrypt.length,R),W.encrypt(K,R)},decrypt(K,R){if(l(K),I&&K.length<I)throw Error("invalid ciphertext length: smaller than tagLength="+I);return Y(W.decrypt.length,R),W.decrypt(K,R)}}}return Object.assign(Q,V),Q};function W$(V,$,Q=!0){if($===void 0)return new Uint8Array(V);if($.length!==V)throw Error("invalid output length, expected "+V+", got: "+$.length);if(Q&&!LZ($))throw Error("invalid output, must be aligned");return $}function LZ(V){return V.byteOffset%4===0}function CV(V){return Uint8Array.from(V)}function K0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function DV(V=32){if(L0&&typeof L0.getRandomValues==="function")return L0.getRandomValues(new Uint8Array(V));if(L0&&typeof L0.randomBytes==="function")return L0.randomBytes(V);throw Error("crypto.getRandomValues must be defined")}var qQ=(V)=>Uint8Array.from(V.split("").map(($)=>$.charCodeAt(0))),jZ=qQ("expand 16-byte k"),mZ=qQ("expand 32-byte k"),SZ=z0(jZ),EZ=z0(mZ);function D(V,$){return V<<$|V>>>32-$}function Y$(V){return V.byteOffset%4===0}var TV=64,xZ=16,HQ=4294967295,OQ=new Uint32Array;function kZ(V,$,Q,Z,J,I,W,Y){let X=J.length,G=new Uint8Array(TV),K=z0(G),R=Y$(J)&&Y$(I),N=R?z0(J):OQ,z=R?z0(I):OQ;for(let U=0;U<X;W++){if(V($,Q,Z,K,W,Y),W>=HQ)throw Error("arx: counter overflow");let M=Math.min(TV,X-U);if(R&&M===TV){let H=U/4;if(U%4!==0)throw Error("arx: invalid block position");for(let q=0,P;q<xZ;q++)P=H+q,z[P]=N[P]^K[q];U+=TV;continue}for(let H=0,q;H<M;H++)q=U+H,I[q]=J[q]^G[H];U+=M}}function PQ(V,$){let{allowShortKeys:Q,extendNonceFn:Z,counterLength:J,counterRight:I,rounds:W}=zQ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},$);if(typeof V!=="function")throw Error("core must be a function");return HV(J),HV(W),I$(I),I$(Q),(Y,X,G,K,R=0)=>{l(Y),l(X),l(G);let N=G.length;if(K===void 0)K=new Uint8Array(N);if(l(K),HV(R),R<0||R>=HQ)throw Error("arx: counter overflow");if(K.length<N)throw Error(`arx: output (${K.length}) is shorter than data (${N})`);let z=[],U=Y.length,M,H;if(U===32)z.push(M=CV(Y)),H=EZ;else if(U===16&&Q)M=new Uint8Array(32),M.set(Y),M.set(Y,16),H=SZ,z.push(M);else throw Error(`arx: invalid 32-byte key, got length=${U}`);if(!Y$(X))z.push(X=CV(X));let q=z0(M);if(Z){if(X.length!==24)throw Error("arx: extended nonce must be 24 bytes");Z(H,q,z0(X.subarray(0,16)),q),X=X.subarray(16)}let P=16-J;if(P!==X.length)throw Error(`arx: nonce must be ${P} or 16 bytes`);if(P!==12){let F=new Uint8Array(12);F.set(X,I?0:12-X.length),X=F,z.push(X)}let T=z0(X);return kZ(V,H,q,T,G,K,R,W),K0(...z),K}}var c=(V,$)=>V[$++]&255|(V[$++]&255)<<8;class CQ{constructor(V){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,V=PV(V),l(V,32);let $=c(V,0),Q=c(V,2),Z=c(V,4),J=c(V,6),I=c(V,8),W=c(V,10),Y=c(V,12),X=c(V,14);this.r[0]=$&8191,this.r[1]=($>>>13|Q<<3)&8191,this.r[2]=(Q>>>10|Z<<6)&7939,this.r[3]=(Z>>>7|J<<9)&8191,this.r[4]=(J>>>4|I<<12)&255,this.r[5]=I>>>1&8190,this.r[6]=(I>>>14|W<<2)&8191,this.r[7]=(W>>>11|Y<<5)&8065,this.r[8]=(Y>>>8|X<<8)&8191,this.r[9]=X>>>5&127;for(let G=0;G<8;G++)this.pad[G]=c(V,16+2*G)}process(V,$,Q=!1){let Z=Q?0:2048,{h:J,r:I}=this,W=I[0],Y=I[1],X=I[2],G=I[3],K=I[4],R=I[5],N=I[6],z=I[7],U=I[8],M=I[9],H=c(V,$+0),q=c(V,$+2),P=c(V,$+4),T=c(V,$+6),F=c(V,$+8),A=c(V,$+10),j=c(V,$+12),m=c(V,$+14),E=J[0]+(H&8191),S=J[1]+((H>>>13|q<<3)&8191),k=J[2]+((q>>>10|P<<6)&8191),C=J[3]+((P>>>7|T<<9)&8191),B=J[4]+((T>>>4|F<<12)&8191),v=J[5]+(F>>>1&8191),y=J[6]+((F>>>14|A<<2)&8191),b=J[7]+((A>>>11|j<<5)&8191),p=J[8]+((j>>>8|m<<8)&8191),r=J[9]+(m>>>5|Z),L=0,d=L+E*W+S*(5*M)+k*(5*U)+C*(5*z)+B*(5*N);L=d>>>13,d&=8191,d+=v*(5*R)+y*(5*K)+b*(5*G)+p*(5*X)+r*(5*Y),L+=d>>>13,d&=8191;let a=L+E*Y+S*W+k*(5*M)+C*(5*U)+B*(5*z);L=a>>>13,a&=8191,a+=v*(5*N)+y*(5*R)+b*(5*K)+p*(5*G)+r*(5*X),L+=a>>>13,a&=8191;let V0=L+E*X+S*Y+k*W+C*(5*M)+B*(5*U);L=V0>>>13,V0&=8191,V0+=v*(5*z)+y*(5*N)+b*(5*R)+p*(5*K)+r*(5*G),L+=V0>>>13,V0&=8191;let i=L+E*G+S*X+k*Y+C*W+B*(5*M);L=i>>>13,i&=8191,i+=v*(5*U)+y*(5*z)+b*(5*N)+p*(5*R)+r*(5*K),L+=i>>>13,i&=8191;let M0=L+E*K+S*G+k*X+C*Y+B*W;L=M0>>>13,M0&=8191,M0+=v*(5*M)+y*(5*U)+b*(5*z)+p*(5*N)+r*(5*R),L+=M0>>>13,M0&=8191;let E0=L+E*R+S*K+k*G+C*X+B*Y;L=E0>>>13,E0&=8191,E0+=v*W+y*(5*M)+b*(5*U)+p*(5*z)+r*(5*N),L+=E0>>>13,E0&=8191;let x0=L+E*N+S*R+k*K+C*G+B*X;L=x0>>>13,x0&=8191,x0+=v*Y+y*W+b*(5*M)+p*(5*U)+r*(5*z),L+=x0>>>13,x0&=8191;let k0=L+E*z+S*N+k*R+C*K+B*G;L=k0>>>13,k0&=8191,k0+=v*X+y*Y+b*W+p*(5*M)+r*(5*U),L+=k0>>>13,k0&=8191;let f0=L+E*U+S*z+k*N+C*R+B*K;L=f0>>>13,f0&=8191,f0+=v*G+y*X+b*Y+p*W+r*(5*M),L+=f0>>>13,f0&=8191;let B0=L+E*M+S*U+k*z+C*N+B*R;L=B0>>>13,B0&=8191,B0+=v*K+y*G+b*X+p*Y+r*W,L+=B0>>>13,B0&=8191,L=(L<<2)+L|0,L=L+d|0,d=L&8191,L=L>>>13,a+=L,J[0]=d,J[1]=a,J[2]=V0,J[3]=i,J[4]=M0,J[5]=E0,J[6]=x0,J[7]=k0,J[8]=f0,J[9]=B0}finalize(){let{h:V,pad:$}=this,Q=new Uint16Array(10),Z=V[1]>>>13;V[1]&=8191;for(let W=2;W<10;W++)V[W]+=Z,Z=V[W]>>>13,V[W]&=8191;V[0]+=Z*5,Z=V[0]>>>13,V[0]&=8191,V[1]+=Z,Z=V[1]>>>13,V[1]&=8191,V[2]+=Z,Q[0]=V[0]+5,Z=Q[0]>>>13,Q[0]&=8191;for(let W=1;W<10;W++)Q[W]=V[W]+Z,Z=Q[W]>>>13,Q[W]&=8191;Q[9]-=8192;let J=(Z^1)-1;for(let W=0;W<10;W++)Q[W]&=J;J=~J;for(let W=0;W<10;W++)V[W]=V[W]&J|Q[W];V[0]=(V[0]|V[1]<<13)&65535,V[1]=(V[1]>>>3|V[2]<<10)&65535,V[2]=(V[2]>>>6|V[3]<<7)&65535,V[3]=(V[3]>>>9|V[4]<<4)&65535,V[4]=(V[4]>>>12|V[5]<<1|V[6]<<14)&65535,V[5]=(V[6]>>>2|V[7]<<11)&65535,V[6]=(V[7]>>>5|V[8]<<8)&65535,V[7]=(V[8]>>>8|V[9]<<5)&65535;let I=V[0]+$[0];V[0]=I&65535;for(let W=1;W<8;W++)I=(V[W]+$[W]|0)+(I>>>16)|0,V[W]=I&65535;K0(Q)}update(V){J$(this);let{buffer:$,blockLen:Q}=this;V=PV(V);let Z=V.length;for(let J=0;J<Z;){let I=Math.min(Q-this.pos,Z-J);if(I===Q){for(;Q<=Z-J;J+=Q)this.process(V,J);continue}if($.set(V.subarray(J,J+I),this.pos),this.pos+=I,J+=I,this.pos===Q)this.process($,0,!1),this.pos=0}return this}destroy(){K0(this.h,this.r,this.buffer,this.pad)}digestInto(V){J$(this),NQ(V,this),this.finished=!0;let{buffer:$,h:Q}=this,{pos:Z}=this;if(Z){$[Z++]=1;for(;Z<16;Z++)$[Z]=0;this.process($,0,!0)}this.finalize();let J=0;for(let I=0;I<8;I++)V[J++]=Q[I]>>>0,V[J++]=Q[I]>>>8;return V}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Q=V.slice(0,$);return this.destroy(),Q}}function fZ(V){let $=(Z,J)=>V(J).update(PV(Z)).digest(),Q=V(new Uint8Array(32));return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=(Z)=>V(Z),$}var X$=fZ((V)=>new CQ(V));function BZ(V,$,Q,Z,J,I=20){let W=V[0],Y=$[0],X=$[1],G=$[2],K=$[3],R=V[1],N=Q[0],z=Q[1],U=J,M=0,H=V[2],q=$[4],P=$[5],T=$[6],F=$[7],A=V[3],j=W,m=Y,E=X,S=G,k=K,C=R,B=N,v=z,y=U,b=M,p=H,r=q,L=P,d=T,a=F,V0=A;for(let M0=0;M0<I;M0+=2)k^=D(j+L|0,7),y^=D(k+j|0,9),L^=D(y+k|0,13),j^=D(L+y|0,18),b^=D(C+m|0,7),d^=D(b+C|0,9),m^=D(d+b|0,13),C^=D(m+d|0,18),a^=D(p+B|0,7),E^=D(a+p|0,9),B^=D(E+a|0,13),p^=D(B+E|0,18),S^=D(V0+r|0,7),v^=D(S+V0|0,9),r^=D(v+S|0,13),V0^=D(r+v|0,18),m^=D(j+S|0,7),E^=D(m+j|0,9),S^=D(E+m|0,13),j^=D(S+E|0,18),B^=D(C+k|0,7),v^=D(B+C|0,9),k^=D(v+B|0,13),C^=D(k+v|0,18),r^=D(p+b|0,7),y^=D(r+p|0,9),b^=D(y+r|0,13),p^=D(b+y|0,18),L^=D(V0+a|0,7),d^=D(L+V0|0,9),a^=D(d+L|0,13),V0^=D(a+d|0,18);let i=0;Z[i++]=W+j|0,Z[i++]=Y+m|0,Z[i++]=X+E|0,Z[i++]=G+S|0,Z[i++]=K+k|0,Z[i++]=R+C|0,Z[i++]=N+B|0,Z[i++]=z+v|0,Z[i++]=U+y|0,Z[i++]=M+b|0,Z[i++]=H+p|0,Z[i++]=q+r|0,Z[i++]=P+L|0,Z[i++]=T+d|0,Z[i++]=F+a|0,Z[i++]=A+V0|0}function gZ(V,$,Q,Z){let J=V[0],I=$[0],W=$[1],Y=$[2],X=$[3],G=V[1],K=Q[0],R=Q[1],N=Q[2],z=Q[3],U=V[2],M=$[4],H=$[5],q=$[6],P=$[7],T=V[3];for(let A=0;A<20;A+=2)X^=D(J+H|0,7),N^=D(X+J|0,9),H^=D(N+X|0,13),J^=D(H+N|0,18),z^=D(G+I|0,7),q^=D(z+G|0,9),I^=D(q+z|0,13),G^=D(I+q|0,18),P^=D(U+K|0,7),W^=D(P+U|0,9),K^=D(W+P|0,13),U^=D(K+W|0,18),Y^=D(T+M|0,7),R^=D(Y+T|0,9),M^=D(R+Y|0,13),T^=D(M+R|0,18),I^=D(J+Y|0,7),W^=D(I+J|0,9),Y^=D(W+I|0,13),J^=D(Y+W|0,18),K^=D(G+X|0,7),R^=D(K+G|0,9),X^=D(R+K|0,13),G^=D(X+R|0,18),M^=D(U+z|0,7),N^=D(M+U|0,9),z^=D(N+M|0,13),U^=D(z+N|0,18),H^=D(T+P|0,7),q^=D(H+T|0,9),P^=D(q+H|0,13),T^=D(P+q|0,18);let F=0;Z[F++]=J,Z[F++]=G,Z[F++]=U,Z[F++]=T,Z[F++]=K,Z[F++]=R,Z[F++]=N,Z[F++]=z}var G$=PQ(BZ,{counterRight:!0,extendNonceFn:gZ}),K$=FQ({blockSize:64,nonceLength:24,tagLength:16},(V,$)=>{return{encrypt(Q,Z){Z=W$(Q.length+32,Z,!1);let J=Z.subarray(0,32),I=Z.subarray(32);Z.set(Q,32),K0(J),G$(V,$,Z,Z);let W=X$(I,J);return Z.set(W,16),K0(Z.subarray(0,16),W),Z.subarray(16)},decrypt(Q,Z){l(Q),Z=W$(Q.length+32,Z,!1);let J=Z.subarray(0,32),I=Z.subarray(32,48),W=Z.subarray(48);Z.set(Q,32),K0(J);let Y=G$(V,$,J,J),X=X$(W,Y);if(!UQ(I,X))throw Error("invalid tag");return G$(V,$,Z.subarray(16),Z.subarray(16)),K0(J,I,X),W}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function iZ(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function VV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function j0(V,...$){if(!iZ(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function $V(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function AV(V,$){j0(V);let Q=$.outputLen;if(V.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function DQ(V){return new Uint8Array(V.buffer,V.byteOffset,V.byteLength)}function y0(V){return new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4))}function b0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function QV(V,$){return V<<32-$|V>>>$}var TQ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function AQ(V){return V<<24&4278190080|V<<8&16711680|V>>>8&65280|V>>>24&255}var _Q=TQ?(V)=>V:(V)=>AQ(V);function vZ(V){for(let $=0;$<V.length;$++)V[$]=AQ(V[$]);return V}var t=TQ?(V)=>V:vZ;function uZ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function p0(V){if(typeof V==="string")V=uZ(V);return j0(V),V}class w${}function LQ(V){let $=(Z,J)=>V(J).update(p0(Z)).digest(),Q=V({});return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=(Z)=>V(Z),$}var jQ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var _V=BigInt(4294967295),mQ=BigInt(32);function R$(V,$=!1){if($)return{h:Number(V&_V),l:Number(V>>mQ&_V)};return{h:Number(V>>mQ&_V)|0,l:Number(V&_V)|0}}function U0(V,$,Q,Z,J){return V=V+$+J|0,Z=QV(Z^V,16),Q=Q+Z|0,$=QV($^Q,12),{a:V,b:$,c:Q,d:Z}}function F0(V,$,Q,Z,J){return V=V+$+J|0,Z=QV(Z^V,8),Q=Q+Z|0,$=QV($^Q,7),{a:V,b:$,c:Q,d:Z}}class M$ extends w${constructor(V,$){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,VV(V),VV($),this.blockLen=V,this.outputLen=$,this.buffer=new Uint8Array(V),this.buffer32=y0(this.buffer)}update(V){$V(this),V=p0(V),j0(V);let{blockLen:$,buffer:Q,buffer32:Z}=this,J=V.length,I=V.byteOffset,W=V.buffer;for(let Y=0;Y<J;){if(this.pos===$)t(Z),this.compress(Z,0,!1),t(Z),this.pos=0;let X=Math.min($-this.pos,J-Y),G=I+Y;if(X===$&&!(G%4)&&Y+X<J){let K=new Uint32Array(W,G,Math.floor((J-Y)/4));t(K);for(let R=0;Y+$<J;R+=Z.length,Y+=$)this.length+=$,this.compress(K,R,!1);t(K);continue}Q.set(V.subarray(Y,Y+X),this.pos),this.pos+=X,this.length+=X,Y+=X}return this}digestInto(V){$V(this),AV(V,this);let{pos:$,buffer32:Q}=this;this.finished=!0,b0(this.buffer.subarray($)),t(Q),this.compress(Q,0,!0),t(Q);let Z=y0(V);this.get().forEach((J,I)=>Z[I]=_Q(J))}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Q=V.slice(0,$);return this.destroy(),Q}_cloneInto(V){let{buffer:$,length:Q,finished:Z,destroyed:J,outputLen:I,pos:W}=this;return V||(V=new this.constructor({dkLen:I})),V.set(...this.get()),V.buffer.set($),V.destroyed=J,V.finished=Z,V.length=Q,V.pos=W,V.outputLen=I,V}clone(){return this._cloneInto()}}function N$(V,$,Q,Z,J,I,W,Y,X,G,K,R,N,z,U,M,H,q,P,T){let F=0;for(let A=0;A<Z;A++)({a:J,b:X,c:N,d:H}=U0(J,X,N,H,Q[$+V[F++]])),{a:J,b:X,c:N,d:H}=F0(J,X,N,H,Q[$+V[F++]]),{a:I,b:G,c:z,d:q}=U0(I,G,z,q,Q[$+V[F++]]),{a:I,b:G,c:z,d:q}=F0(I,G,z,q,Q[$+V[F++]]),{a:W,b:K,c:U,d:P}=U0(W,K,U,P,Q[$+V[F++]]),{a:W,b:K,c:U,d:P}=F0(W,K,U,P,Q[$+V[F++]]),{a:Y,b:R,c:M,d:T}=U0(Y,R,M,T,Q[$+V[F++]]),{a:Y,b:R,c:M,d:T}=F0(Y,R,M,T,Q[$+V[F++]]),{a:J,b:G,c:U,d:T}=U0(J,G,U,T,Q[$+V[F++]]),{a:J,b:G,c:U,d:T}=F0(J,G,U,T,Q[$+V[F++]]),{a:I,b:K,c:M,d:H}=U0(I,K,M,H,Q[$+V[F++]]),{a:I,b:K,c:M,d:H}=F0(I,K,M,H,Q[$+V[F++]]),{a:W,b:R,c:N,d:q}=U0(W,R,N,q,Q[$+V[F++]]),{a:W,b:R,c:N,d:q}=F0(W,R,N,q,Q[$+V[F++]]),{a:Y,b:X,c:z,d:P}=U0(Y,X,z,P,Q[$+V[F++]]),{a:Y,b:X,c:z,d:P}=F0(Y,X,z,P,Q[$+V[F++]]);return{v0:J,v1:I,v2:W,v3:Y,v4:X,v5:G,v6:K,v7:R,v8:N,v9:z,v10:U,v11:M,v12:H,v13:q,v14:P,v15:T}}var w0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},O0=jQ.slice(),SQ=(()=>{let V=Array.from({length:16},(Z,J)=>J),$=(Z)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((J)=>Z[J]),Q=[];for(let Z=0,J=V;Z<7;Z++,J=$(J))Q.push(...J);return Uint8Array.from(Q)})();class z$ extends M${constructor(V={},$=0){super(64,V.dkLen===void 0?32:V.dkLen);this.chunkPos=0,this.chunksDone=0,this.flags=0,this.stack=[],this.posOut=0,this.bufferOut32=new Uint32Array(16),this.chunkOut=0,this.enableXOF=!0;let{key:Q,context:Z}=V,J=Z!==void 0;if(Q!==void 0){if(J)throw Error('Only "key" or "context" can be specified at same time');let I=p0(Q).slice();j0(I,32),this.IV=y0(I),t(this.IV),this.flags=$|w0.KEYED_HASH}else if(J){let I=p0(Z),W=new z$({dkLen:32},w0.DERIVE_KEY_CONTEXT).update(I).digest();this.IV=y0(W),t(this.IV),this.flags=$|w0.DERIVE_KEY_MATERIAL}else this.IV=O0.slice(),this.flags=$;this.state=this.IV.slice(),this.bufferOut=DQ(this.bufferOut32)}get(){return[]}set(){}b2Compress(V,$,Q,Z=0){let{state:J,pos:I}=this,{h:W,l:Y}=R$(BigInt(V),!0),{v0:X,v1:G,v2:K,v3:R,v4:N,v5:z,v6:U,v7:M,v8:H,v9:q,v10:P,v11:T,v12:F,v13:A,v14:j,v15:m}=N$(SQ,Z,Q,7,J[0],J[1],J[2],J[3],J[4],J[5],J[6],J[7],O0[0],O0[1],O0[2],O0[3],W,Y,I,$);J[0]=X^H,J[1]=G^q,J[2]=K^P,J[3]=R^T,J[4]=N^F,J[5]=z^A,J[6]=U^j,J[7]=M^m}compress(V,$=0,Q=!1){let Z=this.flags;if(!this.chunkPos)Z|=w0.CHUNK_START;if(this.chunkPos===15||Q)Z|=w0.CHUNK_END;if(!Q)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,Z,V,$),this.chunkPos+=1,this.chunkPos===16||Q){let J=this.state;this.state=this.IV.slice();for(let I,W=this.chunksDone+1;Q||!(W&1);W>>=1){if(!(I=this.stack.pop()))break;this.buffer32.set(I,0),this.buffer32.set(J,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|w0.PARENT,this.buffer32,0),J=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(J)}this.pos=0}_cloneInto(V){V=super._cloneInto(V);let{IV:$,flags:Q,state:Z,chunkPos:J,posOut:I,chunkOut:W,stack:Y,chunksDone:X}=this;return V.state.set(Z.slice()),V.stack=Y.map((G)=>Uint32Array.from(G)),V.IV.set($),V.flags=Q,V.chunkPos=J,V.chunksDone=X,V.posOut=I,V.chunkOut=W,V.enableXOF=this.enableXOF,V.bufferOut32.set(this.bufferOut32),V}destroy(){this.destroyed=!0,b0(this.state,this.buffer32,this.IV,this.bufferOut32),b0(...this.stack)}b2CompressOut(){let{state:V,pos:$,flags:Q,buffer32:Z,bufferOut32:J}=this,{h:I,l:W}=R$(BigInt(this.chunkOut++));t(Z);let{v0:Y,v1:X,v2:G,v3:K,v4:R,v5:N,v6:z,v7:U,v8:M,v9:H,v10:q,v11:P,v12:T,v13:F,v14:A,v15:j}=N$(SQ,0,Z,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],O0[0],O0[1],O0[2],O0[3],W,I,$,Q);J[0]=Y^M,J[1]=X^H,J[2]=G^q,J[3]=K^P,J[4]=R^T,J[5]=N^F,J[6]=z^A,J[7]=U^j,J[8]=V[0]^M,J[9]=V[1]^H,J[10]=V[2]^q,J[11]=V[3]^P,J[12]=V[4]^T,J[13]=V[5]^F,J[14]=V[6]^A,J[15]=V[7]^j,t(Z),t(J),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,b0(this.buffer.subarray(this.pos));let V=this.flags|w0.ROOT;if(this.stack.length)V|=w0.PARENT,t(this.buffer32),this.compress(this.buffer32,0,!0),t(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else V|=(!this.chunkPos?w0.CHUNK_START:0)|w0.CHUNK_END;this.flags=V,this.b2CompressOut()}writeInto(V){$V(this,!1),j0(V),this.finish();let{blockLen:$,bufferOut:Q}=this;for(let Z=0,J=V.length;Z<J;){if(this.posOut>=$)this.b2CompressOut();let I=Math.min($-this.posOut,J-Z);V.set(Q.subarray(this.posOut,this.posOut+I),Z),this.posOut+=I,Z+=I}return V}xofInto(V){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(V)}xof(V){return VV(V),this.xofInto(new Uint8Array(V))}digestInto(V){if(AV(V,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto(V),this.destroy(),V}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var EQ=LQ((V)=>new z$(V));var U$=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function xQ(V){let $=new Uint8Array(U$.length+32);return $.set(U$),$.set(V.subarray(0,32),U$.length),$}function kQ(V){return typeof V==="string"?new TextEncoder().encode(V):V}function r0(V){let $=new ArrayBuffer(V.byteLength);return new Uint8Array($).set(V),$}class F${verifyKeys=new Map;signKeys=new Map;async genRandomBytes(V){return DV(V)}async gen256BitSecureRandomSeed(){return DV(32)}async encryptXSalsa20Poly1305Combined(V,$){let Q=DV(24),J=K$($,Q).encrypt(V);return new Uint8Array([...Q,...J])}async decryptXSalsa20Poly1305Combined(V,$){let Q=V.slice(0,24),Z=V.slice(24);return K$($,Q).decrypt(Z)}async deriveEd25519KeyPair(V){let $=V,Q=xQ($),Z=await globalThis.crypto.subtle.importKey("pkcs8",r0(Q),{name:"Ed25519"},!0,["sign"]),J=await globalThis.crypto.subtle.exportKey("jwk",Z);if(typeof J.x!=="string")throw Error("Ed25519 JWK missing x");let I=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:J.x},{name:"Ed25519"},!0,["verify"]),W=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",I)),Y=new Uint8Array(64);return Y.set($,0),Y.set(W,32),this.signKeys.set(o($),Z),this.verifyKeys.set(o(W),I),{keyType:"ed25519",privateKey:Y,publicKey:W}}async importSignKey(V){let $=V.subarray(0,32),Q=o($),Z=this.signKeys.get(Q);if(Z)return Z;let J=xQ($),I=await globalThis.crypto.subtle.importKey("pkcs8",r0(J),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Q,I),I}async importVerifyKey(V){let $=o(V),Q=this.verifyKeys.get($);if(Q)return Q;let Z=await globalThis.crypto.subtle.importKey("raw",r0(V),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set($,Z),Z}async signEd25519(V,$){let Q=kQ(V),Z=await this.importSignKey($),J=await globalThis.crypto.subtle.sign({name:"Ed25519"},Z,r0(Q));return new Uint8Array(J)}async checkSigEd25519(V,$,Q){let Z=kQ($);try{let J=await this.importVerifyKey(Q);return await globalThis.crypto.subtle.verify({name:"Ed25519"},J,r0(V),r0(Z))}catch{return!1}}async blake3(V){return EQ(V)}}var nZ=new F$,J0=nZ;var m8=Symbol("EntityID");function fQ(V){return"type"in V}var S8=Symbol("MasterSeed"),E8=Symbol("DerivationSeed"),x8=Symbol("PublicKey"),k8=Symbol("PrivateKey"),f8=Symbol("HostSpecificKeyPair"),B8=Symbol("Hash");function yZ(V){if(!V)return!1;if(typeof V!=="object")return!1;if("body"in V===!1)return!1;if("type"in V===!1)return!1;return!0}function bZ(V){if(!V.bod||V.bod.length===0){let Z={off:V.off,ctr:V.ctr,eid:V.eid};return O(Z)}let $=uV(V.bod);if(yZ($)===!1)return console.warn("msg body invalid",$),w(14);let Q={off:V.off,ctr:V.ctr,eid:V.eid,gid:$.gid,pid:$.pid,type:$.type,body:$.body};return O(Q)}class LV{applier;emitter=new P0;clearer;onTypes;constructor(V,$,Q){this.applier=V;this.clearer=$,this.onTypes=Q}apply=async(V)=>{let $=[],Q=[];for(let W of V){let[Y,X]=bZ(W);if(Q.push(X),X!==0)continue;$.push(Y)}let{stats:Z,types:J}=await this.applier($),I=[];for(let W=0;W<V.length;W++){let Y=Q[W],X=Z[W];if(Y!==0){I.push(Y);continue}if(X!==0){I.push(X);continue}I.push(0)}for(let W of J)this.emitter.emit(W,null);if(J.size>0)this.onTypes?.(J);return I};clear=async()=>{let V=await this.clearer();if(V!==0)return V;return this.emitter.emitAll(null),V};notify=(V)=>{for(let $ of V)this.emitter.emit($,null)};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}var O$={apply:async function(V){return V.map(()=>0)},clear:async function(){return 0},notify:function(V){},on:function(V,$){},off:function(V,$){}};function q$(V){return new LV(($)=>V.apply($),()=>V.clear())}function jV(V,$){let Q=new f($.eid),[Z,J]=Q.readStruct(Q0);if(J!==0)return w(J);let I=new Date(Z.ts.getTime()+$.off);if(V!==void 0&&I<=V.updatedAt)return w(15);if(fQ($))return O({eid:$.eid,gid:$.gid,pid:$.pid,type:$.type,createdAt:Z.ts,updatedAt:I,ctr:$.ctr,body:$.body});else return O(void 0)}var pZ={getEnt:async()=>w(21),getEntities:async(V)=>w(21),countEntities:async()=>w(21),apply:async(V)=>({stats:V.map(()=>21),types:new Set}),clear:async()=>21};var n="entities",mV="entity_type_created_at",H$="entity_type_updated_at",P$="entity_type_group_id",C$="entity_type_parent_id";function rZ(V){let $={bod:V.body,crd:V.createdAt,...V.ctr!==0?{ctr:V.ctr}:{},eid:g(V.eid),gid:V.gid,pid:V.pid?g(V.pid):void 0,typ:V.type,upd:V.updatedAt};if($.gid===void 0)delete $.gid;if($.pid===void 0)delete $.pid;if($.ctr===void 0)delete $.ctr;return $}function l0(V){return{body:V.bod,createdAt:V.crd,updatedAt:V.upd,ctr:V.ctr??0,type:V.typ,eid:Z0(V.eid),gid:V.gid,pid:V.pid?Z0(V.pid):void 0}}class D${db;async init(){this.db=await new Promise((V,$)=>{let Q=indexedDB.open("db",11);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!J)throw Error("Transaction is null during upgrade");if(!Z.objectStoreNames.contains(n))Z.createObjectStore(n,{keyPath:"eid",autoIncrement:!1});let I=J.objectStore(n);if(!I.indexNames.contains(mV))I.createIndex(mV,["typ","crd"],{unique:!1});if(!I.indexNames.contains(H$))I.createIndex(H$,["typ","upd"],{unique:!1});if(!I.indexNames.contains(P$))I.createIndex(P$,["typ","gid"],{unique:!1});if(!I.indexNames.contains(C$))I.createIndex(C$,["typ","pid"],{unique:!1})},Q.onsuccess=()=>V(Q.result),Q.onerror=()=>$(Q.error)})}apply=async(V)=>{let $=new Set;if(!this.db)return{stats:V.map(()=>16),types:$};let Q=this.db.transaction(n,"readwrite"),Z=Q.objectStore(n);return new Promise((J)=>{let I=Array(V.length).fill(0);if(V.length<1){J({stats:[],types:$});return}Q.oncomplete=()=>{J({stats:I,types:$})},Q.onerror=()=>{for(let Y=0;Y<I.length;Y++)if(I[Y]===void 0)I[Y]=18;J({stats:I,types:$})};let W=new Map;for(let Y=0;Y<V.length;Y++){let X=V[Y],G=g(X.eid),K={op:X,index:Y},R=W.get(G);if(R)R.push(K);else W.set(G,[K])}for(let[Y,X]of W){if(X.length<1)continue;let G=Z.get(Y);G.onsuccess=()=>{let K=G.result,R=K?l0(K):void 0;for(let{op:N,index:z}of X){let[U,M]=jV(R,N);if(M!==0){I[z]=M;continue}if(U)$.add(U.type);else if(R)$.add(R.type);R=U}if(R){let N=rZ(R),z=Z.put(N);z.onerror=(U)=>{U.preventDefault();for(let{index:M}of X)I[M]=18}}else{let N=Z.delete(Y);N.onerror=()=>{for(let{index:z}of X)I[z]=18}}},G.onerror=()=>{for(let{index:K}of X)I[K]=18}}})};async clear(){if(!this.db)return 16;let V=this.db.transaction(n,"readwrite"),$=V.objectStore(n);return new Promise((Q)=>{V.oncomplete=()=>Q(0),V.onerror=()=>Q(18),$.clear()})}async getEnt(V){if(!this.db)return w(16);let $=g(V),Z=this.db.transaction(n,"readonly").objectStore(n);return new Promise((J)=>{let I=Z.get($);I.onsuccess=()=>{let W=I.result;if(!W)J(O(void 0));else{let Y=l0(W);J(O(Y))}},I.onerror=()=>J(w(18))})}async getAllOfTypeUpdatedBetween(V,$,Q){if(!this.db)return w(16);let J=this.db.transaction(n,"readonly").objectStore(n).index(H$);return new Promise((I)=>{let W=J.getAll(IDBKeyRange.bound([V,$],[V,Q]));W.onsuccess=()=>{let Y=W.result;I(O(Y.map(l0)))},W.onerror=()=>I(w(18))})}async getGroupMembers(V,$){if(!this.db)return w(16);let Z=this.db.transaction(n,"readonly").objectStore(n).index(P$);return new Promise((J)=>{let I=Z.getAll(IDBKeyRange.only([V,$]));I.onsuccess=()=>{let W=I.result;J(O(W.map(l0)))},I.onerror=()=>J(w(18))})}async getAllOfType(V){if(!this.db)return w(16);let Q=this.db.transaction(n,"readonly").objectStore(n).index(mV);return new Promise((Z)=>{let J=Q.getAll(IDBKeyRange.bound([V],[V,[]]));J.onsuccess=()=>{let I=J.result;Z(O(I.map(l0)))},J.onerror=()=>Z(w(18))})}async getAllEntities(V){if(!this.db)return w(16);if("pid"in V){let $=g(V.pid),Z=this.db.transaction(n,"readonly").objectStore(n).index(C$);return new Promise((J)=>{let I=Z.getAll(IDBKeyRange.only([V.type,$]));I.onsuccess=()=>{let Y=I.result.map(l0);J(O(Y))},I.onerror=()=>J(w(18))})}else if("gid"in V)return await this.getGroupMembers(V.type,V.gid);else if("updatedBetween"in V)return await this.getAllOfTypeUpdatedBetween(V.type,V.updatedBetween.start,V.updatedBetween.end);return await this.getAllOfType(V.type)}async getEntities(V){let[$,Q]=await this.getAllEntities(V);if(Q!==0)return w(Q);return O($)}async countEntities({type:V}){if(!this.db)return w(16);let Q=this.db.transaction(n,"readonly").objectStore(n).index(mV);return new Promise((Z)=>{let J=IDBKeyRange.bound([V],[V,[]]),I=Q.count(J);I.onsuccess=()=>Z(O(I.result)),I.onerror=()=>Z(w(18))})}}async function T$(){let V=new D$;return await V.init(),V}class BQ{ents=new Map;constructor(V=[]){for(let $ of V){let Q=g($.eid);this.ents.set(Q,$)}}async apply(V){let $=new Set,Q=[];for(let Z of V){let J=g(Z.eid),I=this.ents.get(J),[W,Y]=jV(I,Z);if(Y!==0){Q.push(Y);continue}if(W)$.add(W.type);else if(I)$.add(I.type);if(W)this.ents.set(J,W);else this.ents.delete(J);Q.push(0)}return{stats:Q,types:$}}async clear(){return this.ents.clear(),0}async getEnt(V){let $=g(V),Q=this.ents.get($);return O(Q)}async getAllEntities({type:V,gid:$,pid:Q,updatedBetween:Z}){let J=[];if(Q!==void 0){for(let I of this.ents.values())if(I.type===V&&I.pid&&X0(I.pid,Q))J.push(I)}else if($!==void 0){for(let I of this.ents.values())if(I.type===V&&(typeof I.gid==="string"&&I.gid===$))J.push(I)}else if(Z!==void 0){for(let I of this.ents.values())if(I.type===V&&I.updatedAt>=Z.start&&I.updatedAt<=Z.end)J.push(I)}else for(let I of this.ents.values())if(I.type===V)J.push(I);return O(J)}async getEntities(V){let[$,Q]=await this.getAllEntities(V);if(Q!==0)return w(Q);return O($)}async countEntities({type:V}){let $=0;for(let Q of this.ents.values())if(Q.type===V)$+=1;return O($)}}import{useEffect as fV,useState as x$}from"react";class A${db;constructor(V){this.db=V}async enq(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(I0,"readwrite"),Z=Q.objectStore(I0);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=`${W.host}:${W.seq}`;Z.put(W,Y)}})}async deq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(I0,"readwrite"),J=Z.objectStore(I0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=`${V}:${Y}`;J.delete(X)}})}async list(){let $=this.db.transaction(I0,"readonly").objectStore(I0);return new Promise((Q,Z)=>{let J=$.getAll();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async count(){let $=this.db.transaction(I0,"readonly").objectStore(I0);return new Promise((Q,Z)=>{let J=$.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(I0,"readwrite"),$=V.objectStore(I0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}function gQ(V){return{label:V.label,handle:new URL(V.handle),idx:V.idx,lastSeq:V.lastSeq||0,clockOffset:V.clockOffset,subscription:V.subscription}}class _${db;constructor(V){this.db=V}async add(V){return this.put(V)}async put(V){let $={...V,handle:V.handle.toString(),lastSeq:V.lastSeq??0},Q=this.db.transaction(e,"readwrite"),Z=Q.objectStore(e);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error),Z.put($)})}async touch(V,$){let Q=this.db.transaction(e,"readwrite"),Z=Q.objectStore(e);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)return;let X=Y.lastSeq||0;if($<=X)return;Z.put({...Y,lastSeq:$})}})}async get(V){let Q=this.db.transaction(e,"readonly").objectStore(e);return new Promise((Z,J)=>{let I=Q.get(V);I.onsuccess=()=>{let W=I.result;if(!W)Z(void 0);else Z(gQ(W))},I.onerror=()=>J(I.error)})}async set(V,$){let Q=await this.get(V);if(!Q)return 13;try{return await this.put({...Q,...$}),0}catch{return 18}}async del(V){let $=this.db.transaction(e,"readwrite"),Q=$.objectStore(e);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),Q.delete(V)})}async list(){let $=this.db.transaction(e,"readonly").objectStore(e);return new Promise((Q,Z)=>{let J=$.getAll();J.onsuccess=()=>{let I=J.result;Q(I.map(gQ))},J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(e,"readwrite"),$=V.objectStore(e);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}function lZ(V){return V===!0||V==="t"}function m0(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld===void 0?!1:lZ(V.apld)}}function L$(V){return m0(V).apld===!1}async function R0(V,$,Q){let Z=m0($),J=Z.body?.length??0,I;if(Z.body&&J>0)I=await Q.blake3(Z.body);let W={eid:Z.eid,off:Z.off??0,ctr:Z.ctr??0,len:J,hsh:I};return{hash:V,head:W,body:Z.body,applied:Z.apld}}function iQ(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld?"t":"f"}}class j${crypto;db;constructor(V,$){this.crypto=$;this.db=V}async add(V){let $=this.db.transaction(u,"readwrite"),Q=$.objectStore(u);return new Promise((Z)=>{if(V.length===0){Z([]);return}let J=Array(V.length).fill(0);$.oncomplete=()=>Z(J),$.onerror=()=>{for(let I=0;I<J.length;I++)J[I]=18;Z(J)};for(let I=0;I<V.length;I++){let{key:W,data:Y}=V[I],X=g(W),G=Q.put(iQ(Y),X);G.onerror=(K)=>{K.preventDefault(),J[I]=18}}})}async del(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=g(W);Z.delete(Y)}})}async get(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let I=g(V),W=Q.get(I);W.onsuccess=async()=>{let Y=W.result;if(Y)Z(await R0(V,Y,this.crypto));else Z(void 0)},W.onerror=()=>J(W.error)})}async has(V){return await this.get(V)!==void 0}async list(){let $=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Q,Z)=>{let J=[],I=$.openCursor();I.onsuccess=async(W)=>{let Y=W.target.result;if(Y){let{key:X,value:G}=Y,K=Z0(X),R=await R0(K,G,this.crypto);J.push(R),Y.continue()}else Q(J)},I.onerror=()=>Z(I.error)})}async last(V){let Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let I,W=Q.openCursor();W.onsuccess=async(Y)=>{let X=Y.target.result;if(X){let{key:G,value:K}=X;if(X0(V,K.eid)){if(!I||(K.ctr??0)>(I.data.ctr??0)||(K.ctr??0)===(I.data.ctr??0)&&(K.off??0)>(I.data.off??0))I={key:G,data:K}}X.continue()}else if(I){let G=Z0(I.key);Z(await R0(G,I.data,this.crypto))}else Z(void 0)},W.onerror=()=>J(W.error)})}async listUnapplied(){let Q=this.db.transaction(u,"readonly").objectStore(u).index(SV);return new Promise((Z,J)=>{let I=[],W=Q.openCursor(IDBKeyRange.only("f"));W.onsuccess=(Y)=>{let X=Y.target.result;if(X){let{primaryKey:G,value:K}=X;I.push({hash:Z0(G),data:K}),X.continue()}else Promise.all(I.map(({hash:G,data:K})=>R0(G,K,this.crypto))).then(Z).catch(J)},W.onerror=()=>J(W.error)})}async markApplied(V){let $=[...V];if($.length===0)return;let Q=this.db.transaction(u,"readwrite"),Z=Q.objectStore(u);return new Promise((J,I)=>{Q.oncomplete=()=>J(),Q.onerror=()=>I(Q.error);for(let W of $){let Y=g(W),X=Z.get(Y);X.onsuccess=()=>{let G=X.result;if(!G)return;let K=m0(G);Z.put(iQ({...K,apld:!0}),Y)},X.onerror=(G)=>{G.preventDefault()}}})}async wipe(){let V=this.db.transaction(u,"readwrite"),$=V.objectStore(u);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}class h0{seed;crypto;constructor(V,$){this.seed=V,this.crypto=$}async deriveFromKDM(V){let $=a0(this.seed,V);return await this.crypto.blake3($)}async derive(V,$=0){let Q=new TextEncoder().encode(V),Z=new Uint8Array(8);new DataView(Z.buffer).setBigUint64(0,BigInt($),!1);let J=a0(Q,Z);return await this.deriveFromKDM(J)}}class m${enclave;db;constructor(V){this.db=V}async save(V){let $=o(V),Q=this.db.transaction(q0,"readwrite"),Z=Q.objectStore(q0);return new Promise((J,I)=>{Q.oncomplete=()=>{this.enclave=new h0(V,J0),J(this.enclave)},Q.onerror=()=>I(Q.error),Z.put($,"seed")})}async load(){if(this.enclave)return this.enclave;let $=this.db.transaction(q0,"readonly").objectStore(q0);return new Promise((Q,Z)=>{let J=$.get("seed");J.onsuccess=()=>{let I=J.result;if(!I)Q(void 0);else{let W=A0(I);this.enclave=new h0(W,J0),Q(this.enclave)}},J.onerror=()=>Z(J.error)})}async wipe(){this.enclave=void 0;let V=this.db.transaction(q0,"readwrite"),$=V.objectStore(q0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.delete("seed")})}}class S${db;constructor(V){this.db=V}async enq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=o(Y);J.put({host:V,hash:X})}})}async deq(V,$){let Q=[...$];if(Q.length===0)return;let Z=this.db.transaction(W0,"readwrite"),J=Z.objectStore(W0);return new Promise((I,W)=>{Z.oncomplete=()=>I(),Z.onerror=()=>W(Z.error);for(let Y of Q){let X=o(Y);J.delete([V,X])}})}async list(V){let Q=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Z,J)=>{let I=Q.getAll();I.onsuccess=()=>{let Y=I.result.filter((X)=>X.host===V).map((X)=>X.hash);Z(Y.map((X)=>A0(X)))},I.onerror=()=>J(I.error)})}async count(){let $=this.db.transaction(W0,"readonly").objectStore(W0);return new Promise((Q,Z)=>{let J=$.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let V=this.db.transaction(W0,"readwrite"),$=V.objectStore(W0);return new Promise((Q,Z)=>{V.oncomplete=()=>Q(),V.onerror=()=>Z(V.error),$.clear()})}}var q0="seedMeta",e="hosts",W0="uploadQueue",I0="downloadQueue",u="messages",SV="apld",hZ=3;class E${seed;hosts;uploads;downloads;messages;db;constructor(V,$){this.db=V,this.seed=new m$(V),this.hosts=new _$(V),this.uploads=new S$(V),this.downloads=new A$(V),this.messages=new j$(V,$)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function cZ(){return new Promise((V,$)=>{let Q=indexedDB.open("diplomatic-store-db",hZ);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!Z.objectStoreNames.contains(q0))Z.createObjectStore(q0);if(!Z.objectStoreNames.contains(e))Z.createObjectStore(e,{keyPath:"label"});if(!Z.objectStoreNames.contains(W0))Z.createObjectStore(W0,{keyPath:["host","hash"]});if(!Z.objectStoreNames.contains(I0))Z.createObjectStore(I0);let I;if(!Z.objectStoreNames.contains(u))I=Z.createObjectStore(u);else{if(!J)throw Error("missing upgrade transaction for messages store");I=J.objectStore(u)}if(!I.indexNames.contains(SV))I.createIndex(SV,"apld",{unique:!1})},Q.onsuccess=()=>V(Q.result),Q.onerror=()=>$(Q.error)})}async function EV(V){let $=await cZ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new E$($,V)}function vQ(V){if(!V||typeof V!=="object")return!1;if(!("kind"in V))return!1;return typeof V.kind==="string"}function uQ(V){if(typeof V!=="number")return;return V}var H0="[DIPLOMATIC]";class ZV{worker;state;local;nextId=1;pending=new Map;ready;resolveReady;rejectReady;scheduledSync;cachedClientState={hasSeed:!1,hasHost:!1,connected:!1};cachedXferState={numUploads:0,numDownloads:0,progress:n0};clientState;xferState;constructor(V,$,Q,Z,J){this.worker=V,this.state=$,this.clientState=new G0(async()=>this.cachedClientState),this.xferState=new G0(async()=>this.cachedXferState),this.scheduledSync=new t0(J,async()=>{try{await this.request({id:this.allocId(),op:"sync"})}catch(I){console.error(`${H0} worker sync after local write failed`,I)}}),this.local=new _0(Z,$,Q,()=>{throw Error(`${H0} local writer has no transport (use worker for network)`)},J0,!0,void 0,void 0,()=>{this.scheduledSync.schedule()}),this.ready=new Promise((I,W)=>{this.resolveReady=I,this.rejectReady=W}),this.worker.onmessage=(I)=>{this.onMessage(I.data)},this.worker.onerror=(I)=>{console.error(`${H0} worker error`,I),this.failReady(Error(`${H0} worker failed to load`))},this.worker.onmessageerror=()=>{this.failReady(Error(`${H0} worker message error`))}}failReady(V){let $=this.rejectReady;if(this.rejectReady=void 0,this.resolveReady=void 0,$)$(V)}async flushScheduledSync(){await this.scheduledSync.flush()}static async connect(V,$,Q){let Z=Q.clock??new N0,J=Q.syncDebounceMs??OV,I=new ZV(Q.worker,V,$,Z,J),W=Q.readyTimeoutMs??15000,Y;try{let X=I.probeReady();await Promise.race([I.ready,X,new Promise((G,K)=>{Y=setTimeout(()=>{K(Error(`${H0} worker ready timeout after ${W}ms`))},W)})]),X.catch(()=>{})}catch(X){throw I.terminate(),X}finally{if(Y!==void 0)clearTimeout(Y)}return I}markReady(){let V=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V()}probeReady(){return new Promise((V,$)=>{let Q=this.allocId();this.pending.set(Q,{resolve:(Z)=>{if(Z==="pong"){this.markReady(),V();return}$(Error(`${H0} worker probe ping failed`))},reject:$}),this.worker.postMessage({id:Q,op:"ping"})})}async ping(){if(await this.ready,await this.request({id:this.allocId(),op:"ping"})!=="pong")throw Error(`${H0} worker ping failed`)}terminate(){this.scheduledSync.cancel(),this.worker.terminate();for(let[,V]of this.pending)V.reject(Error(`${H0} worker terminated`));this.pending.clear()}onMessage(V){if(!vQ(V))return;let $=V;switch($.kind){case"ready":{this.markReady();return}case"clientState":{this.cachedClientState=$.state,this.clientState.emit();return}case"xferState":{this.cachedXferState=$.state,this.xferState.emit();return}case"dirty":{this.state.notify($.types);return}case"wiped":{this.state.clear();return}case"reply":{let Q=this.pending.get($.id);if(!Q)return;if(this.pending.delete($.id),$.ok)Q.resolve($.result);else Q.reject(new xV($.status));return}default:return}}allocId(){let V=this.nextId;return this.nextId+=1,V}request(V,$){return new Promise((Q,Z)=>{if(this.pending.set(V.id,{resolve:Q,reject:Z}),$&&$.length>0)this.worker.postMessage(V,$);else this.worker.postMessage(V)})}async requestStatus(V,$){try{let Q=await this.request(V,$),Z=uQ(Q);if(Z!==void 0)return Z;return 0}catch(Q){if(Q instanceof xV)return Q.status;return 12}}serializeHost(V){return{handle:V.handle.href,label:V.label,idx:V.idx??0}}async setSeed(V){await this.ready,await this.local.setSeed(V);let $=V.slice();await this.request({id:this.allocId(),op:"setSeed",seed:$},[$.buffer])}async link(V,$=!0){await this.ready,await this.local.link(V,!1),await this.request({id:this.allocId(),op:"link",host:this.serializeHost(V),connect:$})}async unlink(V){await this.ready,await this.local.unlink(V),await this.request({id:this.allocId(),op:"unlink",label:V})}async hosts(){return await this.ready,this.local.hosts()}async connect(V=!0,$=!0){await this.ready,await this.request({id:this.allocId(),op:"connect",listen:V,sync:$})}async disconnect(){await this.ready,await this.request({id:this.allocId(),op:"disconnect"})}async insertRaw(V){return await this.ready,this.local.insertRaw(V)}async upsertRaw(V,$,Q){return await this.ready,this.local.upsertRaw(V,$,Q)}async insert(V){return await this.ready,this.local.insert(V)}async upsert(V,$){return await this.ready,this.local.upsert(V,$)}async delete(V){return await this.ready,this.local.delete(V)}async genEID(V){return await this.ready,this.local.genEID(V)}async sync(){return await this.ready,this.requestStatus({id:this.allocId(),op:"sync"})}async wipe(){await this.ready,await this.request({id:this.allocId(),op:"wipe"})}async import(V){await this.ready;let $=new Uint8Array(await V.arrayBuffer());return this.requestStatus({id:this.allocId(),op:"import",bytes:$},[$.buffer])}async export(V,$){await this.ready;try{let Q=await this.request({id:this.allocId(),op:"export"});if(!(Q instanceof Uint8Array))return 12;let Z=new Blob([Q.slice()]);return qV(Z,V),0}catch(Q){if(Q instanceof xV)return Q.status;return 12}}}class xV extends Error{status;constructor(V){super(`WorkerReplyError: ${_[V]}`);this.status=V;this.name="WorkerReplyError"}}var S0="[DIPLOMATIC]";async function kV(V){let $=V.clock??new N0;if(V.worker!==void 0&&dZ(V)!==void 0)throw Error(`${S0} worker path requires IndexedDB on both sides; do not pass store (got a custom store)`);if(V.worker===void 0){console.info(`${S0} sync on main thread `+"(no worker — app did not request a worker)");let J=await nQ(V.store);return oZ($,V.state,J)}if(typeof Worker>"u")throw Error(`${S0} worker was provided but Worker API is unavailable`);let Q=await nQ(void 0);console.info(`${S0} attaching app-provided sync worker…`);let Z=await ZV.connect(V.state,Q,{worker:V.worker,readyTimeoutMs:V.readyTimeoutMs,clock:$,syncDebounceMs:V.syncDebounceMs});return await Z.ping(),console.info(`${S0} sync worker active (network + EntDB writes off main; local mutates on main; dirty signals only)`),{client:Z,mode:"worker",dispose:()=>{console.info(`${S0} terminating sync worker`),Z.terminate()}}}function dZ(V){if("store"in V)return V.store;return}async function oZ(V,$,Q){let Z=new _0(V,$,Q,NV,J0);return{client:Z,mode:"main",dispose:()=>{Z.disconnect()}}}async function nQ(V){if(V!==void 0)return V;if(typeof indexedDB>"u")throw Error(`${S0} IndexedDB is unavailable; pass store explicitly (e.g. new MemoryStore(crypto))`);return EV(J0)}function aZ(V){let[$,Q]=x$();return fV(()=>{async function Z(){let I=await V.clientState.get();Q(I)}let J=V.clientState.listen(Z);return Z(),()=>{J()}},[V]),$}function sZ(V){let[$,Q]=x$();return fV(()=>{async function Z(){let I=await V.xferState.get();Q(I)}let J=V.xferState.listen(Z);return Z(),()=>{J()}},[V]),$}function tZ(V){fV(()=>{async function $(){try{await V.connect(),await V.sync()}catch(I){console.error("reconnectAndSync failed",I)}}function Q(){$()}function Z(){if(typeof document<"u"&&document.visibilityState==="visible")$()}function J(){$()}if(globalThis.addEventListener("online",Q),typeof document<"u")document.addEventListener("visibilitychange",Z);return globalThis.addEventListener("focus",J),globalThis.addEventListener("pageshow",J),()=>{if(globalThis.removeEventListener("online",Q),typeof document<"u")document.removeEventListener("visibilitychange",Z);globalThis.removeEventListener("focus",J),globalThis.removeEventListener("pageshow",J)}},[V])}function eZ(V={}){let $=V.clock??new N0,{seed:Q,host:Z,readyTimeoutMs:J}=V,I=V.worker,W="store"in V?V.store:void 0,[Y,X]=x$({stateMgr:O$});return fV(()=>{let G=!1,K;return(async()=>{let R=await T$();if(G)return;let N=q$(R),z=I!==void 0?await kV({state:N,clock:$,worker:I,readyTimeoutMs:J}):await kV({state:N,clock:$,store:W,readyTimeoutMs:J});if(G){z.dispose();return}K=z.dispose;let{client:U,mode:M}=z;if(Q)await U.setSeed(Q);if(Z)await U.link(Z);if(G){K();return}X({client:U,entDB:R,stateMgr:N,mode:M,error:void 0})})().catch((R)=>{let N=R instanceof Error?R:Error(String(R));if(console.error("[DIPLOMATIC] useClient init failed",N),!G)X((z)=>({...z,client:void 0,error:N}))}),()=>{G=!0,K?.()}},[$,Q,Z,I,W,J]),Y}import{use as VJ,useEffect as yQ,useRef as $J,useState as QJ}from"react";function bQ(V,$,Q){let[Z,J]=QJ();return yQ(()=>{async function I(){let W=await Q();J(W)}return I(),V.on($,I),()=>{V.off($,I)}},[V,$,Q]),Z}function ZJ(V,$,Q){let Z=$J(Q());return yQ(()=>{async function J(){Z.current=Q()}return V.on($,J),()=>{V.off($,J)}},[V,$,Q]),VJ(Z.current)}function pQ(V,$){return`${V}:${$}`}class k${queue=new Map;async enq(V){for(let $ of V){let Q=pQ($.host,$.seq);this.queue.set(Q,$)}}async deq(V,$){for(let Q of $){let Z=pQ(V,Q);this.queue.delete(Z)}}async list(){let V=[];for(let $ of this.queue.values())V.push($);return V}async count(){return this.queue.size}async wipe(){this.queue.clear()}}class f${hosts=new Map;async add(V){let $={...V,lastSeq:0};this.hosts.set(V.label,$)}async touch(V,$){let Q=this.hosts.get(V);if(!Q||$<=Q.lastSeq)return;this.hosts.set(V,{...Q,lastSeq:$})}async get(V){return this.hosts.get(V)}async set(V,$){let Q=this.hosts.get(V);if(!Q)return 13;return this.hosts.set(V,{...Q,...$}),0}async del(V){this.hosts.delete(V)}async list(){return this.hosts.values()}async wipe(){this.hosts.clear()}}class B${crypto;messages=new Map;constructor(V){this.crypto=V}async add(V){let $=[];for(let{key:Q,data:Z}of V)this.messages.set(g(Q),Z),$.push(0);return $}async del(V){for(let $ of V)this.messages.delete(g($))}async get(V){let $=this.messages.get(g(V));if($)return await R0(V,$,this.crypto);return}async has(V){return this.messages.has(g(V))}async list(){let V=Array.from(this.messages.entries());return await Promise.all(V.map(([Q,Z])=>{let J=Z0(Q);return R0(J,Z,this.crypto)}))}async last(V){let $;for(let[Q,Z]of this.messages){if(X0(V,Z.eid)===!1)continue;let J=Z0(Q);if($===void 0)$={hash:J,data:Z};else if((Z.ctr??0)>($.data.ctr??0)||(Z.ctr??0)===($.data.ctr??0)&&(Z.off??0)>($.data.off??0))$={hash:J,data:Z}}if($)return await R0($.hash,$.data,this.crypto);return}async listUnapplied(){let V=[];for(let[$,Q]of this.messages){if(!L$(Q))continue;let Z=Z0($);V.push(await R0(Z,Q,this.crypto))}return V}async markApplied(V){for(let $ of V){let Q=g($),Z=this.messages.get(Q);if(!Z)continue;this.messages.set(Q,{...m0(Z),apld:!0})}}async wipe(){this.messages.clear()}}class g${enclave;async save(V){return this.enclave=new h0(V,J0),this.enclave}async load(){return this.enclave}async wipe(){this.enclave=void 0}}class i${queue=new Map;async enq(V,$){let Q=this.queue.get(V)||new Set;this.queue.set(V,Q);for(let Z of $)Q.add(o(Z))}async deq(V,$){let Q=this.queue.get(V);if(Q)for(let Z of $)Q.delete(o(Z))}async list(V){let $=this.queue.get(V);if(!$)return[];let Q=[];for(let Z of $)Q.push(A0(Z));return Q}async count(){let V=0;for(let $ of this.queue.values())V+=$.size;return V}async wipe(){this.queue.clear()}}class rQ{seed=new g$;hosts=new f$;uploads=new i$;downloads=new k$;messages;constructor(V){this.messages=new B$(V)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}class lQ{singletonType;latest;latestOff=-1;emitter=new P0;constructor(V){this.singletonType=V}async apply(V){for(let $ of V){let Q=new f($.eid),[Z,J]=Q.readStruct(Q0);if(J!==0)continue;let I=new x;I.writeVarString(this.singletonType);let W=I.result();if(Z.id.length===W.length&&Z.id.every((Y,X)=>Y===W[X])){if(this.latest===void 0||$.off>this.latestOff)this.latestOff=$.off,this.latest=$.bod,this.emitter.emit(this.singletonType,null)}}return V.map(()=>0)}clear=async()=>{return this.latest=void 0,this.latestOff=-1,this.emitter.emit(this.singletonType,null),0};notify=(V)=>{for(let $ of V)if($===this.singletonType)this.emitter.emit(this.singletonType,null)};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}async function bw(V,$){let Q=await EV(J0),Z=new _0(new N0,V,Q,NV,J0);return{client:Z,setSeed:async(I)=>{let W=A0(I);await Q.seed.save(W),await Q.hosts.add({handle:$,label:"host",idx:0}),await Z.connect()}}}export{tZ as useSyncOnResume,ZJ as useStateWatcherSuspense,bQ as useStateWatcher,sZ as useClientXferState,aZ as useClientState,eZ as useClient,eV as shouldEmitItemProgress,EV as openIDBStore,T$ as openEntIDB,kV as openDiplomaticClient,O$ as nullStateManager,pZ as nullEntDB,m0 as normalizeStoredMessageData,L$ as isPendingApply,n0 as idleProgress,A0 as htob,NV as hostHTTPTransport,bw as genWebClient,OZ as genSingletonEID,q$ as entStateManager,Q0 as eidCodec,e0 as defaultPeekProgressEvery,J0 as crypto,o as btoh,ZV as WorkerClient,P0 as TypedEventEmitter,_0 as SyncClient,_ as Status,LV as StateManager,lQ as SingletonStateManager,rQ as MemoryStore,E$ as IDBStore,oV as HTTPTransport,D$ as EntIDB,BQ as EntDBMemory,x as Encoder,f as Decoder,N0 as Clock};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run `fn` over items with at most `concurrency` in flight.
|
|
3
|
+
* Results are returned in input order (not completion order).
|
|
4
|
+
* If `concurrency` < 1, behaves as 1 (serial).
|
|
5
|
+
*/
|
|
6
|
+
export declare function mapPool<T, R>(items: readonly T[], concurrency: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
|
package/dist/web/sync.d.ts
CHANGED
|
@@ -9,6 +9,11 @@ import { IDownloadMessage, IHostRow, IMsgParts, IStore, type IStoredMessageWrite
|
|
|
9
9
|
* payloads (e.g. media) should raise maxPushBytes / maxPullBytes. */
|
|
10
10
|
export declare const defaultMaxPushBytes: number;
|
|
11
11
|
export declare const defaultMaxPullBytes: number;
|
|
12
|
+
/**
|
|
13
|
+
* Concurrent peek-item crypto (sig verify + head open + head hash).
|
|
14
|
+
* WebCrypto Ed25519 verifies pipeline better when overlapped.
|
|
15
|
+
*/
|
|
16
|
+
export declare const defaultPeekConcurrency = 64;
|
|
12
17
|
/** Pull result held in memory until open (not durable). */
|
|
13
18
|
export type IPulled = {
|
|
14
19
|
dl: IDownloadMessage;
|
|
@@ -30,6 +35,11 @@ export interface ISyncParams<Handle extends HostHandle> {
|
|
|
30
35
|
onProgress?: ProgressFn;
|
|
31
36
|
/** Peek progress stride in heads (default `defaultPeekProgressEvery`). */
|
|
32
37
|
peekProgressEvery?: number;
|
|
38
|
+
/**
|
|
39
|
+
* Max concurrent peek-item crypto ops (verify + head decrypt + blake3).
|
|
40
|
+
* Default `defaultPeekConcurrency`. Set 1 for fully serial.
|
|
41
|
+
*/
|
|
42
|
+
peekConcurrency?: number;
|
|
33
43
|
}
|
|
34
44
|
/** Push one batch of sealed bags; deq successes; advance lastSeq from store. */
|
|
35
45
|
export declare function pushBatch<Handle extends HostHandle>(conn: Pick<DiplomaticClientAPI<Handle>, "push">, store: IStore<Handle>, hostLabel: string, bags: IBag[], hashes: Hash[]): Promise<Status>;
|
|
@@ -46,7 +56,7 @@ export type IOpened = {
|
|
|
46
56
|
*/
|
|
47
57
|
export declare function openPulled<Handle extends HostHandle>(store: IStore<Handle>, enclave: Enclave, crypto: ICrypto, items: IPulled[]): Promise<ValStat<IOpened>>;
|
|
48
58
|
/** Discover unseen bags and enqueue download work; advance host lastSeq. */
|
|
49
|
-
export declare function syncPeek<Handle extends HostHandle>({ conn, store, enclave, host, crypto, onProgress, peekProgressEvery, }: ISyncParams<Handle>): Promise<Status>;
|
|
59
|
+
export declare function syncPeek<Handle extends HostHandle>({ conn, store, enclave, host, crypto, onProgress, peekProgressEvery, peekConcurrency, }: ISyncParams<Handle>): Promise<Status>;
|
|
50
60
|
/** Seal and upload pending msgs; list once so concurrent enqs wait for next sync. */
|
|
51
61
|
export declare function syncPush<Handle extends HostHandle>({ conn, store, host, maxPushBytes, onProgress }: ISyncParams<Handle>): Promise<Status>;
|
|
52
62
|
/**
|
package/dist/web/worker.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var F0=64;var O$=32,U0=8;var a0=32;var H$=30000,C$=512,j;((O)=>{O[O.Success=0]="Success";O[O.InvalidSignature=3]="InvalidSignature";O[O.ClockOutOfSync=4]="ClockOutOfSync";O[O.UserNotRegistered=5]="UserNotRegistered";O[O.ServerMisconfigured=6]="ServerMisconfigured";O[O.MissingBody=7]="MissingBody";O[O.ExtraBodyContent=8]="ExtraBodyContent";O[O.MissingParam=9]="MissingParam";O[O.InvalidParam=10]="InvalidParam";O[O.InvalidRequest=11]="InvalidRequest";O[O.InternalError=12]="InternalError";O[O.NotFound=13]="NotFound";O[O.InvalidMessage=14]="InvalidMessage";O[O.NoChange=15]="NoChange";O[O.DatabaseClosed=16]="DatabaseClosed";O[O.StorageError=17]="StorageError";O[O.DatabaseError=18]="DatabaseError";O[O.HashMismatch=19]="HashMismatch";O[O.DecryptionError=20]="DecryptionError";O[O.NotImplemented=21]="NotImplemented";O[O.MissingSeed=22]="MissingSeed";O[O.OutOfBounds=23]="OutOfBounds";O[O.HostError=24]="HostError";O[O.CommunicationError=25]="CommunicationError";O[O.VarLimitExceeded=26]="VarLimitExceeded";O[O.InvalidResponse=27]="InvalidResponse";O[O.ConnectionClosed=28]="ConnectionClosed"})(j||={});function D$(V){if(!V||typeof V!=="object")return!1;if(!("op"in V)||!("id"in V))return!1;return typeof V.op==="string"&&typeof V.id==="number"}function T$(V){let $=V.length,Z=0,J=0;while(J<$){let Q=V.charCodeAt(J++);if((Q&4294967168)===0){Z++;continue}else if((Q&4294965248)===0)Z+=2;else{if(Q>=55296&&Q<=56319){if(J<$){let W=V.charCodeAt(J);if((W&64512)===56320)++J,Q=((Q&1023)<<10)+(W&1023)+65536}}if((Q&4294901760)===0)Z+=3;else Z+=4}}return Z}function EZ(V,$,Z){let J=V.length,Q=Z,W=0;while(W<J){let Y=V.charCodeAt(W++);if((Y&4294967168)===0){$[Q++]=Y;continue}else if((Y&4294965248)===0)$[Q++]=Y>>6&31|192;else{if(Y>=55296&&Y<=56319){if(W<J){let X=V.charCodeAt(W);if((X&64512)===56320)++W,Y=((Y&1023)<<10)+(X&1023)+65536}}if((Y&4294901760)===0)$[Q++]=Y>>12&15|224,$[Q++]=Y>>6&63|128;else $[Q++]=Y>>18&7|240,$[Q++]=Y>>12&63|128,$[Q++]=Y>>6&63|128}$[Q++]=Y&63|128}}var SZ=new TextEncoder,xZ=50;function BZ(V,$,Z){SZ.encodeInto(V,$.subarray(Z))}function A$(V,$,Z){if(V.length>xZ)BZ(V,$,Z);else EZ(V,$,Z)}var fZ=4096;function DV(V,$,Z){let J=$,Q=J+Z,W=[],Y="";while(J<Q){let X=V[J++];if((X&128)===0)W.push(X);else if((X&224)===192){let G=V[J++]&63;W.push((X&31)<<6|G)}else if((X&240)===224){let G=V[J++]&63,K=V[J++]&63;W.push((X&31)<<12|G<<6|K)}else if((X&248)===240){let G=V[J++]&63,K=V[J++]&63,N=V[J++]&63,R=(X&7)<<18|G<<12|K<<6|N;if(R>65535)R-=65536,W.push(R>>>10&1023|55296),R=56320|R&1023;W.push(R)}else W.push(X);if(W.length>=fZ)Y+=String.fromCharCode(...W),W.length=0}if(W.length>0)Y+=String.fromCharCode(...W);return Y}var mZ=new TextDecoder,gZ=200;function vZ(V,$,Z){let J=V.subarray($,$+Z);return mZ.decode(J)}function _$(V,$,Z){if(Z>gZ)return vZ(V,$,Z);else return DV(V,$,Z)}class k0{type;data;constructor(V,$){this.type=V,this.data=$}}class a extends Error{constructor(V){super(V);let $=Object.create(a.prototype);Object.setPrototypeOf(this,$),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:a.name})}}var E0=4294967295;function j$(V,$,Z){let J=Z/4294967296,Q=Z;V.setUint32($,J),V.setUint32($+4,Q)}function s0(V,$,Z){let J=Math.floor(Z/4294967296),Q=Z;V.setUint32($,J),V.setUint32($+4,Q)}function t0(V,$){let Z=V.getInt32($),J=V.getUint32($+4);return Z*4294967296+J}function L$(V,$){let Z=V.getUint32($),J=V.getUint32($+4);return Z*4294967296+J}var iZ=-1,bZ=4294967295,uZ=17179869183;function yZ({sec:V,nsec:$}){if(V>=0&&$>=0&&V<=uZ)if($===0&&V<=bZ){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,V),Z}else{let Z=V/4294967296,J=V&4294967295,Q=new Uint8Array(8),W=new DataView(Q.buffer);return W.setUint32(0,$<<2|Z&3),W.setUint32(4,J),Q}else{let Z=new Uint8Array(12),J=new DataView(Z.buffer);return J.setUint32(0,$),s0(J,4,V),Z}}function pZ(V){let $=V.getTime(),Z=Math.floor($/1000),J=($-Z*1000)*1e6,Q=Math.floor(J/1e9);return{sec:Z+Q,nsec:J-Q*1e9}}function nZ(V){if(V instanceof Date){let $=pZ(V);return yZ($)}else return null}function lZ(V){let $=new DataView(V.buffer,V.byteOffset,V.byteLength);switch(V.byteLength){case 4:{let Z=$.getUint32(0),J=0;return{sec:Z,nsec:0}}case 8:{let Z=$.getUint32(0),J=$.getUint32(4),Q=(Z&3)*4294967296+J,W=Z>>>2;return{sec:Q,nsec:W}}case 12:{let Z=t0($,4),J=$.getUint32(0);return{sec:Z,nsec:J}}default:throw new a(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${V.length}`)}}function hZ(V){let $=lZ(V);return new Date($.sec*1000+$.nsec/1e6)}var k$={type:iZ,encode:nZ,decode:hZ};class S0{static defaultCodec=new S0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(k$)}register({type:V,encode:$,decode:Z}){if(V>=0)this.encoders[V]=$,this.decoders[V]=Z;else{let J=-1-V;this.builtInEncoders[J]=$,this.builtInDecoders[J]=Z}}tryToEncode(V,$){for(let Z=0;Z<this.builtInEncoders.length;Z++){let J=this.builtInEncoders[Z];if(J!=null){let Q=J(V,$);if(Q!=null){let W=-1-Z;return new k0(W,Q)}}}for(let Z=0;Z<this.encoders.length;Z++){let J=this.encoders[Z];if(J!=null){let Q=J(V,$);if(Q!=null)return new k0(Z,Q)}}if(V instanceof k0)return V;return null}decode(V,$,Z){let J=$<0?this.builtInDecoders[-1-$]:this.decoders[$];if(J)return J(V,$,Z);else return new k0($,V)}}function rZ(V){return V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer}function i0(V){if(V instanceof Uint8Array)return V;else if(ArrayBuffer.isView(V))return new Uint8Array(V.buffer,V.byteOffset,V.byteLength);else if(rZ(V))return new Uint8Array(V);else return Uint8Array.from(V)}var cZ=100,dZ=2048;class e0{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??S0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.maxDepth=V?.maxDepth??cZ,this.initialBufferSize=V?.initialBufferSize??dZ,this.sortKeys=V?.sortKeys??!1,this.forceFloat32=V?.forceFloat32??!1,this.ignoreUndefined=V?.ignoreUndefined??!1,this.forceIntegerToFloat=V?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new e0({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(V){if(this.entered)return this.clone().encodeSharedRef(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(V){if(this.entered)return this.clone().encode(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(V,$){if($>this.maxDepth)throw Error(`Too deep objects in depth ${$}`);if(V==null)this.encodeNil();else if(typeof V==="boolean")this.encodeBoolean(V);else if(typeof V==="number")if(!this.forceIntegerToFloat)this.encodeNumber(V);else this.encodeNumberAsFloat(V);else if(typeof V==="string")this.encodeString(V);else if(this.useBigInt64&&typeof V==="bigint")this.encodeBigInt64(V);else this.encodeObject(V,$)}ensureBufferSizeToWrite(V){let $=this.pos+V;if(this.view.byteLength<$)this.resizeBuffer($*2)}resizeBuffer(V){let $=new ArrayBuffer(V),Z=new Uint8Array($),J=new DataView($);Z.set(this.bytes),this.view=J,this.bytes=Z}encodeNil(){this.writeU8(192)}encodeBoolean(V){if(V===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber(V){if(!this.forceIntegerToFloat&&Number.isSafeInteger(V))if(V>=0)if(V<128)this.writeU8(V);else if(V<256)this.writeU8(204),this.writeU8(V);else if(V<65536)this.writeU8(205),this.writeU16(V);else if(V<4294967296)this.writeU8(206),this.writeU32(V);else if(!this.useBigInt64)this.writeU8(207),this.writeU64(V);else this.encodeNumberAsFloat(V);else if(V>=-32)this.writeU8(224|V+32);else if(V>=-128)this.writeU8(208),this.writeI8(V);else if(V>=-32768)this.writeU8(209),this.writeI16(V);else if(V>=-2147483648)this.writeU8(210),this.writeI32(V);else if(!this.useBigInt64)this.writeU8(211),this.writeI64(V);else this.encodeNumberAsFloat(V);else this.encodeNumberAsFloat(V)}encodeNumberAsFloat(V){if(this.forceFloat32)this.writeU8(202),this.writeF32(V);else this.writeU8(203),this.writeF64(V)}encodeBigInt64(V){if(V>=BigInt(0))this.writeU8(207),this.writeBigUint64(V);else this.writeU8(211),this.writeBigInt64(V)}writeStringHeader(V){if(V<32)this.writeU8(160+V);else if(V<256)this.writeU8(217),this.writeU8(V);else if(V<65536)this.writeU8(218),this.writeU16(V);else if(V<4294967296)this.writeU8(219),this.writeU32(V);else throw Error(`Too long string: ${V} bytes in UTF-8`)}encodeString(V){let Z=T$(V);this.ensureBufferSizeToWrite(5+Z),this.writeStringHeader(Z),A$(V,this.bytes,this.pos),this.pos+=Z}encodeObject(V,$){let Z=this.extensionCodec.tryToEncode(V,this.context);if(Z!=null)this.encodeExtension(Z);else if(Array.isArray(V))this.encodeArray(V,$);else if(ArrayBuffer.isView(V))this.encodeBinary(V);else if(typeof V==="object")this.encodeMap(V,$);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply(V)}`)}encodeBinary(V){let $=V.byteLength;if($<256)this.writeU8(196),this.writeU8($);else if($<65536)this.writeU8(197),this.writeU16($);else if($<4294967296)this.writeU8(198),this.writeU32($);else throw Error(`Too large binary: ${$}`);let Z=i0(V);this.writeU8a(Z)}encodeArray(V,$){let Z=V.length;if(Z<16)this.writeU8(144+Z);else if(Z<65536)this.writeU8(220),this.writeU16(Z);else if(Z<4294967296)this.writeU8(221),this.writeU32(Z);else throw Error(`Too large array: ${Z}`);for(let J of V)this.doEncode(J,$+1)}countWithoutUndefined(V,$){let Z=0;for(let J of $)if(V[J]!==void 0)Z++;return Z}encodeMap(V,$){let Z=Object.keys(V);if(this.sortKeys)Z.sort();let J=this.ignoreUndefined?this.countWithoutUndefined(V,Z):Z.length;if(J<16)this.writeU8(128+J);else if(J<65536)this.writeU8(222),this.writeU16(J);else if(J<4294967296)this.writeU8(223),this.writeU32(J);else throw Error(`Too large map object: ${J}`);for(let Q of Z){let W=V[Q];if(!(this.ignoreUndefined&&W===void 0))this.encodeString(Q),this.doEncode(W,$+1)}}encodeExtension(V){if(typeof V.data==="function"){let Z=V.data(this.pos+6),J=Z.length;if(J>=4294967296)throw Error(`Too large extension object: ${J}`);this.writeU8(201),this.writeU32(J),this.writeI8(V.type),this.writeU8a(Z);return}let $=V.data.length;if($===1)this.writeU8(212);else if($===2)this.writeU8(213);else if($===4)this.writeU8(214);else if($===8)this.writeU8(215);else if($===16)this.writeU8(216);else if($<256)this.writeU8(199),this.writeU8($);else if($<65536)this.writeU8(200),this.writeU16($);else if($<4294967296)this.writeU8(201),this.writeU32($);else throw Error(`Too large extension object: ${$}`);this.writeI8(V.type),this.writeU8a(V.data)}writeU8(V){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,V),this.pos++}writeU8a(V){let $=V.length;this.ensureBufferSizeToWrite($),this.bytes.set(V,this.pos),this.pos+=$}writeI8(V){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,V),this.pos++}writeU16(V){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,V),this.pos+=2}writeI16(V){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,V),this.pos+=2}writeU32(V){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,V),this.pos+=4}writeI32(V){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,V),this.pos+=4}writeF32(V){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,V),this.pos+=4}writeF64(V){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,V),this.pos+=8}writeU64(V){this.ensureBufferSizeToWrite(8),j$(this.view,this.pos,V),this.pos+=8}writeI64(V){this.ensureBufferSizeToWrite(8),s0(this.view,this.pos,V),this.pos+=8}writeBigUint64(V){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,V),this.pos+=8}writeBigInt64(V){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,V),this.pos+=8}}function VV(V,$){return new e0($).encodeSharedRef(V)}function $V(V){return`${V<0?"-":""}0x${Math.abs(V).toString(16).padStart(2,"0")}`}var oZ=16,aZ=16;class TV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(V=oZ,$=aZ){this.maxKeyLength=V,this.maxLengthPerKey=$,this.caches=[];for(let Z=0;Z<this.maxKeyLength;Z++)this.caches.push([])}canBeCached(V){return V>0&&V<=this.maxKeyLength}find(V,$,Z){let J=this.caches[Z-1];V:for(let Q of J){let W=Q.bytes;for(let Y=0;Y<Z;Y++)if(W[Y]!==V[$+Y])continue V;return Q.str}return null}store(V,$){let Z=this.caches[V.length-1],J={bytes:V,str:$};if(Z.length>=this.maxLengthPerKey)Z[Math.random()*Z.length|0]=J;else Z.push(J)}decode(V,$,Z){let J=this.find(V,$,Z);if(J!=null)return this.hit++,J;this.miss++;let Q=DV(V,$,Z),W=Uint8Array.prototype.slice.call(V,$,$+Z);return this.store(W,Q),Q}}var AV="array",u0="map_key",S$="map_value",sZ=(V)=>{if(typeof V==="string"||typeof V==="number")return V;throw new a("The type of key must be string or number but "+typeof V)};class x${stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(V){let $=this.getUninitializedStateFromPool();$.type=AV,$.position=0,$.size=V,$.array=Array(V)}pushMapState(V){let $=this.getUninitializedStateFromPool();$.type=u0,$.readCount=0,$.size=V,$.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let V={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(V)}return this.stack[this.stackHeadPosition]}release(V){if(this.stack[this.stackHeadPosition]!==V)throw Error("Invalid stack state. Released state is not on top of the stack.");if(V.type===AV){let Z=V;Z.size=0,Z.array=void 0,Z.position=0,Z.type=void 0}if(V.type===u0||V.type===S$){let Z=V;Z.size=0,Z.map=void 0,Z.readCount=0,Z.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var b0=-1,_V=new DataView(new ArrayBuffer(0)),tZ=new Uint8Array(_V.buffer);try{_V.getInt8(0)}catch(V){if(!(V instanceof RangeError))throw Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var E$=RangeError("Insufficient data"),eZ=new TV;class ZV{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=_V;bytes=tZ;headByte=b0;stack=new x$;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??S0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.rawStrings=V?.rawStrings??!1,this.maxStrLength=V?.maxStrLength??E0,this.maxBinLength=V?.maxBinLength??E0,this.maxArrayLength=V?.maxArrayLength??E0,this.maxMapLength=V?.maxMapLength??E0,this.maxExtLength=V?.maxExtLength??E0,this.keyDecoder=V?.keyDecoder!==void 0?V.keyDecoder:eZ,this.mapKeyConverter=V?.mapKeyConverter??sZ}clone(){return new ZV({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=b0,this.stack.reset()}setBuffer(V){let $=i0(V);this.bytes=$,this.view=new DataView($.buffer,$.byteOffset,$.byteLength),this.pos=0}appendBuffer(V){if(this.headByte===b0&&!this.hasRemaining(1))this.setBuffer(V);else{let $=this.bytes.subarray(this.pos),Z=i0(V),J=new Uint8Array($.length+Z.length);J.set($),J.set(Z,$.length),this.setBuffer(J)}}hasRemaining(V){return this.view.byteLength-this.pos>=V}createExtraByteError(V){let{view:$,pos:Z}=this;return RangeError(`Extra ${$.byteLength-Z} of ${$.byteLength} byte(s) found at buffer[${V}]`)}decode(V){if(this.entered)return this.clone().decode(V);try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);let $=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return $}finally{this.entered=!1}}*decodeMulti(V){if(this.entered){yield*this.clone().decodeMulti(V);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(V){if(this.entered)return this.clone().decodeAsync(V);try{this.entered=!0;let $=!1,Z;for await(let Y of V){if($)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(Y);try{Z=this.doDecodeSync(),$=!0}catch(X){if(!(X instanceof RangeError))throw X}this.totalPos+=this.pos}if($){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Z}let{headByte:J,pos:Q,totalPos:W}=this;throw RangeError(`Insufficient data in parsing ${$V(J)} at ${W} (${Q} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(V){return this.decodeMultiAsync(V,!0)}decodeStream(V){return this.decodeMultiAsync(V,!1)}async*decodeMultiAsync(V,$){if(this.entered){yield*this.clone().decodeMultiAsync(V,$);return}try{this.entered=!0;let Z=$,J=-1;for await(let Q of V){if($&&J===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(Q),Z)J=this.readArraySize(),Z=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--J===0)break}catch(W){if(!(W instanceof RangeError))throw W}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){V:while(!0){let V=this.readHeadByte(),$;if(V>=224)$=V-256;else if(V<192)if(V<128)$=V;else if(V<144){let J=V-128;if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V<160){let J=V-144;if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else{let J=V-160;$=this.decodeString(J,0)}else if(V===192)$=null;else if(V===194)$=!1;else if(V===195)$=!0;else if(V===202)$=this.readF32();else if(V===203)$=this.readF64();else if(V===204)$=this.readU8();else if(V===205)$=this.readU16();else if(V===206)$=this.readU32();else if(V===207)if(this.useBigInt64)$=this.readU64AsBigInt();else $=this.readU64();else if(V===208)$=this.readI8();else if(V===209)$=this.readI16();else if(V===210)$=this.readI32();else if(V===211)if(this.useBigInt64)$=this.readI64AsBigInt();else $=this.readI64();else if(V===217){let J=this.lookU8();$=this.decodeString(J,1)}else if(V===218){let J=this.lookU16();$=this.decodeString(J,2)}else if(V===219){let J=this.lookU32();$=this.decodeString(J,4)}else if(V===220){let J=this.readU16();if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else if(V===221){let J=this.readU32();if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else if(V===222){let J=this.readU16();if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V===223){let J=this.readU32();if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V===196){let J=this.lookU8();$=this.decodeBinary(J,1)}else if(V===197){let J=this.lookU16();$=this.decodeBinary(J,2)}else if(V===198){let J=this.lookU32();$=this.decodeBinary(J,4)}else if(V===212)$=this.decodeExtension(1,0);else if(V===213)$=this.decodeExtension(2,0);else if(V===214)$=this.decodeExtension(4,0);else if(V===215)$=this.decodeExtension(8,0);else if(V===216)$=this.decodeExtension(16,0);else if(V===199){let J=this.lookU8();$=this.decodeExtension(J,1)}else if(V===200){let J=this.lookU16();$=this.decodeExtension(J,2)}else if(V===201){let J=this.lookU32();$=this.decodeExtension(J,4)}else throw new a(`Unrecognized type byte: ${$V(V)}`);this.complete();let Z=this.stack;while(Z.length>0){let J=Z.top();if(J.type===AV)if(J.array[J.position]=$,J.position++,J.position===J.size)$=J.array,Z.release(J);else continue V;else if(J.type===u0){if($==="__proto__")throw new a("The key __proto__ is not allowed");J.key=this.mapKeyConverter($),J.type=S$;continue V}else if(J.map[J.key]=$,J.readCount++,J.readCount===J.size)$=J.map,Z.release(J);else{J.key=null,J.type=u0;continue V}}return $}}readHeadByte(){if(this.headByte===b0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=b0}readArraySize(){let V=this.readHeadByte();switch(V){case 220:return this.readU16();case 221:return this.readU32();default:if(V<160)return V-144;else throw new a(`Unrecognized array type byte: ${$V(V)}`)}}pushMapState(V){if(V>this.maxMapLength)throw new a(`Max length exceeded: map length (${V}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(V)}pushArrayState(V){if(V>this.maxArrayLength)throw new a(`Max length exceeded: array length (${V}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(V)}decodeString(V,$){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String(V,$);return this.decodeBinary(V,$)}decodeUtf8String(V,$){if(V>this.maxStrLength)throw new a(`Max length exceeded: UTF-8 byte length (${V}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+$+V)throw E$;let Z=this.pos+$,J;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached(V))J=this.keyDecoder.decode(this.bytes,Z,V);else J=_$(this.bytes,Z,V);return this.pos+=$+V,J}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===u0;return!1}decodeBinary(V,$){if(V>this.maxBinLength)throw new a(`Max length exceeded: bin length (${V}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(V+$))throw E$;let Z=this.pos+$,J=this.bytes.subarray(Z,Z+V);return this.pos+=$+V,J}decodeExtension(V,$){if(V>this.maxExtLength)throw new a(`Max length exceeded: ext length (${V}) > maxExtLength (${this.maxExtLength})`);let Z=this.view.getInt8(this.pos+$),J=this.decodeBinary(V,$+1);return this.extensionCodec.decode(J,Z,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let V=this.view.getUint8(this.pos);return this.pos++,V}readI8(){let V=this.view.getInt8(this.pos);return this.pos++,V}readU16(){let V=this.view.getUint16(this.pos);return this.pos+=2,V}readI16(){let V=this.view.getInt16(this.pos);return this.pos+=2,V}readU32(){let V=this.view.getUint32(this.pos);return this.pos+=4,V}readI32(){let V=this.view.getInt32(this.pos);return this.pos+=4,V}readU64(){let V=L$(this.view,this.pos);return this.pos+=8,V}readI64(){let V=t0(this.view,this.pos);return this.pos+=8,V}readU64AsBigInt(){let V=this.view.getBigUint64(this.pos);return this.pos+=8,V}readI64AsBigInt(){let V=this.view.getBigInt64(this.pos);return this.pos+=8,V}readF32(){let V=this.view.getFloat32(this.pos);return this.pos+=4,V}readF64(){let V=this.view.getFloat64(this.pos);return this.pos+=8,V}}function jV(V,$){return new ZV($).decode(V)}class y0{listeners=new Map;addEventListener(V,$){let Z=this.listeners.get(V);if(!Z)Z=new Set,this.listeners.set(V,Z);return Z.add($),()=>{this.removeEventListener(V,$)}}removeEventListener(V,$){let Z=this.listeners.get(V);if(Z){if(Z.delete($),Z.size===0)this.listeners.delete(V)}}emit(V,$){let Z=this.listeners.get(V);if(Z){let J=Array.from(Z);for(let Q of J)Q($)}}emitAll(V){let $=Array.from(this.listeners.keys());for(let Z of $)this.emit(Z,V)}}class P0{getter;static eventName="update";emitter;constructor(V){this.getter=V;this.emitter=new y0}get=()=>this.getter();async emit(){let V=await this.getter();queueMicrotask(()=>this.emitter.emit(P0.eventName,V))}listen(V){return this.emitter.addEventListener(P0.eventName,V),()=>{this.emitter.removeEventListener(P0.eventName,V)}}}function P(V){return[V,0]}function I(V){return[void 0,V]}function VJ(V){if(V<0)console.info("N",V),console.trace();if(typeof V!=="bigint")V=BigInt(V);if(V<0n)return I(10);let $=[];while(V>0n){let Z=Number(V&0x7fn);if(V>>=7n,V>0n)$.push(Z|128);else $.push(Z)}if($.length===0)return P(new Uint8Array([0]));if($.length>8)return I(26);return P(new Uint8Array($))}function $J(V,$=0){let Z=0n,J=0,Q=$;while(!0){if(Q>=V.length)return I(14);let W=V[Q++];if(W===void 0)return I(14);if(Z|=BigInt(W&127)<<BigInt(J),(W&128)===0){if(Q-$>8)return I(26);return P({value:Z>0x1fffffffffffffn?Z:Number(Z),bytesRead:Q-$})}if(J+=7,J>=56)return I(26)}}class m{data;pos=0;constructor(V){this.data=V}static async fromResponse(V){let $=await V.arrayBuffer(),Z=new Uint8Array($);return new m(Z)}readBigInt(){if(this.pos+8>this.data.length)return I(7);let V=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,P(V)}readDate(){let[V,$]=this.readVarInt();if($!==0)return I($);return P(new Date(V))}readVarInt(){let[V,$]=$J(this.data,this.pos);if($!==0)return I($);this.pos+=V.bytesRead;let Z=V.value;return P(typeof Z==="bigint"?Number(Z):Z)}readVarString(){let[V,$]=this.readVarInt();if($!==0)return I($);let[Z,J]=this.readBytes(V);if(J!==0)return I(J);let Q=new TextDecoder().decode(Z);return P(Q)}readBytes(V){if(V<0)return I(10);if(this.pos+V>this.data.length)return I(23);let $=this.data.slice(this.pos,this.pos+V);return this.pos+=V,P($)}readVarBytes(){let[V,$]=this.readVarInt();if($!==0)return I($);return this.readBytes(V)}readStruct(V){return V.decode(this)}readStructs(V){let $=[];while(!this.done()){let[Z,J]=this.readStruct(V);if(J!==0)return I(J);$.push(Z)}return P($)}readBytesSeq(V){let $=[];while(!this.done()){let[Z,J]=this.readBytes(V);if(J!==0)return I(J);$.push(Z)}return P($)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class B{parts=[];writeBigInt(V){let $=new Uint8Array(8);new DataView($.buffer).setBigUint64(0,V,!1),this.parts.push($)}writeDate(V){let $=V.getTime();return this.writeVarInt($)}writeVarInt(V){let[$,Z]=VJ(V);if(Z!==0)return Z;return this.parts.push($),0}writeVarString(V){let $=new TextEncoder().encode(V),Z=this.writeVarInt($.length);if(Z!==0)return Z;return this.writeBytes($),0}prependBytes(V){this.parts.unshift(V)}writeBytes(V){this.parts.push(V)}writeVarBytes(V){let $=this.writeVarInt(V.length);if($!==0)return $;return this.writeBytes(V),0}writeStruct(V,$){return V.encode(this,$)}writeStructs(V,$){for(let Z of $){let J=this.writeStruct(V,Z);if(J!==0)return J}return 0}writeBytesSeq(V){for(let $ of V)this.writeBytes($)}result(){let V=this.parts.reduce((J,Q)=>J+Q.length,0),$=new Uint8Array(V),Z=0;for(let J of this.parts)$.set(J,Z),Z+=J.length;return $}*scan(){for(let V of this.parts)yield V}}async function LV(V,$,Z){let J=new B,Q=J.writeDate($);if(Q!==0)return I(Q);let W=J.result(),Y=await Z.signEd25519(W,V.privateKey);return P({pubKey:V.publicKey,sig:Y,timestamp:$})}async function q0(V,$,Z){let J=Z.now().getTime(),Q=V.timestamp.getTime();if(Math.abs(J-Q)>H$)return 4;let Y=new B;Y.writeDate(V.timestamp);let X=Y.result();if(!await $.checkSigEd25519(V.sig,X,V.pubKey))return 3;return 0}var Y0={encode(V,$){let Z=V.writeVarBytes($.id);if(Z!==0)return Z;let J=V.writeDate($.ts);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return I(Z);let[J,Q]=V.readDate();if(Q!==0)return I(Q);return P({id:$,ts:J})}};function JV(V){let $=new B,Z=$.writeStruct(Y0,V);if(Z!==0)return I(Z);let J=$.result();return P(J)}var J0={encode(V,$){let Z=V.writeVarBytes($.eid);if(Z!==0)return Z;let J=V.writeVarInt($.off);if(J!==0)return J;let Q=V.writeVarInt($.ctr);if(Q!==0)return Q;let W=V.writeVarInt($.len);if(W!==0)return W;if($.hsh)V.writeBytes($.hsh);return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return I(Z);let J=new m($),[,Q]=Y0.decode(J);if(Q!==0)return I(Q);let[W,Y]=V.readVarInt();if(Y!==0)return I(Y);let[X,G]=V.readVarInt();if(G!==0)return I(G);let[K,N]=V.readVarInt();if(N!==0)return I(N);let R;if(K>0){let[M,z]=V.readBytes(a0);if(z!==0)return I(z);R=M}return P({eid:$,off:W,ctr:X,len:K,hsh:R})}};function Q0(V){return Array.from(V).map((Z)=>Z.toString(16).padStart(2,"0")).join("")}function QV(V){if(V.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(V.length/2);for(let Z=0;Z<V.length;Z+=2)$[Z/2]=Number.parseInt(V.substr(Z,2),16);return $}function O0(V,$){if(V===$)return!0;if(V.byteLength!==$.byteLength)return!1;return V.every((Z,J)=>Z===$[J])}var d;if(typeof Uint8Array.prototype.toBase64==="function")d=(V)=>V.toBase64();else d=(V)=>btoa(String.fromCharCode(...V));var N0;if(typeof Uint8Array.fromBase64==="function")N0=(V)=>Uint8Array.fromBase64(V);else N0=(V)=>Uint8Array.from(atob(V),($)=>$.charCodeAt(0));function p0(V,$){let Z=new Uint8Array(V.length+$.length);return Z.set(V,0),Z.set($,V.length),Z}function B$(V,$,Z){return Z.checkSigEd25519(V.sig,V.headCph,$)}async function kV(V,$,Z){let J=p0($.privateKey,V);return(await Z.blake3(J)).slice(0,U0)}async function f$(V,$,Z,J){let Q;if(V.bod&&V.len>0)Q=await Z.blake3(V.bod);let W=new B,Y=J0.encode(W,{...V,hsh:Q});if(Y!==0)return I(Y);let X=W.result(),G=await kV(X,$,Z),K=await J.deriveFromKDM(G),N=await Z.encryptXSalsa20Poly1305Combined(X,K),R=V.bod?await Z.encryptXSalsa20Poly1305Combined(V.bod,K):new Uint8Array(0),M=await Z.signEd25519(N,$.privateKey);return P({sig:M,kdm:G,headCph:N,bodyCph:R})}async function EV(V,$,Z,J){let Q=new m(V),[W,Y]=J0.decode(Q);if(Y!==0)return I(14);let X;try{X=$&&$.length>0?await J.decryptXSalsa20Poly1305Combined($,Z):void 0}catch{return I(20)}let G=W.hsh&&X===void 0,K=W.hsh===void 0&&X!==void 0;if(G||K)return I(19);if(W.hsh&&X){let R=await J.blake3(X);if(!O0(R,W.hsh))return I(19)}let N=await J.blake3(V);return P({msgHead:W,bod:X,headHash:N})}class SV{now(){return new Date}}function m$(V,$,Z,J){let Q=$.getTime()-V.getTime(),W=Z.getTime()-J.getTime();return(Q+W)/2}var n0={encode(V,$){if(V.writeVarInt($.quota),$.quota>0){if($.usage===void 0)return 9;V.writeVarInt($.usage)}return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return I(Z);let J;if($>0){let[Q,W]=V.readVarInt();if(W!==0)return I(W);J=Q}return P({quota:$,usage:J})}};var xV={encode(V,$){V.writeBytes(new Uint8Array([$.status]));let Z=V.writeDate($.timeRcvd);if(Z!==0)return Z;let J=V.writeDate($.timeSent);if(J!==0)return J;let Q=V.writeVarInt($.subscription.term);if(Q!==0)return Q;let W=V.writeVarInt($.subscription.elapsed);if(W!==0)return W;let Y=V.writeStruct(n0,$.subscription.stat);if(Y!==0)return Y;let X=V.writeStruct(n0,$.subscription.dyn);if(X!==0)return X;return 0},decode(V){let[$,Z]=V.readBytes(1);if(Z!==0)return I(Z);let J=$[0],[Q,W]=V.readDate();if(W!==0)return I(W);let[Y,X]=V.readDate();if(X!==0)return I(X);let[G,K]=V.readVarInt();if(K!==0)return I(K);let[N,R]=V.readVarInt();if(R!==0)return I(R);let[M,z]=V.readStruct(n0);if(z!==0)return I(z);let[F,w]=V.readStruct(n0);if(w!==0)return I(w);return P({status:J,timeRcvd:Q,timeSent:Y,subscription:{term:G,elapsed:N,stat:M,dyn:F}})}};async function BV(V,$,Z){let{crypto:J,enclave:Q}=V,W=await Q.derive($,Z);return await J.deriveEd25519KeyPair(W)}var fV={encode(V,$){let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarInt($.seq);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return I(Z);let[J,Q]=V.readVarInt();if(Q!==0)return I(Q);return P({headCph:$,seq:J})}};var V0={encode(V,$){V.writeBytes($.pubKey),V.writeBytes($.sig);let Z=V.writeDate($.timestamp);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readBytes(O$);if(Z!==0)return I(Z);let[J,Q]=V.readBytes(F0);if(Q!==0)return I(Q);let[W,Y]=V.readDate();if(Y!==0)return I(Y);return P({pubKey:$,sig:J,timestamp:W})}};var g$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(V0,Z);if(W!==0)return W;for(let Y of J)Q.writeVarInt(Y);return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(V0);if(X!==0)return X;let G=await q0(Y,Q,J);if(G!==0)return G;let{pubKey:K}=Y,[N,R]=await W.hasUser(K);if(R!==0)return R;if(!N)return 5;let[M,z]=$.readVarInt();if(z!==0)return z;if(!$.done())return 8;let[F,w]=await W.listHeads(K,M);if(w!==0)return w;return Z.writeStructs(fV,F)},decodeResp(V){return V.readStructs(fV)}};var mV={encode(V,$){V.writeVarInt($.seq);let Z=V.writeVarBytes($.bodyCph);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return I(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return I(Q);return P({seq:$,bodyCph:J})}};var v$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(V0,Z);if(W!==0)return W;for(let Y of J){let X=Q.writeVarInt(Y);if(X!==0)return X}return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(V0);if(X!==0)return X;let G=await q0(Y,Q,J);if(G!==0)return G;let{pubKey:K}=Y,[N,R]=await W.hasUser(K);if(R!==0)return R;if(!N)return 5;let M=[];while(!$.done()){let[w,q]=$.readVarInt();if(q!==0)return q;M.push(w)}console.info(`PULL: ${M.length} bags`);let[z,F]=await W.getBodies(K,M);if(F!==0)return F;if(!z)return 17;for(let{seq:w,bodyCph:q}of z){let H={seq:w,bodyCph:q},C=Z.writeStruct(mV,H);if(C!==0)return C}return 0},decodeResp(V){return V.readStructs(mV)}};var gV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarBytes($.bodyCph);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readBytes(F0);if(Z!==0)return I(Z);let[J,Q]=V.readBytes(U0);if(Q!==0)return I(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return I(Y);let[X,G]=V.readVarBytes();if(G!==0)return I(G);return P({sig:$,kdm:J,headCph:W,bodyCph:X})}};var WV={encode(V,$){let Z=V.writeVarInt($.seq);if(Z!==0)return Z;let J=V.writeVarBytes($.headCph);if(J!==0)return J;let Q=$.bodyCph?$.bodyCph.length:0,W=V.writeVarInt(Q);if(W!==0)return W;if(Q>0){if(!$.bodyCph)return 10;V.writeBytes($.bodyCph)}return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return I(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return I(Q);let[W,Y]=V.readVarInt();if(Y!==0)return I(Y);let X;if(W>0){let[G,K]=V.readBytes(W);if(K!==0)return I(K);X=G}return P({seq:$,headCph:J,bodyCph:X})}};var YV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readBytes(F0);if(Z!==0)return I(Z);let[J,Q]=V.readBytes(U0);if(Q!==0)return I(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return I(Y);return P({sig:$,kdm:J,headCph:W})}};var XV={encode(V,$){if(V.writeVarInt($.idx),V.writeBytes(new Uint8Array([$.status])),$.status===0)V.writeVarInt($.seq);return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return I(Z);let[J,Q]=V.readBytes(1);if(Q!==0)return I(Q);let W=J[0];if(W!==0)return P({idx:$,status:W});let[Y,X]=V.readVarInt();if(X!==0)return I(X);return P({idx:$,status:W,seq:Y})}};var i$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(V0,Z);if(W!==0)return W;let Y=Q.writeStructs(gV,J);if(Y!==0)return Y;return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W,notifier:Y}=V,[X,G]=$.readStruct(V0);if(G!==0)return G;let K=await q0(X,Q,J);if(K!==0)return K;let{pubKey:N}=X,[R,M]=await W.hasUser(N);if(M!==0)return M;if(!R)return 5;let[z,F]=$.readStructs(gV);if(F!==0)return F;console.info(`PUSH: ${z.length} bags`);let w=[],q=[];for(let U=0;U<z.length;U++){let A=z[U];if(!await B$(A,N,Q)){let k={idx:U,status:3},S=Z.writeStruct(XV,k);if(S!==0)return S;continue}w.push(U),q.push(A)}let[H,C]=await W.setBags(N,q);if(C!==0)return C;if(!H||H.length!==q.length)return 17;let T=[];for(let U=0;U<q.length;U++){let A=q[U],L=w[U],k=H[U],S=new B,E=S.writeStruct(YV,A);if(E!==0)return E;let x=S.result(),O={seq:k,headCph:x};if(z.length===1&&A.bodyCph.length<=C$)O.bodyCph=A.bodyCph;T.push(O);let f={idx:L,status:0,seq:k},v=Z.writeStruct(XV,f);if(v!==0)return v}if(T.length>0){let U=new B,A=U.writeStructs(WV,T);if(A!==0)return A;let L=U.result();await Promise.resolve(Y.push(N,L))}return 0},decodeResp(V){return V.readStructs(XV)}};var b$={async encodeReq(V,$,Z,J,Q){return Q.writeStruct(V0,Z)},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(V0);if(X!==0)return X;let G=await q0(Y,Q,J);if(G!==0)return G;let{pubKey:K}=Y;if(!$.done())return 8;let[N,R]=await W.addUser(K);if(R!==0)return R;return 0},decodeResp(V){return P(void 0)}};class vV{url;websocket;constructor(V){this.url=V}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(V,$,Z=()=>{},J=()=>{}){let{url:Q}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let W=new B;W.writeStruct(V0,V);let Y=W.result(),X=Q0(Y);return Q.searchParams.set("t",X),this.websocket=new WebSocket(Q),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),J()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Z()},this.websocket.onmessage=(G)=>{let K=new Uint8Array(G.data);$(K)},this.websocket.onerror=(G)=>{console.log(`ERROR: ${JSON.stringify(G)}`),this.websocket=void 0,Z()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var h={user:{path:"/user",endpoint:b$,name:0},push:{path:"/push",endpoint:i$,name:2},peek:{path:"/peek",endpoint:g$,name:1},pull:{path:"/pull",endpoint:v$,name:3}},ZJ={0:h.user,2:h.push,1:h.peek,3:h.pull},vY={[h.user.path]:h.user,[h.push.path]:h.push,[h.peek.path]:h.peek,[h.pull.path]:h.pull};class u${url;listener;constructor(V){this.url=V;this.listener=new vV(V)}async call(V,$){let{path:Z}=ZJ[V],J=new URL(Z,this.url);try{return await JJ(J,$)}catch{return I(25)}}}var y$=(V)=>{return new u$(V.handle)};async function JJ(V,$){let Z=await fetch(V,{method:"POST",body:$.result().slice()});if(!Z.ok)return I(24);let J=await m.fromResponse(Z);return P(J)}class GV{enclave;crypto;host;clock;transport;updateHostMeta;constructor(V,$,Z,J,Q,W){this.enclave=V;this.crypto=$;this.host=Z;this.clock=J;this.transport=Q;this.updateHostMeta=W}async call(V,$){let{clock:Z,crypto:J,transport:Q}=this,{endpoint:W,name:Y}=V,X=await this.keys(),G=Z.now(),[K,N]=await LV(X,G,J);if(N!==0)return I(N);let R=new B,M=await W.encodeReq(this,X,K,$,R);if(M!==0)return I(M);let z=Z.now(),[F,w]=await Q.call(Y,R),q=Z.now();if(w!==0)return I(w);let[H,C]=F.readStruct(xV);if(C!==0)return I(C);if(H.status!==0)return I(H.status);let U={clockOffset:m$(z,H.timeRcvd,H.timeSent,q),subscription:H.subscription},A=await this.updateHostMeta(U);if(A!==0)return I(A);return W.decodeResp(F)}keys=()=>{let{host:V}=this;return BV(this,V.label,V.idx)};seal=async(V)=>{let{crypto:$,enclave:Z}=this,J=await this.keys();return f$(V,J,$,Z)};register=()=>this.call(h.user,[]);peek=(V)=>this.call(h.peek,[V]);push=(V)=>this.call(h.push,V);pull=(V)=>this.call(h.pull,V);listen=async(V,$,Z)=>{let{clock:J,crypto:Q,host:W,transport:Y}=this,{listener:X}=Y,G=await BV(this,W.label,W.idx),K=J.now(),[N,R]=await LV(G,K,Q);if(R!==0)return R;return await X.connect(N,V,$,Z)};isConnected(){let V=this.transport?.listener;if(V&&typeof V.connected==="function")return V.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var iV={encode(V,$){let Z=V.writeVarString($.lbl);if(Z!==0)return Z;let J=V.writeVarInt($.idx);if(J!==0)return J;let Q=V.writeVarInt($.num);if(Q!==0)return Q;return V.writeBytes($.hsh),V.writeBytes($.sig),0},decode(V){let[$,Z]=V.readVarString();if(Z!==0)return I(Z);let[J,Q]=V.readVarInt();if(Q!==0)return I(Q);let[W,Y]=V.readVarInt();if(Y!==0)return I(Y);let[X,G]=V.readBytes(a0);if(G!==0)return I(G);let[K,N]=V.readBytes(F0);if(N!==0)return I(N);return P({lbl:$,idx:J,num:W,hsh:X,sig:K})}};var bV={encode(V,$){let Z=V.writeStruct(iV,$.head);if(Z!==0)return Z;let J=V.writeVarBytes($.indexEnc);if(J!==0)return J;let Q=V.writeVarBytes($.bodyEnc);if(Q!==0)return Q;return 0},decode(V){let[$,Z]=V.readStruct(iV);if(Z!==0)return I(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return I(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return I(Y);return P({head:$,indexEnc:J,bodyEnc:W})}};var uV={encode(V,$){V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarInt($.lenBody);if(J!==0)return J;if($.lenBody>0&&$.offBody!==void 0){let Q=V.writeVarInt($.offBody);if(Q!==0)return Q}return 0},decode(V){let[$,Z]=V.readBytes(U0);if(Z!==0)return I(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return I(Q);let[W,Y]=V.readVarInt();if(Y!==0)return I(Y);let X;if(W>0){let[G,K]=V.readVarInt();if(K!==0)return I(K);X=G}return P({kdm:$,headCph:J,lenBody:W,offBody:X})}};async function p$(V,$,Z,J,Q){let W=await Q.derive(V,$),Y=await J.deriveEd25519KeyPair(W),X=new B,G=new B,K=0,N=0;for(let C of Z){let T=new B,U=T.writeStruct(J0,C.head);if(U!==0)return I(U);let A=T.result(),L=await kV(A,Y,J),k=await Q.deriveFromKDM(L),S=await J.encryptXSalsa20Poly1305Combined(A,k),E=C.body?await J.encryptXSalsa20Poly1305Combined(C.body,k):new Uint8Array(0),x=C.head.len>0&&C.head.hsh!==void 0?E.length:0,O={kdm:L,headCph:S,lenBody:x,offBody:x>0?N:void 0},f=X.writeStruct(uV,O);if(f!==0)return I(f);if(C.body)G.writeBytes(E),N+=E.length;K++}let R=G.result(),M=X.result(),z=await J.blake3(M),F=await J.signEd25519(z,Y.privateKey),w={lbl:V,idx:$,num:K,hsh:z,sig:F},q=new B;q.writeStruct(bV,{head:w,indexEnc:M,bodyEnc:R});let H=q.result();return P(H)}async function n$(V,$,Z){let[J,Q]=bV.decode(new m(V));if(Q!==0)return I(Q);let{head:W,indexEnc:Y,bodyEnc:X}=J,G=await Z.derive(W.lbl,W.idx),K=await $.deriveEd25519KeyPair(G);if(!await $.checkSigEd25519(W.sig,W.hsh,K.publicKey))return I(3);let R=await $.blake3(Y);if(!O0(R,W.hsh))return I(19);let M=new m(Y),z=[];for(let w=0;w<W.num;w++){let[q,H]=M.readStruct(uV);if(H!==0)return I(H);z.push(q)}if(z.length!==W.num)return I(14);let F=[];for(let w of z){let q=await Z.deriveFromKDM(w.kdm),H=await $.decryptXSalsa20Poly1305Combined(w.headCph,q),[C,T]=J0.decode(new m(H));if(T!==0)return I(T);let U;if(w.lenBody>0&&w.offBody!==void 0){if(C.hsh===void 0)return I(14);let A=X.slice(w.offBody,w.offBody+w.lenBody);U=await $.decryptXSalsa20Poly1305Combined(A,q);let L=await $.blake3(U);if(!O0(L,C.hsh))return I(19)}F.push({head:C,body:U})}return P(F)}async function l$({now:V,bod:$,crypto:Z}){let J=await Z.genRandomBytes(8),Q=new B,W=Q.writeStruct(Y0,{id:J,ts:V});if(W!==0)return I(W);let Y=Q.result();return KV({now:V,eid:Y,ctr:0,bod:$,crypto:Z})}async function KV({now:V,eid:$,ctr:Z,bod:J,crypto:Q}){let W=new m($),[Y,X]=Y0.decode(W);if(X!==0)return I(X);let G=V.getTime()-Y.ts.getTime(),K,N=J?.length??0;if(J&&N>0)K=await Q.blake3(J);return P({eid:$,off:G,ctr:Z,len:N,hsh:K})}class NV{inflight=null;again=!1;run(V){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain(V),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain(V){try{this.again=!1;let $=await V();while(this.again)this.again=!1,$=await V();return $}finally{this.inflight=null}}}var h$=100;class yV{timer=null;delayMs;work;tail=new NV;constructor(V,$){this.delayMs=V<0?0:V,this.work=$}schedule(){if(this.delayMs<=0){this.fire();return}if(this.timer!==null)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=null,this.fire()},this.delayMs)}async flush(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null,this.fire();await this.tail.flush()}cancel(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null}fire(){return this.tail.run(this.work)}}var pV={phase:"idle"},RV=50;function l0(V,$,Z){if(V<=0||$<=0)return!1;if(V===1||V===$)return!0;return V%Z===0}function r$(V,$){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(V,$);return}let Z=URL.createObjectURL(V),J=document.createElement("a");J.href=Z,J.download=$,document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL(Z)}function c$(V,$,Z){let J=[],Q=[],W=0;for(let Y of V){let X=$(Y);if(Q.length>0&&W+X>Z)J.push(Q),Q=[],W=0;if(Q.push(Y),W+=X,W>=Z)J.push(Q),Q=[],W=0}if(Q.length>0)J.push(Q);return J}async function nV(V,$,Z,J){let Q=new m(V.headCph),[W,Y]=Q.readStruct(YV);if(Y!==0)return I(Y);let{sig:X,kdm:G,headCph:K}=W;if(!await J.checkSigEd25519(X,K,$.publicKey))return I(3);let R=await Z.deriveFromKDM(G),M;try{M=await J.decryptXSalsa20Poly1305Combined(K,R)}catch{return I(20)}return P({kdm:G,headEnc:M})}var lV=1048576,hV=1048576;function QJ(V){return V.sig.length+V.kdm.length+V.headCph.length+V.bodyCph.length}async function WJ(V,$,Z,J,Q){if(J.length<1)return 0;let[W,Y]=await V.push(J);if(Y!==0)return Y;if(!W)return 27;for(let G of W){if(G.status!==0){console.error("push err",G);continue}let K=Q[G.idx];if(!K){console.error("no hash",G);continue}await $.uploads.deq(Z,[K])}let X=await $.hosts.get(Z);if(X){let G=X.lastSeq,K=G,N=[];for(let R of W)if(R.status===0)N.push(R.seq);N.sort((R,M)=>R-M);for(let R of N)if(R===G+1)G=R;if(G>K)await $.hosts.touch(Z,G)}return 0}async function d$(V,$){if($.length<1)return P([]);let Z=new Map,J=[];for(let X of $)Z.set(X.seq,X),J.push(X.seq);let[Q,W]=await V.pull(J);if(W!==0)return I(W);if(!Q)return I(27);let Y=[];for(let{seq:X,bodyCph:G}of Q){let K=Z.get(X);if(!K)continue;Y.push({dl:K,bodyCph:G})}return P(Y)}async function YJ(V,$,Z,J){if(J.length<1)return P({parts:[],hashes:[]});let Q=[],W=[],Y=[],X=new Map;for(let{dl:K,bodyCph:N}of J){let{head:R,kdm:M,seq:z,host:F}=K,w=new B;w.writeStruct(J0,R);let q=w.result(),H=await Z.blake3(q),C=await $.deriveFromKDM(M),[T,U]=await EV(q,N,C,Z);if(U!==0){let k=X.get(F)??[];k.push(z),X.set(F,k);continue}let A={head:R,body:T.bod};Y.push({key:H,data:t$(A)}),Q.push(A),W.push(H);let L=X.get(F)??[];L.push(z),X.set(F,L)}let G=await V.messages.add(Y);for(let[K,N]of X)await V.downloads.deq(K,N);for(let K=0;K<G.length;K++){let N=G[K];if(N!==0&&N!==15)console.error("ERR storing",j[N],"for message",K)}return P({parts:Q,hashes:W})}async function o$({conn:V,store:$,enclave:Z,host:J,crypto:Q,onProgress:W,peekProgressEvery:Y}){let X=await V.keys(),G=[],[K,N]=await V.peek(J.lastSeq);if(N!==0)return N;let R=K.length,M=Y??RV;if(W&&R>0)W({phase:"peek",host:J.label,done:0,total:R});let z=0;for(let F of K){let[w,q]=await nV(F,X,Z,Q);if(q!==0){if(console.error("peek: decrypting item head",q),z+=1,W&&l0(z,R,M))W({phase:"peek",host:J.label,done:z,total:R});continue}let H=await Q.blake3(w.headEnc);if(await $.messages.has(H)){if(console.info("peek: skipping download enqueue"),await $.uploads.deq(J.label,[H]),z+=1,W&&l0(z,R,M))W({phase:"peek",host:J.label,done:z,total:R});continue}let T=new m(w.headEnc),[U,A]=T.readStruct(J0);if(A!==0){if(console.error("peek: reading item head",A),z+=1,W&&l0(z,R,M))W({phase:"peek",host:J.label,done:z,total:R});continue}if(G.push({kdm:w.kdm,head:U,seq:F.seq,host:J.label}),z+=1,W&&l0(z,R,M))W({phase:"peek",host:J.label,done:z,total:R})}if(await $.downloads.enq(G),K.length>0){let F=Math.max(...K.map((w)=>w.seq));await $.hosts.touch(J.label,F)}if(W)W({phase:"peek",host:J.label,done:R,total:R});return 0}async function a$({conn:V,store:$,host:Z,maxPushBytes:J,onProgress:Q}){let W=J??lV,Y=await $.uploads.list(Z.label),X=Y.length,G=0;if(Q&&X>0)Q({phase:"push",host:Z.label,done:0,total:X});let K=[],N=[],R=0,M=async()=>{if(K.length<1)return 0;let z=K.length,F=await WJ(V,$,Z.label,K,N);if(K=[],N=[],R=0,F===0){if(G+=z,Q)Q({phase:"push",host:Z.label,done:G,total:X})}return F};for(let z of Y){let F=await $.messages.get(z);if(!F){G+=1;continue}let w={...F.head,bod:F.body},[q,H]=await V.seal(w);if(H!==0)return H;if(!q)return 12;let C=QJ(q);if(K.length>0&&R+C>W){let T=await M();if(T!==0)return T}if(K.push(q),N.push(z),R+=C,R>=W){let T=await M();if(T!==0)return T}}return M()}async function s$({conn:V,store:$,enclave:Z,host:J,crypto:Q,maxPullBytes:W,onProgress:Y},X){let G=W??hV,K=await $.downloads.list(),N=Array.from(K).filter((w)=>w.host===J.label);if(N.length<1)return 15;let R=c$(N,(w)=>w.head.len,G),M=N.length,z=0;if(Y)Y({phase:"pull",host:J.label,done:0,total:M});let F=d$(V,R[0]);for(let w=0;w<R.length;w++){let[q,H]=await F;if(H!==0||!q)return H;if(z+=R[w].length,Y)Y({phase:"pull",host:J.label,done:z,total:M});let C=R[w+1];if(C)F=d$(V,C);if(Y)Y({phase:"open",host:J.label,done:z,total:M});let[,T]=await YJ($,Z,Q,q);if(T!==0)return T;if(X){if(Y)Y({phase:"exec",host:J.label,done:z,total:M});await X()}}return 0}function t$({head:V,body:$}){return{eid:V.eid,...V.off!==0?{off:V.off}:{},...V.ctr!==0?{ctr:V.ctr}:{},body:$,apld:!1}}async function e$(V,{conn:$,store:Z,enclave:J,host:Q,crypto:W,onProgress:Y},X){let G=Q.label,K=await $.keys(),N=new m(V),[R,M]=N.readStructs(WV);if(M!==0){console.error("Failed decoding notif",j[M]);return}let z=!1,w=(await Z.hosts.get(G))?.lastSeq,q=[],H=!1;for(let U of R){let[A,L]=await nV({seq:U.seq,headCph:U.headCph},K,J,W);if(L!==0){console.error("Failed decrypting notif",j[L]);continue}let k=await W.blake3(A.headEnc);if(await Z.messages.has(k))continue;let S=new m(A.headEnc),[E,x]=S.readStruct(J0);if(x!==0){console.error("Failed to parse head",j[x]);continue}if(!U.bodyCph&&E.len>0)H=!0,await Z.downloads.enq([{seq:U.seq,host:G,kdm:A.kdm,head:E}]);else q.push({...A,head:E,bodyCph:U.bodyCph,headEncHash:k});if(w===void 0||U.seq!==w+1)console.log("out of seq",U.seq,w),z=!0;else w=U.seq}if(w!==void 0)await Z.hosts.touch(Q.label,w);let C=[];for(let U of q){let A=await J.deriveFromKDM(U.kdm),[L,k]=await EV(U.headEnc,U.bodyCph,A,W);if(k!==0){console.error("Failed to open body",j[k]);continue}C.push({key:U.headEncHash,data:t$({head:U.head,body:L.bod})})}let T=await Z.messages.add(C);for(let U=0;U<T.length;U++){let A=T[U];if(A!==0&&A!==15)console.error("ERR storing",j[A],"for message",U)}if(Y&&C.length>0)Y({phase:"open",host:Q.label,done:C.length,total:C.length});if(z||H||C.length>0)X()}class rV{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new NV;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=RV;lastProgress=pV;scheduledSync;constructor(V,$,Z,J,Q,W=!0,Y=lV,X=hV,G){this.clock=V;this.state=$;this.store=Z;this.transport=J;this.crypto=Q;this.forceSkewHandlingByDefault=W;this.onScheduleSync=G;this.maxPushBytes=Y,this.maxPullBytes=X,this.clientState=new P0(()=>this.getClientState()),this.xferState=new P0(()=>this.getXferState()),this.scheduledSync=new yV(h$,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(K){console.error("Debounced sync failed:",K)}})}emitProgress=(V)=>{this.lastProgress=V,this.xferState.emit()};async setSeed(V){await this.store.seed.save(V),this.clientState.emit()}async getClientState(){let{store:V,connections:$}=this,Z=await V.seed.load(),J=await V.hosts.list(),Q=!1;for(let W of $.values())if(W.isConnected()){Q=!0;break}return{hasSeed:Z!==void 0,hasHost:Array.from(J).length>0,connected:Q}}async getXferState(){let{uploads:V,downloads:$}=this.store,Z=await V.count();return{numDownloads:await $.count(),numUploads:Z,progress:this.lastProgress}}apply=async(V,$={enqueueUpload:!0,triggerUpload:!0})=>{let Z=[],J=[];for(let{head:W,body:Y}of V){let X=new B;X.writeStruct(J0,W);let G=X.result(),K=await this.crypto.blake3(G),N={eid:W.eid,...W.off!==0?{off:W.off}:{},...W.ctr!==0?{ctr:W.ctr}:{},body:Y,apld:!1};Z.push(K),J.push({key:K,data:N})}await this.store.messages.add(J);let Q=await this.applyHashes(Z);if($.enqueueUpload){let W=[];for(let Y=0;Y<Z.length;Y++){let X=Q[Y];if(X===0||X===15)W.push(Z[Y])}if(W.length>0){let Y=await this.store.hosts.list();for(let X of Y)await this.store.uploads.enq(X.label,W);this.xferState.emit()}}if($.triggerUpload)this.scheduleSync();return Q};enqueueApplyJob(V){let $=this.applyChain.then(V,V);return this.applyChain=$.then(()=>{return},()=>{return}),$}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let V=await this.store.messages.listUnapplied();if(V.length<1)return[];return this.applyStored(V)}applyHashes=(V)=>{return this.enqueueApplyJob(async()=>{let $=[];for(let Q of V){let W=await this.store.messages.get(Q);if(W)$.push(W)}let Z=await this.applyStored($),J=new Map;for(let Q=0;Q<$.length;Q++)J.set(d($[Q].hash),Z[Q]??12);return V.map((Q)=>J.get(d(Q))??13)})};async applyStored(V){if(V.length<1)return[];let $=V.map((Q)=>({...Q.head,bod:Q.body})),Z=await this.state.apply($),J=[];for(let Q=0;Q<V.length;Q++){let W=Z[Q];if(W===0||W===15)J.push(V[Q].hash)}if(J.length>0)await this.store.messages.markApplied(J);return Z}async insertRaw(V){let{clock:$,crypto:Z}=this,[J,Q]=await l$({now:$.now(),bod:V,crypto:Z});if(Q!==0)return I(Q);return await this.apply([{head:J,body:V}]),P(J)}async upsertRaw(V,$,Z=!1){let{clock:J,crypto:Q,store:W}=this,Y=J.now(),X=await W.messages.last(V);if(X){let z=new m(V),[F,w]=z.readStruct(Y0);if(w!==0)return I(w);if(F.ts.getTime()+X.head.off>Y.getTime()){if(Z===!1)return I(4);let H=X.head.off+1,C=X.head.ctr+1,T={eid:V,off:H,ctr:C,len:0},A=(await this.apply([{head:T,body:void 0}]))[0];if(A!==0)return I(A);if($===void 0)return P(T);let[L,k]=JV({id:F.id,ts:Y});if(k!==0)return I(k);let S={now:Y,eid:L,ctr:0,bod:$,crypto:Q},[E,x]=await KV(S);if(x!==0)return I(x);let f=(await this.apply([{head:E,body:$}]))[0];if(f!==0)return I(f);return P(E)}}let G=(X?.head.ctr??-1)+1,[K,N]=await KV({now:Y,eid:V,ctr:G,bod:$,crypto:Q});if(N!==0)return I(N);let M=(await this.apply([{head:K,body:$}]))[0];if(M!==0)return I(M);return P(K)}async insert(V){let{body:$,type:Z,gid:J,pid:Q}=V,Y=VV({body:$,type:Z,gid:J,pid:Q});return this.insertRaw(Y)}async upsert(V,$=this.forceSkewHandlingByDefault){let{eid:Z,body:J,type:Q,gid:W,pid:Y}=V;if(Z===void 0)return this.insert(V);let G=VV({body:J,type:Q,gid:W,pid:Y});return this.upsertRaw(Z,G,$)}async delete(V){return this.upsertRaw(V,void 0,!0)}async genEID(V){let{clock:$,crypto:Z}=this,J=$.now();if(V!==void 0)return JV({id:V,ts:J});let Q=await Z.genRandomBytes(8);return JV({id:Q,ts:J})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:V,crypto:$,store:Z}=this,J=await Z.seed.load();if(!J)return 22;await this.drainApplyQueue();for(let[Q,W]of V){let Y=await Z.hosts.get(Q);if(!Y)continue;let X={conn:W,store:Z,enclave:J,host:Y,crypto:$,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},G=await o$(X);if(G!==0)return console.error(`Failed to peek: ${G}`),G;this.xferState.emit();let K=await a$(X);if(K!==0)return console.error(`Failed to push: ${K}`),K;this.xferState.emit();let N=await s$(X,async()=>{await this.drainApplyQueue()});if(N!==0&&N!==15)return console.error(`Failed to pull: ${N}`),N;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async wipe(){this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush(),await this.store.wipe(),await this.state.clear(),this.lastProgress=pV,this.clientState.emit(),this.xferState.emit()}import=async(V,$)=>{let{crypto:Z,store:J}=this,Q=$?.onProgress,W=await J.seed.load();if(!W)return 22;console.time("import: decoding file...");let Y=await V.bytes(),[X,G]=await n$(Y,Z,W);if(G!==0)return G;console.timeEnd("import: decoding file...");let K=0;while(K<X.length){let N=0,R=0,M=K;for(let w=K;w<X.length&&R<100&&N<102400;w++)N+=X[w].head.len,R++,M=w+1;let z=X.slice(K,M);console.time(`import: applying [${K}, ${M}]`);let F=await this.apply(z,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${K}, ${M}]`);for(let w=0;w<z.length;w++){let q=F[w];if(q!==0&&q!==15)console.warn(`failed to import msg ${K+w}: ${j[q]}`)}if(Q)queueMicrotask(()=>Q(M,X.length,0));this.emitProgress({phase:"import",done:M,total:X.length}),K=M}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:V,store:$}=this,Z=await $.seed.load();if(!Z)return I(22);let J=await $.messages.list();return p$("export",0,J,V,Z)}async export(V){let[$,Z]=await this.exportBytes();if(Z!==0)return Z;if(!$)return 12;let J=new Blob([$.slice()]);return r$(J,V),0}async link(V,$=!0){if(await this.store.hosts.add(V),this.clientState.emit(),$){let Z=await this.store.hosts.get(V.label);if(Z)await this.connectToHost(Z)}}async unlink(V){await this.store.hosts.del(V),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async(V,$=!0,Z=!0)=>{let{clock:J,connections:Q,crypto:W,store:Y,transport:X}=this,G=Q.get(V.label);if(G){if(G.isConnected())return;try{G.closeListener()}catch{}Q.delete(V.label)}let K=await Y.seed.load();if(!K)return;console.info(`Connecting to ${V.handle} (${V.label})`);let N=new GV(K,W,V,J,X(V),(R)=>Y.hosts.set(V.label,R));if(await N.register(),$)await N.listen(async(R)=>{let M={conn:N,store:Y,enclave:K,host:V,crypto:W,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return e$(R,M,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(Q.set(V.label,N),this.clientState.emit(),Z)this.scheduleSync()};async connect(V=!0,$=!0){let{connectToHost:Z,scheduleSync:J,store:Q}=this;if(!await Q.seed.load())return;await this.drainApplyQueue();let Y=await Q.hosts.list();for(let X of Y)await Z(X,V,!1);if($)J()}disconnect=async()=>{for(let V of this.connections.values())try{V.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var H0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function IV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function cV(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function l(V,...$){if(!cV(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function dV(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function VZ(V,$){l(V);let Z=$.outputLen;if(V.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function oV(V){if(typeof V!=="boolean")throw Error(`boolean expected, not ${V}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var R0=(V)=>new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4));var XJ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!XJ)throw Error("Non little-endian hardware is not supported");function GJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function wV(V){if(typeof V==="string")V=GJ(V);else if(cV(V))V=zV(V);else throw Error("Uint8Array expected, got "+typeof V);return V}function $Z(V,$){if($==null||typeof $!=="object")throw Error("options must be defined");return Object.assign(V,$)}function ZZ(V,$){if(V.length!==$.length)return!1;let Z=0;for(let J=0;J<V.length;J++)Z|=V[J]^$[J];return Z===0}var JZ=(V,$)=>{function Z(J,...Q){if(l(J),V.nonceLength!==void 0){let N=Q[0];if(!N)throw Error("nonce / iv required");if(V.varSizeNonce)l(N);else l(N,V.nonceLength)}let W=V.tagLength;if(W&&Q[1]!==void 0)l(Q[1]);let Y=$(J,...Q),X=(N,R)=>{if(R!==void 0){if(N!==2)throw Error("cipher output not supported");l(R)}},G=!1;return{encrypt(N,R){if(G)throw Error("cannot encrypt() twice with same key + nonce");return G=!0,l(N),X(Y.encrypt.length,R),Y.encrypt(N,R)},decrypt(N,R){if(l(N),W&&N.length<W)throw Error("invalid ciphertext length: smaller than tagLength="+W);return X(Y.decrypt.length,R),Y.decrypt(N,R)}}}return Object.assign(Z,V),Z};function aV(V,$,Z=!0){if($===void 0)return new Uint8Array(V);if($.length!==V)throw Error("invalid output length, expected "+V+", got: "+$.length);if(Z&&!KJ($))throw Error("invalid output, must be aligned");return $}function KJ(V){return V.byteOffset%4===0}function zV(V){return Uint8Array.from(V)}function X0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function MV(V=32){if(H0&&typeof H0.getRandomValues==="function")return H0.getRandomValues(new Uint8Array(V));if(H0&&typeof H0.randomBytes==="function")return H0.randomBytes(V);throw Error("crypto.getRandomValues must be defined")}var WZ=(V)=>Uint8Array.from(V.split("").map(($)=>$.charCodeAt(0))),NJ=WZ("expand 16-byte k"),RJ=WZ("expand 32-byte k"),IJ=R0(NJ),wJ=R0(RJ);function D(V,$){return V<<$|V>>>32-$}function sV(V){return V.byteOffset%4===0}var FV=64,zJ=16,YZ=4294967295,QZ=new Uint32Array;function MJ(V,$,Z,J,Q,W,Y,X){let G=Q.length,K=new Uint8Array(FV),N=R0(K),R=sV(Q)&&sV(W),M=R?R0(Q):QZ,z=R?R0(W):QZ;for(let F=0;F<G;Y++){if(V($,Z,J,N,Y,X),Y>=YZ)throw Error("arx: counter overflow");let w=Math.min(FV,G-F);if(R&&w===FV){let q=F/4;if(F%4!==0)throw Error("arx: invalid block position");for(let H=0,C;H<zJ;H++)C=q+H,z[C]=M[C]^N[H];F+=FV;continue}for(let q=0,H;q<w;q++)H=F+q,W[H]=Q[H]^K[q];F+=w}}function XZ(V,$){let{allowShortKeys:Z,extendNonceFn:J,counterLength:Q,counterRight:W,rounds:Y}=$Z({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},$);if(typeof V!=="function")throw Error("core must be a function");return IV(Q),IV(Y),oV(W),oV(Z),(X,G,K,N,R=0)=>{l(X),l(G),l(K);let M=K.length;if(N===void 0)N=new Uint8Array(M);if(l(N),IV(R),R<0||R>=YZ)throw Error("arx: counter overflow");if(N.length<M)throw Error(`arx: output (${N.length}) is shorter than data (${M})`);let z=[],F=X.length,w,q;if(F===32)z.push(w=zV(X)),q=wJ;else if(F===16&&Z)w=new Uint8Array(32),w.set(X),w.set(X,16),q=IJ,z.push(w);else throw Error(`arx: invalid 32-byte key, got length=${F}`);if(!sV(G))z.push(G=zV(G));let H=R0(w);if(J){if(G.length!==24)throw Error("arx: extended nonce must be 24 bytes");J(q,H,R0(G.subarray(0,16)),H),G=G.subarray(16)}let C=16-Q;if(C!==G.length)throw Error(`arx: nonce must be ${C} or 16 bytes`);if(C!==12){let U=new Uint8Array(12);U.set(G,W?0:12-G.length),G=U,z.push(G)}let T=R0(G);return MJ(V,q,H,T,K,N,R,Y),X0(...z),N}}var r=(V,$)=>V[$++]&255|(V[$++]&255)<<8;class GZ{constructor(V){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,V=wV(V),l(V,32);let $=r(V,0),Z=r(V,2),J=r(V,4),Q=r(V,6),W=r(V,8),Y=r(V,10),X=r(V,12),G=r(V,14);this.r[0]=$&8191,this.r[1]=($>>>13|Z<<3)&8191,this.r[2]=(Z>>>10|J<<6)&7939,this.r[3]=(J>>>7|Q<<9)&8191,this.r[4]=(Q>>>4|W<<12)&255,this.r[5]=W>>>1&8190,this.r[6]=(W>>>14|Y<<2)&8191,this.r[7]=(Y>>>11|X<<5)&8065,this.r[8]=(X>>>8|G<<8)&8191,this.r[9]=G>>>5&127;for(let K=0;K<8;K++)this.pad[K]=r(V,16+2*K)}process(V,$,Z=!1){let J=Z?0:2048,{h:Q,r:W}=this,Y=W[0],X=W[1],G=W[2],K=W[3],N=W[4],R=W[5],M=W[6],z=W[7],F=W[8],w=W[9],q=r(V,$+0),H=r(V,$+2),C=r(V,$+4),T=r(V,$+6),U=r(V,$+8),A=r(V,$+10),L=r(V,$+12),k=r(V,$+14),S=Q[0]+(q&8191),E=Q[1]+((q>>>13|H<<3)&8191),x=Q[2]+((H>>>10|C<<6)&8191),O=Q[3]+((C>>>7|T<<9)&8191),f=Q[4]+((T>>>4|U<<12)&8191),v=Q[5]+(U>>>1&8191),u=Q[6]+((U>>>14|A<<2)&8191),y=Q[7]+((A>>>11|L<<5)&8191),p=Q[8]+((L>>>8|k<<8)&8191),n=Q[9]+(k>>>5|J),_=0,c=_+S*Y+E*(5*w)+x*(5*F)+O*(5*z)+f*(5*M);_=c>>>13,c&=8191,c+=v*(5*R)+u*(5*N)+y*(5*K)+p*(5*G)+n*(5*X),_+=c>>>13,c&=8191;let o=_+S*X+E*Y+x*(5*w)+O*(5*F)+f*(5*z);_=o>>>13,o&=8191,o+=v*(5*M)+u*(5*R)+y*(5*N)+p*(5*K)+n*(5*G),_+=o>>>13,o&=8191;let e=_+S*G+E*X+x*Y+O*(5*w)+f*(5*F);_=e>>>13,e&=8191,e+=v*(5*z)+u*(5*M)+y*(5*R)+p*(5*N)+n*(5*K),_+=e>>>13,e&=8191;let g=_+S*K+E*G+x*X+O*Y+f*(5*w);_=g>>>13,g&=8191,g+=v*(5*F)+u*(5*z)+y*(5*M)+p*(5*R)+n*(5*N),_+=g>>>13,g&=8191;let K0=_+S*N+E*K+x*G+O*X+f*Y;_=K0>>>13,K0&=8191,K0+=v*(5*w)+u*(5*F)+y*(5*z)+p*(5*M)+n*(5*R),_+=K0>>>13,K0&=8191;let T0=_+S*R+E*N+x*K+O*G+f*X;_=T0>>>13,T0&=8191,T0+=v*Y+u*(5*w)+y*(5*F)+p*(5*z)+n*(5*M),_+=T0>>>13,T0&=8191;let A0=_+S*M+E*R+x*N+O*K+f*G;_=A0>>>13,A0&=8191,A0+=v*X+u*Y+y*(5*w)+p*(5*F)+n*(5*z),_+=A0>>>13,A0&=8191;let _0=_+S*z+E*M+x*R+O*N+f*K;_=_0>>>13,_0&=8191,_0+=v*G+u*X+y*Y+p*(5*w)+n*(5*F),_+=_0>>>13,_0&=8191;let j0=_+S*F+E*z+x*M+O*R+f*N;_=j0>>>13,j0&=8191,j0+=v*K+u*G+y*X+p*Y+n*(5*w),_+=j0>>>13,j0&=8191;let L0=_+S*w+E*F+x*z+O*M+f*R;_=L0>>>13,L0&=8191,L0+=v*N+u*K+y*G+p*X+n*Y,_+=L0>>>13,L0&=8191,_=(_<<2)+_|0,_=_+c|0,c=_&8191,_=_>>>13,o+=_,Q[0]=c,Q[1]=o,Q[2]=e,Q[3]=g,Q[4]=K0,Q[5]=T0,Q[6]=A0,Q[7]=_0,Q[8]=j0,Q[9]=L0}finalize(){let{h:V,pad:$}=this,Z=new Uint16Array(10),J=V[1]>>>13;V[1]&=8191;for(let Y=2;Y<10;Y++)V[Y]+=J,J=V[Y]>>>13,V[Y]&=8191;V[0]+=J*5,J=V[0]>>>13,V[0]&=8191,V[1]+=J,J=V[1]>>>13,V[1]&=8191,V[2]+=J,Z[0]=V[0]+5,J=Z[0]>>>13,Z[0]&=8191;for(let Y=1;Y<10;Y++)Z[Y]=V[Y]+J,J=Z[Y]>>>13,Z[Y]&=8191;Z[9]-=8192;let Q=(J^1)-1;for(let Y=0;Y<10;Y++)Z[Y]&=Q;Q=~Q;for(let Y=0;Y<10;Y++)V[Y]=V[Y]&Q|Z[Y];V[0]=(V[0]|V[1]<<13)&65535,V[1]=(V[1]>>>3|V[2]<<10)&65535,V[2]=(V[2]>>>6|V[3]<<7)&65535,V[3]=(V[3]>>>9|V[4]<<4)&65535,V[4]=(V[4]>>>12|V[5]<<1|V[6]<<14)&65535,V[5]=(V[6]>>>2|V[7]<<11)&65535,V[6]=(V[7]>>>5|V[8]<<8)&65535,V[7]=(V[8]>>>8|V[9]<<5)&65535;let W=V[0]+$[0];V[0]=W&65535;for(let Y=1;Y<8;Y++)W=(V[Y]+$[Y]|0)+(W>>>16)|0,V[Y]=W&65535;X0(Z)}update(V){dV(this);let{buffer:$,blockLen:Z}=this;V=wV(V);let J=V.length;for(let Q=0;Q<J;){let W=Math.min(Z-this.pos,J-Q);if(W===Z){for(;Z<=J-Q;Q+=Z)this.process(V,Q);continue}if($.set(V.subarray(Q,Q+W),this.pos),this.pos+=W,Q+=W,this.pos===Z)this.process($,0,!1),this.pos=0}return this}destroy(){X0(this.h,this.r,this.buffer,this.pad)}digestInto(V){dV(this),VZ(V,this),this.finished=!0;let{buffer:$,h:Z}=this,{pos:J}=this;if(J){$[J++]=1;for(;J<16;J++)$[J]=0;this.process($,0,!0)}this.finalize();let Q=0;for(let W=0;W<8;W++)V[Q++]=Z[W]>>>0,V[Q++]=Z[W]>>>8;return V}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Z=V.slice(0,$);return this.destroy(),Z}}function FJ(V){let $=(J,Q)=>V(Q).update(wV(J)).digest(),Z=V(new Uint8Array(32));return $.outputLen=Z.outputLen,$.blockLen=Z.blockLen,$.create=(J)=>V(J),$}var tV=FJ((V)=>new GZ(V));function UJ(V,$,Z,J,Q,W=20){let Y=V[0],X=$[0],G=$[1],K=$[2],N=$[3],R=V[1],M=Z[0],z=Z[1],F=Q,w=0,q=V[2],H=$[4],C=$[5],T=$[6],U=$[7],A=V[3],L=Y,k=X,S=G,E=K,x=N,O=R,f=M,v=z,u=F,y=w,p=q,n=H,_=C,c=T,o=U,e=A;for(let K0=0;K0<W;K0+=2)x^=D(L+_|0,7),u^=D(x+L|0,9),_^=D(u+x|0,13),L^=D(_+u|0,18),y^=D(O+k|0,7),c^=D(y+O|0,9),k^=D(c+y|0,13),O^=D(k+c|0,18),o^=D(p+f|0,7),S^=D(o+p|0,9),f^=D(S+o|0,13),p^=D(f+S|0,18),E^=D(e+n|0,7),v^=D(E+e|0,9),n^=D(v+E|0,13),e^=D(n+v|0,18),k^=D(L+E|0,7),S^=D(k+L|0,9),E^=D(S+k|0,13),L^=D(E+S|0,18),f^=D(O+x|0,7),v^=D(f+O|0,9),x^=D(v+f|0,13),O^=D(x+v|0,18),n^=D(p+y|0,7),u^=D(n+p|0,9),y^=D(u+n|0,13),p^=D(y+u|0,18),_^=D(e+o|0,7),c^=D(_+e|0,9),o^=D(c+_|0,13),e^=D(o+c|0,18);let g=0;J[g++]=Y+L|0,J[g++]=X+k|0,J[g++]=G+S|0,J[g++]=K+E|0,J[g++]=N+x|0,J[g++]=R+O|0,J[g++]=M+f|0,J[g++]=z+v|0,J[g++]=F+u|0,J[g++]=w+y|0,J[g++]=q+p|0,J[g++]=H+n|0,J[g++]=C+_|0,J[g++]=T+c|0,J[g++]=U+o|0,J[g++]=A+e|0}function qJ(V,$,Z,J){let Q=V[0],W=$[0],Y=$[1],X=$[2],G=$[3],K=V[1],N=Z[0],R=Z[1],M=Z[2],z=Z[3],F=V[2],w=$[4],q=$[5],H=$[6],C=$[7],T=V[3];for(let A=0;A<20;A+=2)G^=D(Q+q|0,7),M^=D(G+Q|0,9),q^=D(M+G|0,13),Q^=D(q+M|0,18),z^=D(K+W|0,7),H^=D(z+K|0,9),W^=D(H+z|0,13),K^=D(W+H|0,18),C^=D(F+N|0,7),Y^=D(C+F|0,9),N^=D(Y+C|0,13),F^=D(N+Y|0,18),X^=D(T+w|0,7),R^=D(X+T|0,9),w^=D(R+X|0,13),T^=D(w+R|0,18),W^=D(Q+X|0,7),Y^=D(W+Q|0,9),X^=D(Y+W|0,13),Q^=D(X+Y|0,18),N^=D(K+G|0,7),R^=D(N+K|0,9),G^=D(R+N|0,13),K^=D(G+R|0,18),w^=D(F+z|0,7),M^=D(w+F|0,9),z^=D(M+w|0,13),F^=D(z+M|0,18),q^=D(T+C|0,7),H^=D(q+T|0,9),C^=D(H+q|0,13),T^=D(C+H|0,18);let U=0;J[U++]=Q,J[U++]=K,J[U++]=F,J[U++]=T,J[U++]=N,J[U++]=R,J[U++]=M,J[U++]=z}var eV=XZ(UJ,{counterRight:!0,extendNonceFn:qJ}),V$=JZ({blockSize:64,nonceLength:24,tagLength:16},(V,$)=>{return{encrypt(Z,J){J=aV(Z.length+32,J,!1);let Q=J.subarray(0,32),W=J.subarray(32);J.set(Z,32),X0(Q),eV(V,$,J,J);let Y=tV(W,Q);return J.set(Y,16),X0(J.subarray(0,16),Y),J.subarray(16)},decrypt(Z,J){l(Z),J=aV(Z.length+32,J,!1);let Q=J.subarray(0,32),W=J.subarray(32,48),Y=J.subarray(48);J.set(Z,32),X0(Q);let X=eV(V,$,Q,Q),G=tV(Y,X);if(!ZZ(W,G))throw Error("invalid tag");return eV(V,$,J.subarray(16),J.subarray(16)),X0(Q,W,G),Y}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function PJ(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function h0(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function C0(V,...$){if(!PJ(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function r0(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function UV(V,$){C0(V);let Z=$.outputLen;if(V.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function KZ(V){return new Uint8Array(V.buffer,V.byteOffset,V.byteLength)}function x0(V){return new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4))}function B0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function c0(V,$){return V<<32-$|V>>>$}var NZ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function RZ(V){return V<<24&4278190080|V<<8&16711680|V>>>8&65280|V>>>24&255}var IZ=NZ?(V)=>V:(V)=>RZ(V);function OJ(V){for(let $=0;$<V.length;$++)V[$]=RZ(V[$]);return V}var s=NZ?(V)=>V:OJ;function HJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function f0(V){if(typeof V==="string")V=HJ(V);return C0(V),V}class $${}function wZ(V){let $=(J,Q)=>V(Q).update(f0(J)).digest(),Z=V({});return $.outputLen=Z.outputLen,$.blockLen=Z.blockLen,$.create=(J)=>V(J),$}var zZ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qV=BigInt(4294967295),MZ=BigInt(32);function Z$(V,$=!1){if($)return{h:Number(V&qV),l:Number(V>>MZ&qV)};return{h:Number(V>>MZ&qV)|0,l:Number(V&qV)|0}}function I0(V,$,Z,J,Q){return V=V+$+Q|0,J=c0(J^V,16),Z=Z+J|0,$=c0($^Z,12),{a:V,b:$,c:Z,d:J}}function w0(V,$,Z,J,Q){return V=V+$+Q|0,J=c0(J^V,8),Z=Z+J|0,$=c0($^Z,7),{a:V,b:$,c:Z,d:J}}class J$ extends $${constructor(V,$){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,h0(V),h0($),this.blockLen=V,this.outputLen=$,this.buffer=new Uint8Array(V),this.buffer32=x0(this.buffer)}update(V){r0(this),V=f0(V),C0(V);let{blockLen:$,buffer:Z,buffer32:J}=this,Q=V.length,W=V.byteOffset,Y=V.buffer;for(let X=0;X<Q;){if(this.pos===$)s(J),this.compress(J,0,!1),s(J),this.pos=0;let G=Math.min($-this.pos,Q-X),K=W+X;if(G===$&&!(K%4)&&X+G<Q){let N=new Uint32Array(Y,K,Math.floor((Q-X)/4));s(N);for(let R=0;X+$<Q;R+=J.length,X+=$)this.length+=$,this.compress(N,R,!1);s(N);continue}Z.set(V.subarray(X,X+G),this.pos),this.pos+=G,this.length+=G,X+=G}return this}digestInto(V){r0(this),UV(V,this);let{pos:$,buffer32:Z}=this;this.finished=!0,B0(this.buffer.subarray($)),s(Z),this.compress(Z,0,!0),s(Z);let J=x0(V);this.get().forEach((Q,W)=>J[W]=IZ(Q))}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Z=V.slice(0,$);return this.destroy(),Z}_cloneInto(V){let{buffer:$,length:Z,finished:J,destroyed:Q,outputLen:W,pos:Y}=this;return V||(V=new this.constructor({dkLen:W})),V.set(...this.get()),V.buffer.set($),V.destroyed=Q,V.finished=J,V.length=Z,V.pos=Y,V.outputLen=W,V}clone(){return this._cloneInto()}}function Q$(V,$,Z,J,Q,W,Y,X,G,K,N,R,M,z,F,w,q,H,C,T){let U=0;for(let A=0;A<J;A++)({a:Q,b:G,c:M,d:q}=I0(Q,G,M,q,Z[$+V[U++]])),{a:Q,b:G,c:M,d:q}=w0(Q,G,M,q,Z[$+V[U++]]),{a:W,b:K,c:z,d:H}=I0(W,K,z,H,Z[$+V[U++]]),{a:W,b:K,c:z,d:H}=w0(W,K,z,H,Z[$+V[U++]]),{a:Y,b:N,c:F,d:C}=I0(Y,N,F,C,Z[$+V[U++]]),{a:Y,b:N,c:F,d:C}=w0(Y,N,F,C,Z[$+V[U++]]),{a:X,b:R,c:w,d:T}=I0(X,R,w,T,Z[$+V[U++]]),{a:X,b:R,c:w,d:T}=w0(X,R,w,T,Z[$+V[U++]]),{a:Q,b:K,c:F,d:T}=I0(Q,K,F,T,Z[$+V[U++]]),{a:Q,b:K,c:F,d:T}=w0(Q,K,F,T,Z[$+V[U++]]),{a:W,b:N,c:w,d:q}=I0(W,N,w,q,Z[$+V[U++]]),{a:W,b:N,c:w,d:q}=w0(W,N,w,q,Z[$+V[U++]]),{a:Y,b:R,c:M,d:H}=I0(Y,R,M,H,Z[$+V[U++]]),{a:Y,b:R,c:M,d:H}=w0(Y,R,M,H,Z[$+V[U++]]),{a:X,b:G,c:z,d:C}=I0(X,G,z,C,Z[$+V[U++]]),{a:X,b:G,c:z,d:C}=w0(X,G,z,C,Z[$+V[U++]]);return{v0:Q,v1:W,v2:Y,v3:X,v4:G,v5:K,v6:N,v7:R,v8:M,v9:z,v10:F,v11:w,v12:q,v13:H,v14:C,v15:T}}var G0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},z0=zZ.slice(),FZ=(()=>{let V=Array.from({length:16},(J,Q)=>Q),$=(J)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((Q)=>J[Q]),Z=[];for(let J=0,Q=V;J<7;J++,Q=$(Q))Z.push(...Q);return Uint8Array.from(Z)})();class W$ extends J${constructor(V={},$=0){super(64,V.dkLen===void 0?32:V.dkLen);this.chunkPos=0,this.chunksDone=0,this.flags=0,this.stack=[],this.posOut=0,this.bufferOut32=new Uint32Array(16),this.chunkOut=0,this.enableXOF=!0;let{key:Z,context:J}=V,Q=J!==void 0;if(Z!==void 0){if(Q)throw Error('Only "key" or "context" can be specified at same time');let W=f0(Z).slice();C0(W,32),this.IV=x0(W),s(this.IV),this.flags=$|G0.KEYED_HASH}else if(Q){let W=f0(J),Y=new W$({dkLen:32},G0.DERIVE_KEY_CONTEXT).update(W).digest();this.IV=x0(Y),s(this.IV),this.flags=$|G0.DERIVE_KEY_MATERIAL}else this.IV=z0.slice(),this.flags=$;this.state=this.IV.slice(),this.bufferOut=KZ(this.bufferOut32)}get(){return[]}set(){}b2Compress(V,$,Z,J=0){let{state:Q,pos:W}=this,{h:Y,l:X}=Z$(BigInt(V),!0),{v0:G,v1:K,v2:N,v3:R,v4:M,v5:z,v6:F,v7:w,v8:q,v9:H,v10:C,v11:T,v12:U,v13:A,v14:L,v15:k}=Q$(FZ,J,Z,7,Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7],z0[0],z0[1],z0[2],z0[3],Y,X,W,$);Q[0]=G^q,Q[1]=K^H,Q[2]=N^C,Q[3]=R^T,Q[4]=M^U,Q[5]=z^A,Q[6]=F^L,Q[7]=w^k}compress(V,$=0,Z=!1){let J=this.flags;if(!this.chunkPos)J|=G0.CHUNK_START;if(this.chunkPos===15||Z)J|=G0.CHUNK_END;if(!Z)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,J,V,$),this.chunkPos+=1,this.chunkPos===16||Z){let Q=this.state;this.state=this.IV.slice();for(let W,Y=this.chunksDone+1;Z||!(Y&1);Y>>=1){if(!(W=this.stack.pop()))break;this.buffer32.set(W,0),this.buffer32.set(Q,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|G0.PARENT,this.buffer32,0),Q=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(Q)}this.pos=0}_cloneInto(V){V=super._cloneInto(V);let{IV:$,flags:Z,state:J,chunkPos:Q,posOut:W,chunkOut:Y,stack:X,chunksDone:G}=this;return V.state.set(J.slice()),V.stack=X.map((K)=>Uint32Array.from(K)),V.IV.set($),V.flags=Z,V.chunkPos=Q,V.chunksDone=G,V.posOut=W,V.chunkOut=Y,V.enableXOF=this.enableXOF,V.bufferOut32.set(this.bufferOut32),V}destroy(){this.destroyed=!0,B0(this.state,this.buffer32,this.IV,this.bufferOut32),B0(...this.stack)}b2CompressOut(){let{state:V,pos:$,flags:Z,buffer32:J,bufferOut32:Q}=this,{h:W,l:Y}=Z$(BigInt(this.chunkOut++));s(J);let{v0:X,v1:G,v2:K,v3:N,v4:R,v5:M,v6:z,v7:F,v8:w,v9:q,v10:H,v11:C,v12:T,v13:U,v14:A,v15:L}=Q$(FZ,0,J,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],z0[0],z0[1],z0[2],z0[3],Y,W,$,Z);Q[0]=X^w,Q[1]=G^q,Q[2]=K^H,Q[3]=N^C,Q[4]=R^T,Q[5]=M^U,Q[6]=z^A,Q[7]=F^L,Q[8]=V[0]^w,Q[9]=V[1]^q,Q[10]=V[2]^H,Q[11]=V[3]^C,Q[12]=V[4]^T,Q[13]=V[5]^U,Q[14]=V[6]^A,Q[15]=V[7]^L,s(J),s(Q),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,B0(this.buffer.subarray(this.pos));let V=this.flags|G0.ROOT;if(this.stack.length)V|=G0.PARENT,s(this.buffer32),this.compress(this.buffer32,0,!0),s(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else V|=(!this.chunkPos?G0.CHUNK_START:0)|G0.CHUNK_END;this.flags=V,this.b2CompressOut()}writeInto(V){r0(this,!1),C0(V),this.finish();let{blockLen:$,bufferOut:Z}=this;for(let J=0,Q=V.length;J<Q;){if(this.posOut>=$)this.b2CompressOut();let W=Math.min($-this.posOut,Q-J);V.set(Z.subarray(this.posOut,this.posOut+W),J),this.posOut+=W,J+=W}return V}xofInto(V){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(V)}xof(V){return h0(V),this.xofInto(new Uint8Array(V))}digestInto(V){if(UV(V,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto(V),this.destroy(),V}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var UZ=wZ((V)=>new W$(V));var Y$=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function qZ(V){let $=new Uint8Array(Y$.length+32);return $.set(Y$),$.set(V.subarray(0,32),Y$.length),$}function PZ(V){return typeof V==="string"?new TextEncoder().encode(V):V}function m0(V){let $=new ArrayBuffer(V.byteLength);return new Uint8Array($).set(V),$}class X${verifyKeys=new Map;signKeys=new Map;async genRandomBytes(V){return MV(V)}async gen256BitSecureRandomSeed(){return MV(32)}async encryptXSalsa20Poly1305Combined(V,$){let Z=MV(24),Q=V$($,Z).encrypt(V);return new Uint8Array([...Z,...Q])}async decryptXSalsa20Poly1305Combined(V,$){let Z=V.slice(0,24),J=V.slice(24);return V$($,Z).decrypt(J)}async deriveEd25519KeyPair(V){let $=V,Z=qZ($),J=await globalThis.crypto.subtle.importKey("pkcs8",m0(Z),{name:"Ed25519"},!0,["sign"]),Q=await globalThis.crypto.subtle.exportKey("jwk",J);if(typeof Q.x!=="string")throw Error("Ed25519 JWK missing x");let W=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:Q.x},{name:"Ed25519"},!0,["verify"]),Y=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",W)),X=new Uint8Array(64);return X.set($,0),X.set(Y,32),this.signKeys.set(Q0($),J),this.verifyKeys.set(Q0(Y),W),{keyType:"ed25519",privateKey:X,publicKey:Y}}async importSignKey(V){let $=V.subarray(0,32),Z=Q0($),J=this.signKeys.get(Z);if(J)return J;let Q=qZ($),W=await globalThis.crypto.subtle.importKey("pkcs8",m0(Q),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Z,W),W}async importVerifyKey(V){let $=Q0(V),Z=this.verifyKeys.get($);if(Z)return Z;let J=await globalThis.crypto.subtle.importKey("raw",m0(V),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set($,J),J}async signEd25519(V,$){let Z=PZ(V),J=await this.importSignKey($),Q=await globalThis.crypto.subtle.sign({name:"Ed25519"},J,m0(Z));return new Uint8Array(Q)}async checkSigEd25519(V,$,Z){let J=PZ($);try{let Q=await this.importVerifyKey(Z);return await globalThis.crypto.subtle.verify({name:"Ed25519"},Q,m0(V),m0(J))}catch{return!1}}async blake3(V){return UZ(V)}}var CJ=new X$,g0=CJ;var $G=Symbol("EntityID");function OZ(V){return"type"in V}var ZG=Symbol("MasterSeed"),JG=Symbol("DerivationSeed"),QG=Symbol("PublicKey"),WG=Symbol("PrivateKey"),YG=Symbol("HostSpecificKeyPair"),XG=Symbol("Hash");function DJ(V){if(!V)return!1;if(typeof V!=="object")return!1;if("body"in V===!1)return!1;if("type"in V===!1)return!1;return!0}function TJ(V){if(!V.bod||V.bod.length===0){let J={off:V.off,ctr:V.ctr,eid:V.eid};return P(J)}let $=jV(V.bod);if(DJ($)===!1)return console.warn("msg body invalid",$),I(14);let Z={off:V.off,ctr:V.ctr,eid:V.eid,gid:$.gid,pid:$.pid,type:$.type,body:$.body};return P(Z)}class PV{applier;emitter=new y0;clearer;onTypes;constructor(V,$,Z){this.applier=V;this.clearer=$,this.onTypes=Z}apply=async(V)=>{let $=[],Z=[];for(let Y of V){let[X,G]=TJ(Y);if(Z.push(G),G!==0)continue;$.push(X)}let{stats:J,types:Q}=await this.applier($),W=[];for(let Y=0;Y<V.length;Y++){let X=Z[Y],G=J[Y];if(X!==0){W.push(X);continue}if(G!==0){W.push(G);continue}W.push(0)}for(let Y of Q)this.emitter.emit(Y,null);if(Q.size>0)this.onTypes?.(Q);return W};clear=async()=>{let V=await this.clearer();if(V!==0)return V;return this.emitter.emitAll(null),V};notify=(V)=>{for(let $ of V)this.emitter.emit($,null)};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}function HZ(V,$){let Z=new m($.eid),[J,Q]=Z.readStruct(Y0);if(Q!==0)return I(Q);let W=new Date(J.ts.getTime()+$.off);if(V!==void 0&&W<=V.updatedAt)return I(15);if(OZ($))return P({eid:$.eid,gid:$.gid,pid:$.pid,type:$.type,createdAt:J.ts,updatedAt:W,ctr:$.ctr,body:$.body});else return P(void 0)}var b="entities",OV="entity_type_created_at",G$="entity_type_updated_at",K$="entity_type_group_id",N$="entity_type_parent_id";function AJ(V){let $={bod:V.body,crd:V.createdAt,...V.ctr!==0?{ctr:V.ctr}:{},eid:d(V.eid),gid:V.gid,pid:V.pid?d(V.pid):void 0,typ:V.type,upd:V.updatedAt};if($.gid===void 0)delete $.gid;if($.pid===void 0)delete $.pid;if($.ctr===void 0)delete $.ctr;return $}function v0(V){return{body:V.bod,createdAt:V.crd,updatedAt:V.upd,ctr:V.ctr??0,type:V.typ,eid:N0(V.eid),gid:V.gid,pid:V.pid?N0(V.pid):void 0}}class CZ{db;async init(){this.db=await new Promise((V,$)=>{let Z=indexedDB.open("db",11);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!Q)throw Error("Transaction is null during upgrade");if(!J.objectStoreNames.contains(b))J.createObjectStore(b,{keyPath:"eid",autoIncrement:!1});let W=Q.objectStore(b);if(!W.indexNames.contains(OV))W.createIndex(OV,["typ","crd"],{unique:!1});if(!W.indexNames.contains(G$))W.createIndex(G$,["typ","upd"],{unique:!1});if(!W.indexNames.contains(K$))W.createIndex(K$,["typ","gid"],{unique:!1});if(!W.indexNames.contains(N$))W.createIndex(N$,["typ","pid"],{unique:!1})},Z.onsuccess=()=>V(Z.result),Z.onerror=()=>$(Z.error)})}apply=async(V)=>{let $=new Set;if(!this.db)return{stats:V.map(()=>16),types:$};let Z=this.db.transaction(b,"readwrite"),J=Z.objectStore(b);return new Promise((Q)=>{let W=Array(V.length).fill(0);if(V.length<1){Q({stats:[],types:$});return}Z.oncomplete=()=>{Q({stats:W,types:$})},Z.onerror=()=>{for(let X=0;X<W.length;X++)if(W[X]===void 0)W[X]=18;Q({stats:W,types:$})};let Y=new Map;for(let X=0;X<V.length;X++){let G=V[X],K=d(G.eid),N={op:G,index:X},R=Y.get(K);if(R)R.push(N);else Y.set(K,[N])}for(let[X,G]of Y){if(G.length<1)continue;let K=J.get(X);K.onsuccess=()=>{let N=K.result,R=N?v0(N):void 0;for(let{op:M,index:z}of G){let[F,w]=HZ(R,M);if(w!==0){W[z]=w;continue}if(F)$.add(F.type);else if(R)$.add(R.type);R=F}if(R){let M=AJ(R),z=J.put(M);z.onerror=(F)=>{F.preventDefault();for(let{index:w}of G)W[w]=18}}else{let M=J.delete(X);M.onerror=()=>{for(let{index:z}of G)W[z]=18}}},K.onerror=()=>{for(let{index:N}of G)W[N]=18}}})};async clear(){if(!this.db)return 16;let V=this.db.transaction(b,"readwrite"),$=V.objectStore(b);return new Promise((Z)=>{V.oncomplete=()=>Z(0),V.onerror=()=>Z(18),$.clear()})}async getEnt(V){if(!this.db)return I(16);let $=d(V),J=this.db.transaction(b,"readonly").objectStore(b);return new Promise((Q)=>{let W=J.get($);W.onsuccess=()=>{let Y=W.result;if(!Y)Q(P(void 0));else{let X=v0(Y);Q(P(X))}},W.onerror=()=>Q(I(18))})}async getAllOfTypeUpdatedBetween(V,$,Z){if(!this.db)return I(16);let Q=this.db.transaction(b,"readonly").objectStore(b).index(G$);return new Promise((W)=>{let Y=Q.getAll(IDBKeyRange.bound([V,$],[V,Z]));Y.onsuccess=()=>{let X=Y.result;W(P(X.map(v0)))},Y.onerror=()=>W(I(18))})}async getGroupMembers(V,$){if(!this.db)return I(16);let J=this.db.transaction(b,"readonly").objectStore(b).index(K$);return new Promise((Q)=>{let W=J.getAll(IDBKeyRange.only([V,$]));W.onsuccess=()=>{let Y=W.result;Q(P(Y.map(v0)))},W.onerror=()=>Q(I(18))})}async getAllOfType(V){if(!this.db)return I(16);let Z=this.db.transaction(b,"readonly").objectStore(b).index(OV);return new Promise((J)=>{let Q=Z.getAll(IDBKeyRange.bound([V],[V,[]]));Q.onsuccess=()=>{let W=Q.result;J(P(W.map(v0)))},Q.onerror=()=>J(I(18))})}async getAllEntities(V){if(!this.db)return I(16);if("pid"in V){let $=d(V.pid),J=this.db.transaction(b,"readonly").objectStore(b).index(N$);return new Promise((Q)=>{let W=J.getAll(IDBKeyRange.only([V.type,$]));W.onsuccess=()=>{let X=W.result.map(v0);Q(P(X))},W.onerror=()=>Q(I(18))})}else if("gid"in V)return await this.getGroupMembers(V.type,V.gid);else if("updatedBetween"in V)return await this.getAllOfTypeUpdatedBetween(V.type,V.updatedBetween.start,V.updatedBetween.end);return await this.getAllOfType(V.type)}async getEntities(V){let[$,Z]=await this.getAllEntities(V);if(Z!==0)return I(Z);return P($)}async countEntities({type:V}){if(!this.db)return I(16);let Z=this.db.transaction(b,"readonly").objectStore(b).index(OV);return new Promise((J)=>{let Q=IDBKeyRange.bound([V],[V,[]]),W=Z.count(Q);W.onsuccess=()=>J(P(W.result)),W.onerror=()=>J(I(18))})}}async function DZ(){let V=new CZ;return await V.init(),V}class R${db;constructor(V){this.db=V}async enq(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction($0,"readwrite"),J=Z.objectStore($0);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=`${Y.host}:${Y.seq}`;J.put(Y,X)}})}async deq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction($0,"readwrite"),Q=J.objectStore($0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let G=`${V}:${X}`;Q.delete(G)}})}async list(){let $=this.db.transaction($0,"readonly").objectStore($0);return new Promise((Z,J)=>{let Q=$.getAll();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async count(){let $=this.db.transaction($0,"readonly").objectStore($0);return new Promise((Z,J)=>{let Q=$.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction($0,"readwrite"),$=V.objectStore($0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}function TZ(V){return{label:V.label,handle:new URL(V.handle),idx:V.idx,lastSeq:V.lastSeq||0,clockOffset:V.clockOffset,subscription:V.subscription}}class I${db;constructor(V){this.db=V}async add(V){return this.put(V)}async put(V){let $={...V,handle:V.handle.toString(),lastSeq:V.lastSeq??0},Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error),J.put($)})}async touch(V,$){let Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);let Y=J.get(V);Y.onsuccess=()=>{let X=Y.result;if(!X)return;let G=X.lastSeq||0;if($<=G)return;J.put({...X,lastSeq:$})}})}async get(V){let Z=this.db.transaction(t,"readonly").objectStore(t);return new Promise((J,Q)=>{let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)J(void 0);else J(TZ(Y))},W.onerror=()=>Q(W.error)})}async set(V,$){let Z=await this.get(V);if(!Z)return 13;try{return await this.put({...Z,...$}),0}catch{return 18}}async del(V){let $=this.db.transaction(t,"readwrite"),Z=$.objectStore(t);return new Promise((J,Q)=>{$.oncomplete=()=>J(),$.onerror=()=>Q($.error),Z.delete(V)})}async list(){let $=this.db.transaction(t,"readonly").objectStore(t);return new Promise((Z,J)=>{let Q=$.getAll();Q.onsuccess=()=>{let W=Q.result;Z(W.map(TZ))},Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(t,"readwrite"),$=V.objectStore(t);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}function _J(V){return V===!0||V==="t"}function w$(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld===void 0?!1:_J(V.apld)}}async function d0(V,$,Z){let J=w$($),Q=J.body?.length??0,W;if(J.body&&Q>0)W=await Z.blake3(J.body);let Y={eid:J.eid,off:J.off??0,ctr:J.ctr??0,len:Q,hsh:W};return{hash:V,head:Y,body:J.body,applied:J.apld}}function AZ(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld?"t":"f"}}class z${crypto;db;constructor(V,$){this.crypto=$;this.db=V}async add(V){let $=this.db.transaction(i,"readwrite"),Z=$.objectStore(i);return new Promise((J)=>{if(V.length===0){J([]);return}let Q=Array(V.length).fill(0);$.oncomplete=()=>J(Q),$.onerror=()=>{for(let W=0;W<Q.length;W++)Q[W]=18;J(Q)};for(let W=0;W<V.length;W++){let{key:Y,data:X}=V[W],G=d(Y),K=Z.put(AZ(X),G);K.onerror=(N)=>{N.preventDefault(),Q[W]=18}}})}async del(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(i,"readwrite"),J=Z.objectStore(i);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=d(Y);J.delete(X)}})}async get(V){let Z=this.db.transaction(i,"readonly").objectStore(i);return new Promise((J,Q)=>{let W=d(V),Y=Z.get(W);Y.onsuccess=async()=>{let X=Y.result;if(X)J(await d0(V,X,this.crypto));else J(void 0)},Y.onerror=()=>Q(Y.error)})}async has(V){return await this.get(V)!==void 0}async list(){let $=this.db.transaction(i,"readonly").objectStore(i);return new Promise((Z,J)=>{let Q=[],W=$.openCursor();W.onsuccess=async(Y)=>{let X=Y.target.result;if(X){let{key:G,value:K}=X,N=N0(G),R=await d0(N,K,this.crypto);Q.push(R),X.continue()}else Z(Q)},W.onerror=()=>J(W.error)})}async last(V){let Z=this.db.transaction(i,"readonly").objectStore(i);return new Promise((J,Q)=>{let W,Y=Z.openCursor();Y.onsuccess=async(X)=>{let G=X.target.result;if(G){let{key:K,value:N}=G;if(O0(V,N.eid)){if(!W||(N.ctr??0)>(W.data.ctr??0)||(N.ctr??0)===(W.data.ctr??0)&&(N.off??0)>(W.data.off??0))W={key:K,data:N}}G.continue()}else if(W){let K=N0(W.key);J(await d0(K,W.data,this.crypto))}else J(void 0)},Y.onerror=()=>Q(Y.error)})}async listUnapplied(){let Z=this.db.transaction(i,"readonly").objectStore(i).index(HV);return new Promise((J,Q)=>{let W=[],Y=Z.openCursor(IDBKeyRange.only("f"));Y.onsuccess=(X)=>{let G=X.target.result;if(G){let{primaryKey:K,value:N}=G;W.push({hash:N0(K),data:N}),G.continue()}else Promise.all(W.map(({hash:K,data:N})=>d0(K,N,this.crypto))).then(J).catch(Q)},Y.onerror=()=>Q(Y.error)})}async markApplied(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(i,"readwrite"),J=Z.objectStore(i);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=d(Y),G=J.get(X);G.onsuccess=()=>{let K=G.result;if(!K)return;let N=w$(K);J.put(AZ({...N,apld:!0}),X)},G.onerror=(K)=>{K.preventDefault()}}})}async wipe(){let V=this.db.transaction(i,"readwrite"),$=V.objectStore(i);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}class CV{seed;crypto;constructor(V,$){this.seed=V,this.crypto=$}async deriveFromKDM(V){let $=p0(this.seed,V);return await this.crypto.blake3($)}async derive(V,$=0){let Z=new TextEncoder().encode(V),J=new Uint8Array(8);new DataView(J.buffer).setBigUint64(0,BigInt($),!1);let Q=p0(Z,J);return await this.deriveFromKDM(Q)}}class M${enclave;db;constructor(V){this.db=V}async save(V){let $=Q0(V),Z=this.db.transaction(M0,"readwrite"),J=Z.objectStore(M0);return new Promise((Q,W)=>{Z.oncomplete=()=>{this.enclave=new CV(V,g0),Q(this.enclave)},Z.onerror=()=>W(Z.error),J.put($,"seed")})}async load(){if(this.enclave)return this.enclave;let $=this.db.transaction(M0,"readonly").objectStore(M0);return new Promise((Z,J)=>{let Q=$.get("seed");Q.onsuccess=()=>{let W=Q.result;if(!W)Z(void 0);else{let Y=QV(W);this.enclave=new CV(Y,g0),Z(this.enclave)}},Q.onerror=()=>J(Q.error)})}async wipe(){this.enclave=void 0;let V=this.db.transaction(M0,"readwrite"),$=V.objectStore(M0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.delete("seed")})}}class F${db;constructor(V){this.db=V}async enq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(Z0,"readwrite"),Q=J.objectStore(Z0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let G=Q0(X);Q.put({host:V,hash:G})}})}async deq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(Z0,"readwrite"),Q=J.objectStore(Z0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let G=Q0(X);Q.delete([V,G])}})}async list(V){let Z=this.db.transaction(Z0,"readonly").objectStore(Z0);return new Promise((J,Q)=>{let W=Z.getAll();W.onsuccess=()=>{let X=W.result.filter((G)=>G.host===V).map((G)=>G.hash);J(X.map((G)=>QV(G)))},W.onerror=()=>Q(W.error)})}async count(){let $=this.db.transaction(Z0,"readonly").objectStore(Z0);return new Promise((Z,J)=>{let Q=$.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(Z0,"readwrite"),$=V.objectStore(Z0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}var M0="seedMeta",t="hosts",Z0="uploadQueue",$0="downloadQueue",i="messages",HV="apld",jJ=3;class _Z{seed;hosts;uploads;downloads;messages;db;constructor(V,$){this.db=V,this.seed=new M$(V),this.hosts=new I$(V),this.uploads=new F$(V),this.downloads=new R$(V),this.messages=new z$(V,$)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function LJ(){return new Promise((V,$)=>{let Z=indexedDB.open("diplomatic-store-db",jJ);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!J.objectStoreNames.contains(M0))J.createObjectStore(M0);if(!J.objectStoreNames.contains(t))J.createObjectStore(t,{keyPath:"label"});if(!J.objectStoreNames.contains(Z0))J.createObjectStore(Z0,{keyPath:["host","hash"]});if(!J.objectStoreNames.contains($0))J.createObjectStore($0);let W;if(!J.objectStoreNames.contains(i))W=J.createObjectStore(i);else{if(!Q)throw Error("missing upgrade transaction for messages store");W=Q.objectStore(i)}if(!W.indexNames.contains(HV))W.createIndex(HV,"apld",{unique:!1})},Z.onsuccess=()=>V(Z.result),Z.onerror=()=>$(Z.error)})}async function jZ(V){let $=await LJ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new _Z($,V)}class U${client;post;whenReady;resolveReady;rejectReady;constructor(V){this.post=V,this.whenReady=new Promise(($,Z)=>{this.resolveReady=$,this.rejectReady=Z})}async init(){try{let V=await jZ(g0),$=await DZ(),Z=new PV($.apply,()=>$.clear(),(W)=>{this.post({kind:"dirty",types:Array.from(W)})}),J=Z.clear;Z.clear=async()=>{let W=await J();if(W===0)this.post({kind:"wiped"});return W};let Q=new rV(new SV,Z,V,y$,g0);this.client=Q,Q.clientState.listen(()=>{this.emitClientState()}),Q.xferState.listen(()=>{this.emitXferState()}),this.post({kind:"ready"}),this.markReady(),await this.emitClientState(),await this.emitXferState()}catch(V){let $=V instanceof Error?V:Error(String(V));throw this.failReady($),$}}markReady(){let V=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V()}failReady(V){let $=this.rejectReady;if(this.resolveReady=void 0,this.rejectReady=void 0,$)$(V)}requireClient(){if(!this.client)throw Error("WorkerRuntime not initialized");return this.client}async emitClientState(){let V=this.client;if(!V)return;let $=await V.clientState.get();this.post({kind:"clientState",state:$})}async emitXferState(){let V=this.client;if(!V)return;let $=await V.xferState.get();this.post({kind:"xferState",state:$})}hostFromSerialized(V){return{handle:new URL(V.handle),label:V.label,idx:V.idx}}async handle(V){await this.whenReady;let $=this.requireClient();switch(V.op){case"ping":return"pong";case"setSeed":{await $.setSeed(kJ(V.seed));return}case"link":{await $.link(this.hostFromSerialized(V.host),V.connect??!0);return}case"unlink":{await $.unlink(V.label);return}case"connect":{await $.connect(V.listen??!0,V.sync??!0);return}case"disconnect":{await $.disconnect();return}case"sync":return await $.sync();case"wipe":{await $.wipe();return}case"insertRaw":{let[Z,J]=await $.insertRaw(LZ(V.body));if(J!==0)throw new W0(J);return Z}case"upsertRaw":{let[Z,J]=await $.upsertRaw(o0(V.eid),V.body!==void 0?LZ(V.body):void 0,V.force);if(J!==0)throw new W0(J);return Z}case"insert":{let[Z,J]=await $.insert({type:V.params.type,body:V.params.body,gid:V.params.gid,pid:V.params.pid!==void 0?o0(V.params.pid):void 0});if(J!==0)throw new W0(J);return Z}case"upsert":{let[Z,J]=await $.upsert({type:V.params.type,body:V.params.body,eid:V.params.eid!==void 0?o0(V.params.eid):void 0,gid:V.params.gid,pid:V.params.pid!==void 0?o0(V.params.pid):void 0},V.force);if(J!==0)throw new W0(J);return Z}case"delete":{let[Z,J]=await $.delete(o0(V.eid));if(J!==0)throw new W0(J);return Z}case"import":{let Z=V.bytes.slice(),J=new Blob([Z]),Q=new File([J],"import.dip");return await $.import(Q)}case"export":{let[Z,J]=await $.exportBytes();if(J!==0)throw new W0(J);if(!Z)throw new W0(12);return Z}case"getClientState":return await $.clientState.get();case"getXferState":return await $.xferState.get();default:{let Z=V;throw Error("unknown worker command")}}}}class W0 extends Error{status;constructor(V){super(`WorkerStatusError: ${j[V]}`);this.status=V;this.name="WorkerStatusError"}}function q$(V,$){return{kind:"reply",id:V,ok:!0,result:$}}function P$(V,$){return{kind:"reply",id:V,ok:!1,status:$}}function kJ(V){if(V.length!==32)throw new W0(10);return V}function o0(V){return V}function LZ(V){return V}var D0=globalThis,kZ=new U$((V,$)=>{if($&&$.length>0)D0.postMessage(V,$);else D0.postMessage(V)});D0.onmessage=(V)=>{let $=V.data;if(!D$($))return;EJ($)};async function EJ(V){try{let $=await kZ.handle(V);if(V.op==="export"&&$ instanceof Uint8Array){let Z=$.slice();D0.postMessage(q$(V.id,Z),[Z.buffer]);return}D0.postMessage(q$(V.id,$))}catch($){if($ instanceof W0){D0.postMessage(P$(V.id,$.status));return}console.error("worker command failed",$),D0.postMessage(P$(V.id,12))}}kZ.init().catch((V)=>{console.error("worker init failed",V)});
|
|
1
|
+
var F0=64;var q$=32,P0=8;var o0=32;var O$=30000,H$=512,j;((C)=>{C[C.Success=0]="Success";C[C.InvalidSignature=3]="InvalidSignature";C[C.ClockOutOfSync=4]="ClockOutOfSync";C[C.UserNotRegistered=5]="UserNotRegistered";C[C.ServerMisconfigured=6]="ServerMisconfigured";C[C.MissingBody=7]="MissingBody";C[C.ExtraBodyContent=8]="ExtraBodyContent";C[C.MissingParam=9]="MissingParam";C[C.InvalidParam=10]="InvalidParam";C[C.InvalidRequest=11]="InvalidRequest";C[C.InternalError=12]="InternalError";C[C.NotFound=13]="NotFound";C[C.InvalidMessage=14]="InvalidMessage";C[C.NoChange=15]="NoChange";C[C.DatabaseClosed=16]="DatabaseClosed";C[C.StorageError=17]="StorageError";C[C.DatabaseError=18]="DatabaseError";C[C.HashMismatch=19]="HashMismatch";C[C.DecryptionError=20]="DecryptionError";C[C.NotImplemented=21]="NotImplemented";C[C.MissingSeed=22]="MissingSeed";C[C.OutOfBounds=23]="OutOfBounds";C[C.HostError=24]="HostError";C[C.CommunicationError=25]="CommunicationError";C[C.VarLimitExceeded=26]="VarLimitExceeded";C[C.InvalidResponse=27]="InvalidResponse";C[C.ConnectionClosed=28]="ConnectionClosed"})(j||={});function C$(V){if(!V||typeof V!=="object")return!1;if(!("op"in V)||!("id"in V))return!1;return typeof V.op==="string"&&typeof V.id==="number"}function T$(V){let $=V.length,Z=0,J=0;while(J<$){let Q=V.charCodeAt(J++);if((Q&4294967168)===0){Z++;continue}else if((Q&4294965248)===0)Z+=2;else{if(Q>=55296&&Q<=56319){if(J<$){let W=V.charCodeAt(J);if((W&64512)===56320)++J,Q=((Q&1023)<<10)+(W&1023)+65536}}if((Q&4294901760)===0)Z+=3;else Z+=4}}return Z}function SZ(V,$,Z){let J=V.length,Q=Z,W=0;while(W<J){let Y=V.charCodeAt(W++);if((Y&4294967168)===0){$[Q++]=Y;continue}else if((Y&4294965248)===0)$[Q++]=Y>>6&31|192;else{if(Y>=55296&&Y<=56319){if(W<J){let X=V.charCodeAt(W);if((X&64512)===56320)++W,Y=((Y&1023)<<10)+(X&1023)+65536}}if((Y&4294901760)===0)$[Q++]=Y>>12&15|224,$[Q++]=Y>>6&63|128;else $[Q++]=Y>>18&7|240,$[Q++]=Y>>12&63|128,$[Q++]=Y>>6&63|128}$[Q++]=Y&63|128}}var xZ=new TextEncoder,BZ=50;function fZ(V,$,Z){xZ.encodeInto(V,$.subarray(Z))}function A$(V,$,Z){if(V.length>BZ)fZ(V,$,Z);else SZ(V,$,Z)}var mZ=4096;function CV(V,$,Z){let J=$,Q=J+Z,W=[],Y="";while(J<Q){let X=V[J++];if((X&128)===0)W.push(X);else if((X&224)===192){let G=V[J++]&63;W.push((X&31)<<6|G)}else if((X&240)===224){let G=V[J++]&63,K=V[J++]&63;W.push((X&31)<<12|G<<6|K)}else if((X&248)===240){let G=V[J++]&63,K=V[J++]&63,R=V[J++]&63,I=(X&7)<<18|G<<12|K<<6|R;if(I>65535)I-=65536,W.push(I>>>10&1023|55296),I=56320|I&1023;W.push(I)}else W.push(X);if(W.length>=mZ)Y+=String.fromCharCode(...W),W.length=0}if(W.length>0)Y+=String.fromCharCode(...W);return Y}var gZ=new TextDecoder,vZ=200;function iZ(V,$,Z){let J=V.subarray($,$+Z);return gZ.decode(J)}function D$(V,$,Z){if(Z>vZ)return iZ(V,$,Z);else return CV(V,$,Z)}class k0{type;data;constructor(V,$){this.type=V,this.data=$}}class a extends Error{constructor(V){super(V);let $=Object.create(a.prototype);Object.setPrototypeOf(this,$),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:a.name})}}var E0=4294967295;function _$(V,$,Z){let J=Z/4294967296,Q=Z;V.setUint32($,J),V.setUint32($+4,Q)}function a0(V,$,Z){let J=Math.floor(Z/4294967296),Q=Z;V.setUint32($,J),V.setUint32($+4,Q)}function s0(V,$){let Z=V.getInt32($),J=V.getUint32($+4);return Z*4294967296+J}function j$(V,$){let Z=V.getUint32($),J=V.getUint32($+4);return Z*4294967296+J}var bZ=-1,uZ=4294967295,yZ=17179869183;function nZ({sec:V,nsec:$}){if(V>=0&&$>=0&&V<=yZ)if($===0&&V<=uZ){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,V),Z}else{let Z=V/4294967296,J=V&4294967295,Q=new Uint8Array(8),W=new DataView(Q.buffer);return W.setUint32(0,$<<2|Z&3),W.setUint32(4,J),Q}else{let Z=new Uint8Array(12),J=new DataView(Z.buffer);return J.setUint32(0,$),a0(J,4,V),Z}}function pZ(V){let $=V.getTime(),Z=Math.floor($/1000),J=($-Z*1000)*1e6,Q=Math.floor(J/1e9);return{sec:Z+Q,nsec:J-Q*1e9}}function lZ(V){if(V instanceof Date){let $=pZ(V);return nZ($)}else return null}function hZ(V){let $=new DataView(V.buffer,V.byteOffset,V.byteLength);switch(V.byteLength){case 4:{let Z=$.getUint32(0),J=0;return{sec:Z,nsec:0}}case 8:{let Z=$.getUint32(0),J=$.getUint32(4),Q=(Z&3)*4294967296+J,W=Z>>>2;return{sec:Q,nsec:W}}case 12:{let Z=s0($,4),J=$.getUint32(0);return{sec:Z,nsec:J}}default:throw new a(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${V.length}`)}}function rZ(V){let $=hZ(V);return new Date($.sec*1000+$.nsec/1e6)}var L$={type:bZ,encode:lZ,decode:rZ};class S0{static defaultCodec=new S0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(L$)}register({type:V,encode:$,decode:Z}){if(V>=0)this.encoders[V]=$,this.decoders[V]=Z;else{let J=-1-V;this.builtInEncoders[J]=$,this.builtInDecoders[J]=Z}}tryToEncode(V,$){for(let Z=0;Z<this.builtInEncoders.length;Z++){let J=this.builtInEncoders[Z];if(J!=null){let Q=J(V,$);if(Q!=null){let W=-1-Z;return new k0(W,Q)}}}for(let Z=0;Z<this.encoders.length;Z++){let J=this.encoders[Z];if(J!=null){let Q=J(V,$);if(Q!=null)return new k0(Z,Q)}}if(V instanceof k0)return V;return null}decode(V,$,Z){let J=$<0?this.builtInDecoders[-1-$]:this.decoders[$];if(J)return J(V,$,Z);else return new k0($,V)}}function cZ(V){return V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer}function i0(V){if(V instanceof Uint8Array)return V;else if(ArrayBuffer.isView(V))return new Uint8Array(V.buffer,V.byteOffset,V.byteLength);else if(cZ(V))return new Uint8Array(V);else return Uint8Array.from(V)}var dZ=100,oZ=2048;class t0{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??S0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.maxDepth=V?.maxDepth??dZ,this.initialBufferSize=V?.initialBufferSize??oZ,this.sortKeys=V?.sortKeys??!1,this.forceFloat32=V?.forceFloat32??!1,this.ignoreUndefined=V?.ignoreUndefined??!1,this.forceIntegerToFloat=V?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new t0({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(V){if(this.entered)return this.clone().encodeSharedRef(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(V){if(this.entered)return this.clone().encode(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(V,$){if($>this.maxDepth)throw Error(`Too deep objects in depth ${$}`);if(V==null)this.encodeNil();else if(typeof V==="boolean")this.encodeBoolean(V);else if(typeof V==="number")if(!this.forceIntegerToFloat)this.encodeNumber(V);else this.encodeNumberAsFloat(V);else if(typeof V==="string")this.encodeString(V);else if(this.useBigInt64&&typeof V==="bigint")this.encodeBigInt64(V);else this.encodeObject(V,$)}ensureBufferSizeToWrite(V){let $=this.pos+V;if(this.view.byteLength<$)this.resizeBuffer($*2)}resizeBuffer(V){let $=new ArrayBuffer(V),Z=new Uint8Array($),J=new DataView($);Z.set(this.bytes),this.view=J,this.bytes=Z}encodeNil(){this.writeU8(192)}encodeBoolean(V){if(V===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber(V){if(!this.forceIntegerToFloat&&Number.isSafeInteger(V))if(V>=0)if(V<128)this.writeU8(V);else if(V<256)this.writeU8(204),this.writeU8(V);else if(V<65536)this.writeU8(205),this.writeU16(V);else if(V<4294967296)this.writeU8(206),this.writeU32(V);else if(!this.useBigInt64)this.writeU8(207),this.writeU64(V);else this.encodeNumberAsFloat(V);else if(V>=-32)this.writeU8(224|V+32);else if(V>=-128)this.writeU8(208),this.writeI8(V);else if(V>=-32768)this.writeU8(209),this.writeI16(V);else if(V>=-2147483648)this.writeU8(210),this.writeI32(V);else if(!this.useBigInt64)this.writeU8(211),this.writeI64(V);else this.encodeNumberAsFloat(V);else this.encodeNumberAsFloat(V)}encodeNumberAsFloat(V){if(this.forceFloat32)this.writeU8(202),this.writeF32(V);else this.writeU8(203),this.writeF64(V)}encodeBigInt64(V){if(V>=BigInt(0))this.writeU8(207),this.writeBigUint64(V);else this.writeU8(211),this.writeBigInt64(V)}writeStringHeader(V){if(V<32)this.writeU8(160+V);else if(V<256)this.writeU8(217),this.writeU8(V);else if(V<65536)this.writeU8(218),this.writeU16(V);else if(V<4294967296)this.writeU8(219),this.writeU32(V);else throw Error(`Too long string: ${V} bytes in UTF-8`)}encodeString(V){let Z=T$(V);this.ensureBufferSizeToWrite(5+Z),this.writeStringHeader(Z),A$(V,this.bytes,this.pos),this.pos+=Z}encodeObject(V,$){let Z=this.extensionCodec.tryToEncode(V,this.context);if(Z!=null)this.encodeExtension(Z);else if(Array.isArray(V))this.encodeArray(V,$);else if(ArrayBuffer.isView(V))this.encodeBinary(V);else if(typeof V==="object")this.encodeMap(V,$);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply(V)}`)}encodeBinary(V){let $=V.byteLength;if($<256)this.writeU8(196),this.writeU8($);else if($<65536)this.writeU8(197),this.writeU16($);else if($<4294967296)this.writeU8(198),this.writeU32($);else throw Error(`Too large binary: ${$}`);let Z=i0(V);this.writeU8a(Z)}encodeArray(V,$){let Z=V.length;if(Z<16)this.writeU8(144+Z);else if(Z<65536)this.writeU8(220),this.writeU16(Z);else if(Z<4294967296)this.writeU8(221),this.writeU32(Z);else throw Error(`Too large array: ${Z}`);for(let J of V)this.doEncode(J,$+1)}countWithoutUndefined(V,$){let Z=0;for(let J of $)if(V[J]!==void 0)Z++;return Z}encodeMap(V,$){let Z=Object.keys(V);if(this.sortKeys)Z.sort();let J=this.ignoreUndefined?this.countWithoutUndefined(V,Z):Z.length;if(J<16)this.writeU8(128+J);else if(J<65536)this.writeU8(222),this.writeU16(J);else if(J<4294967296)this.writeU8(223),this.writeU32(J);else throw Error(`Too large map object: ${J}`);for(let Q of Z){let W=V[Q];if(!(this.ignoreUndefined&&W===void 0))this.encodeString(Q),this.doEncode(W,$+1)}}encodeExtension(V){if(typeof V.data==="function"){let Z=V.data(this.pos+6),J=Z.length;if(J>=4294967296)throw Error(`Too large extension object: ${J}`);this.writeU8(201),this.writeU32(J),this.writeI8(V.type),this.writeU8a(Z);return}let $=V.data.length;if($===1)this.writeU8(212);else if($===2)this.writeU8(213);else if($===4)this.writeU8(214);else if($===8)this.writeU8(215);else if($===16)this.writeU8(216);else if($<256)this.writeU8(199),this.writeU8($);else if($<65536)this.writeU8(200),this.writeU16($);else if($<4294967296)this.writeU8(201),this.writeU32($);else throw Error(`Too large extension object: ${$}`);this.writeI8(V.type),this.writeU8a(V.data)}writeU8(V){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,V),this.pos++}writeU8a(V){let $=V.length;this.ensureBufferSizeToWrite($),this.bytes.set(V,this.pos),this.pos+=$}writeI8(V){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,V),this.pos++}writeU16(V){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,V),this.pos+=2}writeI16(V){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,V),this.pos+=2}writeU32(V){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,V),this.pos+=4}writeI32(V){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,V),this.pos+=4}writeF32(V){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,V),this.pos+=4}writeF64(V){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,V),this.pos+=8}writeU64(V){this.ensureBufferSizeToWrite(8),_$(this.view,this.pos,V),this.pos+=8}writeI64(V){this.ensureBufferSizeToWrite(8),a0(this.view,this.pos,V),this.pos+=8}writeBigUint64(V){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,V),this.pos+=8}writeBigInt64(V){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,V),this.pos+=8}}function e0(V,$){return new t0($).encodeSharedRef(V)}function VV(V){return`${V<0?"-":""}0x${Math.abs(V).toString(16).padStart(2,"0")}`}var aZ=16,sZ=16;class TV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(V=aZ,$=sZ){this.maxKeyLength=V,this.maxLengthPerKey=$,this.caches=[];for(let Z=0;Z<this.maxKeyLength;Z++)this.caches.push([])}canBeCached(V){return V>0&&V<=this.maxKeyLength}find(V,$,Z){let J=this.caches[Z-1];V:for(let Q of J){let W=Q.bytes;for(let Y=0;Y<Z;Y++)if(W[Y]!==V[$+Y])continue V;return Q.str}return null}store(V,$){let Z=this.caches[V.length-1],J={bytes:V,str:$};if(Z.length>=this.maxLengthPerKey)Z[Math.random()*Z.length|0]=J;else Z.push(J)}decode(V,$,Z){let J=this.find(V,$,Z);if(J!=null)return this.hit++,J;this.miss++;let Q=CV(V,$,Z),W=Uint8Array.prototype.slice.call(V,$,$+Z);return this.store(W,Q),Q}}var AV="array",u0="map_key",E$="map_value",tZ=(V)=>{if(typeof V==="string"||typeof V==="number")return V;throw new a("The type of key must be string or number but "+typeof V)};class S${stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(V){let $=this.getUninitializedStateFromPool();$.type=AV,$.position=0,$.size=V,$.array=Array(V)}pushMapState(V){let $=this.getUninitializedStateFromPool();$.type=u0,$.readCount=0,$.size=V,$.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let V={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(V)}return this.stack[this.stackHeadPosition]}release(V){if(this.stack[this.stackHeadPosition]!==V)throw Error("Invalid stack state. Released state is not on top of the stack.");if(V.type===AV){let Z=V;Z.size=0,Z.array=void 0,Z.position=0,Z.type=void 0}if(V.type===u0||V.type===E$){let Z=V;Z.size=0,Z.map=void 0,Z.readCount=0,Z.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var b0=-1,DV=new DataView(new ArrayBuffer(0)),eZ=new Uint8Array(DV.buffer);try{DV.getInt8(0)}catch(V){if(!(V instanceof RangeError))throw Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var k$=RangeError("Insufficient data"),VJ=new TV;class $V{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=DV;bytes=eZ;headByte=b0;stack=new S$;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??S0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.rawStrings=V?.rawStrings??!1,this.maxStrLength=V?.maxStrLength??E0,this.maxBinLength=V?.maxBinLength??E0,this.maxArrayLength=V?.maxArrayLength??E0,this.maxMapLength=V?.maxMapLength??E0,this.maxExtLength=V?.maxExtLength??E0,this.keyDecoder=V?.keyDecoder!==void 0?V.keyDecoder:VJ,this.mapKeyConverter=V?.mapKeyConverter??tZ}clone(){return new $V({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=b0,this.stack.reset()}setBuffer(V){let $=i0(V);this.bytes=$,this.view=new DataView($.buffer,$.byteOffset,$.byteLength),this.pos=0}appendBuffer(V){if(this.headByte===b0&&!this.hasRemaining(1))this.setBuffer(V);else{let $=this.bytes.subarray(this.pos),Z=i0(V),J=new Uint8Array($.length+Z.length);J.set($),J.set(Z,$.length),this.setBuffer(J)}}hasRemaining(V){return this.view.byteLength-this.pos>=V}createExtraByteError(V){let{view:$,pos:Z}=this;return RangeError(`Extra ${$.byteLength-Z} of ${$.byteLength} byte(s) found at buffer[${V}]`)}decode(V){if(this.entered)return this.clone().decode(V);try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);let $=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return $}finally{this.entered=!1}}*decodeMulti(V){if(this.entered){yield*this.clone().decodeMulti(V);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(V){if(this.entered)return this.clone().decodeAsync(V);try{this.entered=!0;let $=!1,Z;for await(let Y of V){if($)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(Y);try{Z=this.doDecodeSync(),$=!0}catch(X){if(!(X instanceof RangeError))throw X}this.totalPos+=this.pos}if($){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Z}let{headByte:J,pos:Q,totalPos:W}=this;throw RangeError(`Insufficient data in parsing ${VV(J)} at ${W} (${Q} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(V){return this.decodeMultiAsync(V,!0)}decodeStream(V){return this.decodeMultiAsync(V,!1)}async*decodeMultiAsync(V,$){if(this.entered){yield*this.clone().decodeMultiAsync(V,$);return}try{this.entered=!0;let Z=$,J=-1;for await(let Q of V){if($&&J===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(Q),Z)J=this.readArraySize(),Z=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--J===0)break}catch(W){if(!(W instanceof RangeError))throw W}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){V:while(!0){let V=this.readHeadByte(),$;if(V>=224)$=V-256;else if(V<192)if(V<128)$=V;else if(V<144){let J=V-128;if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V<160){let J=V-144;if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else{let J=V-160;$=this.decodeString(J,0)}else if(V===192)$=null;else if(V===194)$=!1;else if(V===195)$=!0;else if(V===202)$=this.readF32();else if(V===203)$=this.readF64();else if(V===204)$=this.readU8();else if(V===205)$=this.readU16();else if(V===206)$=this.readU32();else if(V===207)if(this.useBigInt64)$=this.readU64AsBigInt();else $=this.readU64();else if(V===208)$=this.readI8();else if(V===209)$=this.readI16();else if(V===210)$=this.readI32();else if(V===211)if(this.useBigInt64)$=this.readI64AsBigInt();else $=this.readI64();else if(V===217){let J=this.lookU8();$=this.decodeString(J,1)}else if(V===218){let J=this.lookU16();$=this.decodeString(J,2)}else if(V===219){let J=this.lookU32();$=this.decodeString(J,4)}else if(V===220){let J=this.readU16();if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else if(V===221){let J=this.readU32();if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else if(V===222){let J=this.readU16();if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V===223){let J=this.readU32();if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V===196){let J=this.lookU8();$=this.decodeBinary(J,1)}else if(V===197){let J=this.lookU16();$=this.decodeBinary(J,2)}else if(V===198){let J=this.lookU32();$=this.decodeBinary(J,4)}else if(V===212)$=this.decodeExtension(1,0);else if(V===213)$=this.decodeExtension(2,0);else if(V===214)$=this.decodeExtension(4,0);else if(V===215)$=this.decodeExtension(8,0);else if(V===216)$=this.decodeExtension(16,0);else if(V===199){let J=this.lookU8();$=this.decodeExtension(J,1)}else if(V===200){let J=this.lookU16();$=this.decodeExtension(J,2)}else if(V===201){let J=this.lookU32();$=this.decodeExtension(J,4)}else throw new a(`Unrecognized type byte: ${VV(V)}`);this.complete();let Z=this.stack;while(Z.length>0){let J=Z.top();if(J.type===AV)if(J.array[J.position]=$,J.position++,J.position===J.size)$=J.array,Z.release(J);else continue V;else if(J.type===u0){if($==="__proto__")throw new a("The key __proto__ is not allowed");J.key=this.mapKeyConverter($),J.type=E$;continue V}else if(J.map[J.key]=$,J.readCount++,J.readCount===J.size)$=J.map,Z.release(J);else{J.key=null,J.type=u0;continue V}}return $}}readHeadByte(){if(this.headByte===b0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=b0}readArraySize(){let V=this.readHeadByte();switch(V){case 220:return this.readU16();case 221:return this.readU32();default:if(V<160)return V-144;else throw new a(`Unrecognized array type byte: ${VV(V)}`)}}pushMapState(V){if(V>this.maxMapLength)throw new a(`Max length exceeded: map length (${V}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(V)}pushArrayState(V){if(V>this.maxArrayLength)throw new a(`Max length exceeded: array length (${V}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(V)}decodeString(V,$){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String(V,$);return this.decodeBinary(V,$)}decodeUtf8String(V,$){if(V>this.maxStrLength)throw new a(`Max length exceeded: UTF-8 byte length (${V}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+$+V)throw k$;let Z=this.pos+$,J;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached(V))J=this.keyDecoder.decode(this.bytes,Z,V);else J=D$(this.bytes,Z,V);return this.pos+=$+V,J}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===u0;return!1}decodeBinary(V,$){if(V>this.maxBinLength)throw new a(`Max length exceeded: bin length (${V}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(V+$))throw k$;let Z=this.pos+$,J=this.bytes.subarray(Z,Z+V);return this.pos+=$+V,J}decodeExtension(V,$){if(V>this.maxExtLength)throw new a(`Max length exceeded: ext length (${V}) > maxExtLength (${this.maxExtLength})`);let Z=this.view.getInt8(this.pos+$),J=this.decodeBinary(V,$+1);return this.extensionCodec.decode(J,Z,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let V=this.view.getUint8(this.pos);return this.pos++,V}readI8(){let V=this.view.getInt8(this.pos);return this.pos++,V}readU16(){let V=this.view.getUint16(this.pos);return this.pos+=2,V}readI16(){let V=this.view.getInt16(this.pos);return this.pos+=2,V}readU32(){let V=this.view.getUint32(this.pos);return this.pos+=4,V}readI32(){let V=this.view.getInt32(this.pos);return this.pos+=4,V}readU64(){let V=j$(this.view,this.pos);return this.pos+=8,V}readI64(){let V=s0(this.view,this.pos);return this.pos+=8,V}readU64AsBigInt(){let V=this.view.getBigUint64(this.pos);return this.pos+=8,V}readI64AsBigInt(){let V=this.view.getBigInt64(this.pos);return this.pos+=8,V}readF32(){let V=this.view.getFloat32(this.pos);return this.pos+=4,V}readF64(){let V=this.view.getFloat64(this.pos);return this.pos+=8,V}}function _V(V,$){return new $V($).decode(V)}class y0{listeners=new Map;addEventListener(V,$){let Z=this.listeners.get(V);if(!Z)Z=new Set,this.listeners.set(V,Z);return Z.add($),()=>{this.removeEventListener(V,$)}}removeEventListener(V,$){let Z=this.listeners.get(V);if(Z){if(Z.delete($),Z.size===0)this.listeners.delete(V)}}emit(V,$){let Z=this.listeners.get(V);if(Z){let J=Array.from(Z);for(let Q of J)Q($)}}emitAll(V){let $=Array.from(this.listeners.keys());for(let Z of $)this.emit(Z,V)}}class q0{getter;static eventName="update";emitter;constructor(V){this.getter=V;this.emitter=new y0}get=()=>this.getter();async emit(){let V=await this.getter();queueMicrotask(()=>this.emitter.emit(q0.eventName,V))}listen(V){return this.emitter.addEventListener(q0.eventName,V),()=>{this.emitter.removeEventListener(q0.eventName,V)}}}function O(V){return[V,0]}function N(V){return[void 0,V]}function $J(V){if(V<0)console.info("N",V),console.trace();if(typeof V!=="bigint")V=BigInt(V);if(V<0n)return N(10);let $=[];while(V>0n){let Z=Number(V&0x7fn);if(V>>=7n,V>0n)$.push(Z|128);else $.push(Z)}if($.length===0)return O(new Uint8Array([0]));if($.length>8)return N(26);return O(new Uint8Array($))}function ZJ(V,$=0){let Z=0n,J=0,Q=$;while(!0){if(Q>=V.length)return N(14);let W=V[Q++];if(W===void 0)return N(14);if(Z|=BigInt(W&127)<<BigInt(J),(W&128)===0){if(Q-$>8)return N(26);return O({value:Z>0x1fffffffffffffn?Z:Number(Z),bytesRead:Q-$})}if(J+=7,J>=56)return N(26)}}class m{data;pos=0;constructor(V){this.data=V}static async fromResponse(V){let $=await V.arrayBuffer(),Z=new Uint8Array($);return new m(Z)}readBigInt(){if(this.pos+8>this.data.length)return N(7);let V=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,O(V)}readDate(){let[V,$]=this.readVarInt();if($!==0)return N($);return O(new Date(V))}readVarInt(){let[V,$]=ZJ(this.data,this.pos);if($!==0)return N($);this.pos+=V.bytesRead;let Z=V.value;return O(typeof Z==="bigint"?Number(Z):Z)}readVarString(){let[V,$]=this.readVarInt();if($!==0)return N($);let[Z,J]=this.readBytes(V);if(J!==0)return N(J);let Q=new TextDecoder().decode(Z);return O(Q)}readBytes(V){if(V<0)return N(10);if(this.pos+V>this.data.length)return N(23);let $=this.data.slice(this.pos,this.pos+V);return this.pos+=V,O($)}readVarBytes(){let[V,$]=this.readVarInt();if($!==0)return N($);return this.readBytes(V)}readStruct(V){return V.decode(this)}readStructs(V){let $=[];while(!this.done()){let[Z,J]=this.readStruct(V);if(J!==0)return N(J);$.push(Z)}return O($)}readBytesSeq(V){let $=[];while(!this.done()){let[Z,J]=this.readBytes(V);if(J!==0)return N(J);$.push(Z)}return O($)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class B{parts=[];writeBigInt(V){let $=new Uint8Array(8);new DataView($.buffer).setBigUint64(0,V,!1),this.parts.push($)}writeDate(V){let $=V.getTime();return this.writeVarInt($)}writeVarInt(V){let[$,Z]=$J(V);if(Z!==0)return Z;return this.parts.push($),0}writeVarString(V){let $=new TextEncoder().encode(V),Z=this.writeVarInt($.length);if(Z!==0)return Z;return this.writeBytes($),0}prependBytes(V){this.parts.unshift(V)}writeBytes(V){this.parts.push(V)}writeVarBytes(V){let $=this.writeVarInt(V.length);if($!==0)return $;return this.writeBytes(V),0}writeStruct(V,$){return V.encode(this,$)}writeStructs(V,$){for(let Z of $){let J=this.writeStruct(V,Z);if(J!==0)return J}return 0}writeBytesSeq(V){for(let $ of V)this.writeBytes($)}result(){let V=this.parts.reduce((J,Q)=>J+Q.length,0),$=new Uint8Array(V),Z=0;for(let J of this.parts)$.set(J,Z),Z+=J.length;return $}*scan(){for(let V of this.parts)yield V}}async function jV(V,$,Z){let J=new B,Q=J.writeDate($);if(Q!==0)return N(Q);let W=J.result(),Y=await Z.signEd25519(W,V.privateKey);return O({pubKey:V.publicKey,sig:Y,timestamp:$})}async function U0(V,$,Z){let J=Z.now().getTime(),Q=V.timestamp.getTime();if(Math.abs(J-Q)>O$)return 4;let Y=new B;Y.writeDate(V.timestamp);let X=Y.result();if(!await $.checkSigEd25519(V.sig,X,V.pubKey))return 3;return 0}var Y0={encode(V,$){let Z=V.writeVarBytes($.id);if(Z!==0)return Z;let J=V.writeDate($.ts);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return N(Z);let[J,Q]=V.readDate();if(Q!==0)return N(Q);return O({id:$,ts:J})}};function ZV(V){let $=new B,Z=$.writeStruct(Y0,V);if(Z!==0)return N(Z);let J=$.result();return O(J)}var J0={encode(V,$){let Z=V.writeVarBytes($.eid);if(Z!==0)return Z;let J=V.writeVarInt($.off);if(J!==0)return J;let Q=V.writeVarInt($.ctr);if(Q!==0)return Q;let W=V.writeVarInt($.len);if(W!==0)return W;if($.hsh)V.writeBytes($.hsh);return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return N(Z);let J=new m($),[,Q]=Y0.decode(J);if(Q!==0)return N(Q);let[W,Y]=V.readVarInt();if(Y!==0)return N(Y);let[X,G]=V.readVarInt();if(G!==0)return N(G);let[K,R]=V.readVarInt();if(R!==0)return N(R);let I;if(K>0){let[z,M]=V.readBytes(o0);if(M!==0)return N(M);I=z}return O({eid:$,off:W,ctr:X,len:K,hsh:I})}};function Q0(V){return Array.from(V).map((Z)=>Z.toString(16).padStart(2,"0")).join("")}function JV(V){if(V.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(V.length/2);for(let Z=0;Z<V.length;Z+=2)$[Z/2]=Number.parseInt(V.substr(Z,2),16);return $}function O0(V,$){if(V===$)return!0;if(V.byteLength!==$.byteLength)return!1;return V.every((Z,J)=>Z===$[J])}var d;if(typeof Uint8Array.prototype.toBase64==="function")d=(V)=>V.toBase64();else d=(V)=>btoa(String.fromCharCode(...V));var R0;if(typeof Uint8Array.fromBase64==="function")R0=(V)=>Uint8Array.fromBase64(V);else R0=(V)=>Uint8Array.from(atob(V),($)=>$.charCodeAt(0));function n0(V,$){let Z=new Uint8Array(V.length+$.length);return Z.set(V,0),Z.set($,V.length),Z}function x$(V,$,Z){return Z.checkSigEd25519(V.sig,V.headCph,$)}async function LV(V,$,Z){let J=n0($.privateKey,V);return(await Z.blake3(J)).slice(0,P0)}async function B$(V,$,Z,J){let Q;if(V.bod&&V.len>0)Q=await Z.blake3(V.bod);let W=new B,Y=J0.encode(W,{...V,hsh:Q});if(Y!==0)return N(Y);let X=W.result(),G=await LV(X,$,Z),K=await J.deriveFromKDM(G),R=await Z.encryptXSalsa20Poly1305Combined(X,K),I=V.bod?await Z.encryptXSalsa20Poly1305Combined(V.bod,K):new Uint8Array(0),z=await Z.signEd25519(R,$.privateKey);return O({sig:z,kdm:G,headCph:R,bodyCph:I})}async function kV(V,$,Z,J){let Q=new m(V),[W,Y]=J0.decode(Q);if(Y!==0)return N(14);let X;try{X=$&&$.length>0?await J.decryptXSalsa20Poly1305Combined($,Z):void 0}catch{return N(20)}let G=W.hsh&&X===void 0,K=W.hsh===void 0&&X!==void 0;if(G||K)return N(19);if(W.hsh&&X){let I=await J.blake3(X);if(!O0(I,W.hsh))return N(19)}let R=await J.blake3(V);return O({msgHead:W,bod:X,headHash:R})}class EV{now(){return new Date}}function f$(V,$,Z,J){let Q=$.getTime()-V.getTime(),W=Z.getTime()-J.getTime();return(Q+W)/2}var p0={encode(V,$){if(V.writeVarInt($.quota),$.quota>0){if($.usage===void 0)return 9;V.writeVarInt($.usage)}return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return N(Z);let J;if($>0){let[Q,W]=V.readVarInt();if(W!==0)return N(W);J=Q}return O({quota:$,usage:J})}};var SV={encode(V,$){V.writeBytes(new Uint8Array([$.status]));let Z=V.writeDate($.timeRcvd);if(Z!==0)return Z;let J=V.writeDate($.timeSent);if(J!==0)return J;let Q=V.writeVarInt($.subscription.term);if(Q!==0)return Q;let W=V.writeVarInt($.subscription.elapsed);if(W!==0)return W;let Y=V.writeStruct(p0,$.subscription.stat);if(Y!==0)return Y;let X=V.writeStruct(p0,$.subscription.dyn);if(X!==0)return X;return 0},decode(V){let[$,Z]=V.readBytes(1);if(Z!==0)return N(Z);let J=$[0],[Q,W]=V.readDate();if(W!==0)return N(W);let[Y,X]=V.readDate();if(X!==0)return N(X);let[G,K]=V.readVarInt();if(K!==0)return N(K);let[R,I]=V.readVarInt();if(I!==0)return N(I);let[z,M]=V.readStruct(p0);if(M!==0)return N(M);let[F,w]=V.readStruct(p0);if(w!==0)return N(w);return O({status:J,timeRcvd:Q,timeSent:Y,subscription:{term:G,elapsed:R,stat:z,dyn:F}})}};async function xV(V,$,Z){let{crypto:J,enclave:Q}=V,W=await Q.derive($,Z);return await J.deriveEd25519KeyPair(W)}var BV={encode(V,$){let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarInt($.seq);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return N(Z);let[J,Q]=V.readVarInt();if(Q!==0)return N(Q);return O({headCph:$,seq:J})}};var V0={encode(V,$){V.writeBytes($.pubKey),V.writeBytes($.sig);let Z=V.writeDate($.timestamp);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readBytes(q$);if(Z!==0)return N(Z);let[J,Q]=V.readBytes(F0);if(Q!==0)return N(Q);let[W,Y]=V.readDate();if(Y!==0)return N(Y);return O({pubKey:$,sig:J,timestamp:W})}};var m$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(V0,Z);if(W!==0)return W;for(let Y of J)Q.writeVarInt(Y);return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(V0);if(X!==0)return X;let G=await U0(Y,Q,J);if(G!==0)return G;let{pubKey:K}=Y,[R,I]=await W.hasUser(K);if(I!==0)return I;if(!R)return 5;let[z,M]=$.readVarInt();if(M!==0)return M;if(!$.done())return 8;let[F,w]=await W.listHeads(K,z);if(w!==0)return w;return Z.writeStructs(BV,F)},decodeResp(V){return V.readStructs(BV)}};var fV={encode(V,$){V.writeVarInt($.seq);let Z=V.writeVarBytes($.bodyCph);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return N(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return N(Q);return O({seq:$,bodyCph:J})}};var g$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(V0,Z);if(W!==0)return W;for(let Y of J){let X=Q.writeVarInt(Y);if(X!==0)return X}return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(V0);if(X!==0)return X;let G=await U0(Y,Q,J);if(G!==0)return G;let{pubKey:K}=Y,[R,I]=await W.hasUser(K);if(I!==0)return I;if(!R)return 5;let z=[];while(!$.done()){let[w,q]=$.readVarInt();if(q!==0)return q;z.push(w)}console.info(`PULL: ${z.length} bags`);let[M,F]=await W.getBodies(K,z);if(F!==0)return F;if(!M)return 17;for(let{seq:w,bodyCph:q}of M){let U={seq:w,bodyCph:q},H=Z.writeStruct(fV,U);if(H!==0)return H}return 0},decodeResp(V){return V.readStructs(fV)}};var mV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarBytes($.bodyCph);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readBytes(F0);if(Z!==0)return N(Z);let[J,Q]=V.readBytes(P0);if(Q!==0)return N(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return N(Y);let[X,G]=V.readVarBytes();if(G!==0)return N(G);return O({sig:$,kdm:J,headCph:W,bodyCph:X})}};var QV={encode(V,$){let Z=V.writeVarInt($.seq);if(Z!==0)return Z;let J=V.writeVarBytes($.headCph);if(J!==0)return J;let Q=$.bodyCph?$.bodyCph.length:0,W=V.writeVarInt(Q);if(W!==0)return W;if(Q>0){if(!$.bodyCph)return 10;V.writeBytes($.bodyCph)}return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return N(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return N(Q);let[W,Y]=V.readVarInt();if(Y!==0)return N(Y);let X;if(W>0){let[G,K]=V.readBytes(W);if(K!==0)return N(K);X=G}return O({seq:$,headCph:J,bodyCph:X})}};var WV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readBytes(F0);if(Z!==0)return N(Z);let[J,Q]=V.readBytes(P0);if(Q!==0)return N(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return N(Y);return O({sig:$,kdm:J,headCph:W})}};var YV={encode(V,$){if(V.writeVarInt($.idx),V.writeBytes(new Uint8Array([$.status])),$.status===0)V.writeVarInt($.seq);return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return N(Z);let[J,Q]=V.readBytes(1);if(Q!==0)return N(Q);let W=J[0];if(W!==0)return O({idx:$,status:W});let[Y,X]=V.readVarInt();if(X!==0)return N(X);return O({idx:$,status:W,seq:Y})}};var v$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(V0,Z);if(W!==0)return W;let Y=Q.writeStructs(mV,J);if(Y!==0)return Y;return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W,notifier:Y}=V,[X,G]=$.readStruct(V0);if(G!==0)return G;let K=await U0(X,Q,J);if(K!==0)return K;let{pubKey:R}=X,[I,z]=await W.hasUser(R);if(z!==0)return z;if(!I)return 5;let[M,F]=$.readStructs(mV);if(F!==0)return F;console.info(`PUSH: ${M.length} bags`);let w=[],q=[];for(let P=0;P<M.length;P++){let D=M[P];if(!await x$(D,R,Q)){let k={idx:P,status:3},S=Z.writeStruct(YV,k);if(S!==0)return S;continue}w.push(P),q.push(D)}let[U,H]=await W.setBags(R,q);if(H!==0)return H;if(!U||U.length!==q.length)return 17;let A=[];for(let P=0;P<q.length;P++){let D=q[P],L=w[P],k=U[P],S=new B,E=S.writeStruct(WV,D);if(E!==0)return E;let x=S.result(),C={seq:k,headCph:x};if(M.length===1&&D.bodyCph.length<=H$)C.bodyCph=D.bodyCph;A.push(C);let f={idx:L,status:0,seq:k},v=Z.writeStruct(YV,f);if(v!==0)return v}if(A.length>0){let P=new B,D=P.writeStructs(QV,A);if(D!==0)return D;let L=P.result();await Promise.resolve(Y.push(R,L))}return 0},decodeResp(V){return V.readStructs(YV)}};var i$={async encodeReq(V,$,Z,J,Q){return Q.writeStruct(V0,Z)},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(V0);if(X!==0)return X;let G=await U0(Y,Q,J);if(G!==0)return G;let{pubKey:K}=Y;if(!$.done())return 8;let[R,I]=await W.addUser(K);if(I!==0)return I;return 0},decodeResp(V){return O(void 0)}};class gV{url;websocket;constructor(V){this.url=V}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(V,$,Z=()=>{},J=()=>{}){let{url:Q}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let W=new B;W.writeStruct(V0,V);let Y=W.result(),X=Q0(Y);return Q.searchParams.set("t",X),this.websocket=new WebSocket(Q),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),J()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Z()},this.websocket.onmessage=(G)=>{let K=new Uint8Array(G.data);$(K)},this.websocket.onerror=(G)=>{console.log(`ERROR: ${JSON.stringify(G)}`),this.websocket=void 0,Z()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var h={user:{path:"/user",endpoint:i$,name:0},push:{path:"/push",endpoint:v$,name:2},peek:{path:"/peek",endpoint:m$,name:1},pull:{path:"/pull",endpoint:g$,name:3}},JJ={0:h.user,2:h.push,1:h.peek,3:h.pull},bY={[h.user.path]:h.user,[h.push.path]:h.push,[h.peek.path]:h.peek,[h.pull.path]:h.pull};class b${url;listener;constructor(V){this.url=V;this.listener=new gV(V)}async call(V,$){let{path:Z}=JJ[V],J=new URL(Z,this.url);try{return await QJ(J,$)}catch{return N(25)}}}var u$=(V)=>{return new b$(V.handle)};async function QJ(V,$){let Z=await fetch(V,{method:"POST",body:$.result().slice()});if(!Z.ok)return N(24);let J=await m.fromResponse(Z);return O(J)}class XV{enclave;crypto;host;clock;transport;updateHostMeta;constructor(V,$,Z,J,Q,W){this.enclave=V;this.crypto=$;this.host=Z;this.clock=J;this.transport=Q;this.updateHostMeta=W}async call(V,$){let{clock:Z,crypto:J,transport:Q}=this,{endpoint:W,name:Y}=V,X=await this.keys(),G=Z.now(),[K,R]=await jV(X,G,J);if(R!==0)return N(R);let I=new B,z=await W.encodeReq(this,X,K,$,I);if(z!==0)return N(z);let M=Z.now(),[F,w]=await Q.call(Y,I),q=Z.now();if(w!==0)return N(w);let[U,H]=F.readStruct(SV);if(H!==0)return N(H);if(U.status!==0)return N(U.status);let P={clockOffset:f$(M,U.timeRcvd,U.timeSent,q),subscription:U.subscription},D=await this.updateHostMeta(P);if(D!==0)return N(D);return W.decodeResp(F)}keys=()=>{let{host:V}=this;return xV(this,V.label,V.idx)};seal=async(V)=>{let{crypto:$,enclave:Z}=this,J=await this.keys();return B$(V,J,$,Z)};register=()=>this.call(h.user,[]);peek=(V)=>this.call(h.peek,[V]);push=(V)=>this.call(h.push,V);pull=(V)=>this.call(h.pull,V);listen=async(V,$,Z)=>{let{clock:J,crypto:Q,host:W,transport:Y}=this,{listener:X}=Y,G=await xV(this,W.label,W.idx),K=J.now(),[R,I]=await jV(G,K,Q);if(I!==0)return I;return await X.connect(R,V,$,Z)};isConnected(){let V=this.transport?.listener;if(V&&typeof V.connected==="function")return V.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var vV={encode(V,$){let Z=V.writeVarString($.lbl);if(Z!==0)return Z;let J=V.writeVarInt($.idx);if(J!==0)return J;let Q=V.writeVarInt($.num);if(Q!==0)return Q;return V.writeBytes($.hsh),V.writeBytes($.sig),0},decode(V){let[$,Z]=V.readVarString();if(Z!==0)return N(Z);let[J,Q]=V.readVarInt();if(Q!==0)return N(Q);let[W,Y]=V.readVarInt();if(Y!==0)return N(Y);let[X,G]=V.readBytes(o0);if(G!==0)return N(G);let[K,R]=V.readBytes(F0);if(R!==0)return N(R);return O({lbl:$,idx:J,num:W,hsh:X,sig:K})}};var iV={encode(V,$){let Z=V.writeStruct(vV,$.head);if(Z!==0)return Z;let J=V.writeVarBytes($.indexEnc);if(J!==0)return J;let Q=V.writeVarBytes($.bodyEnc);if(Q!==0)return Q;return 0},decode(V){let[$,Z]=V.readStruct(vV);if(Z!==0)return N(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return N(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return N(Y);return O({head:$,indexEnc:J,bodyEnc:W})}};var bV={encode(V,$){V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarInt($.lenBody);if(J!==0)return J;if($.lenBody>0&&$.offBody!==void 0){let Q=V.writeVarInt($.offBody);if(Q!==0)return Q}return 0},decode(V){let[$,Z]=V.readBytes(P0);if(Z!==0)return N(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return N(Q);let[W,Y]=V.readVarInt();if(Y!==0)return N(Y);let X;if(W>0){let[G,K]=V.readVarInt();if(K!==0)return N(K);X=G}return O({kdm:$,headCph:J,lenBody:W,offBody:X})}};async function y$(V,$,Z,J,Q){let W=await Q.derive(V,$),Y=await J.deriveEd25519KeyPair(W),X=new B,G=new B,K=0,R=0;for(let H of Z){let A=new B,P=A.writeStruct(J0,H.head);if(P!==0)return N(P);let D=A.result(),L=await LV(D,Y,J),k=await Q.deriveFromKDM(L),S=await J.encryptXSalsa20Poly1305Combined(D,k),E=H.body?await J.encryptXSalsa20Poly1305Combined(H.body,k):new Uint8Array(0),x=H.head.len>0&&H.head.hsh!==void 0?E.length:0,C={kdm:L,headCph:S,lenBody:x,offBody:x>0?R:void 0},f=X.writeStruct(bV,C);if(f!==0)return N(f);if(H.body)G.writeBytes(E),R+=E.length;K++}let I=G.result(),z=X.result(),M=await J.blake3(z),F=await J.signEd25519(M,Y.privateKey),w={lbl:V,idx:$,num:K,hsh:M,sig:F},q=new B;q.writeStruct(iV,{head:w,indexEnc:z,bodyEnc:I});let U=q.result();return O(U)}async function n$(V,$,Z){let[J,Q]=iV.decode(new m(V));if(Q!==0)return N(Q);let{head:W,indexEnc:Y,bodyEnc:X}=J,G=await Z.derive(W.lbl,W.idx),K=await $.deriveEd25519KeyPair(G);if(!await $.checkSigEd25519(W.sig,W.hsh,K.publicKey))return N(3);let I=await $.blake3(Y);if(!O0(I,W.hsh))return N(19);let z=new m(Y),M=[];for(let w=0;w<W.num;w++){let[q,U]=z.readStruct(bV);if(U!==0)return N(U);M.push(q)}if(M.length!==W.num)return N(14);let F=[];for(let w of M){let q=await Z.deriveFromKDM(w.kdm),U=await $.decryptXSalsa20Poly1305Combined(w.headCph,q),[H,A]=J0.decode(new m(U));if(A!==0)return N(A);let P;if(w.lenBody>0&&w.offBody!==void 0){if(H.hsh===void 0)return N(14);let D=X.slice(w.offBody,w.offBody+w.lenBody);P=await $.decryptXSalsa20Poly1305Combined(D,q);let L=await $.blake3(P);if(!O0(L,H.hsh))return N(19)}F.push({head:H,body:P})}return O(F)}async function p$({now:V,bod:$,crypto:Z}){let J=await Z.genRandomBytes(8),Q=new B,W=Q.writeStruct(Y0,{id:J,ts:V});if(W!==0)return N(W);let Y=Q.result();return GV({now:V,eid:Y,ctr:0,bod:$,crypto:Z})}async function GV({now:V,eid:$,ctr:Z,bod:J,crypto:Q}){let W=new m($),[Y,X]=Y0.decode(W);if(X!==0)return N(X);let G=V.getTime()-Y.ts.getTime(),K,R=J?.length??0;if(J&&R>0)K=await Q.blake3(J);return O({eid:$,off:G,ctr:Z,len:R,hsh:K})}class KV{inflight=null;again=!1;run(V){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain(V),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain(V){try{this.again=!1;let $=await V();while(this.again)this.again=!1,$=await V();return $}finally{this.inflight=null}}}var l$=100;class uV{timer=null;delayMs;work;tail=new KV;constructor(V,$){this.delayMs=V<0?0:V,this.work=$}schedule(){if(this.delayMs<=0){this.fire();return}if(this.timer!==null)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=null,this.fire()},this.delayMs)}async flush(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null,this.fire();await this.tail.flush()}cancel(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null}fire(){return this.tail.run(this.work)}}var yV={phase:"idle"},RV=50;function h$(V,$,Z){if(V<=0||$<=0)return!1;if(V===1||V===$)return!0;return V%Z===0}function r$(V,$){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(V,$);return}let Z=URL.createObjectURL(V),J=document.createElement("a");J.href=Z,J.download=$,document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL(Z)}function c$(V,$,Z){let J=[],Q=[],W=0;for(let Y of V){let X=$(Y);if(Q.length>0&&W+X>Z)J.push(Q),Q=[],W=0;if(Q.push(Y),W+=X,W>=Z)J.push(Q),Q=[],W=0}if(Q.length>0)J.push(Q);return J}async function d$(V,$,Z){let J=V.length;if(J<1)return[];let Q=Array(J),W=0,Y=Math.min(Math.max(1,$),J),X=async()=>{while(!0){let K=W;if(W+=1,K>=J)return;Q[K]=await Z(V[K],K)}},G=[];for(let K=0;K<Y;K++)G.push(X());return await Promise.all(G),Q}async function nV(V,$,Z,J){let Q=new m(V.headCph),[W,Y]=Q.readStruct(WV);if(Y!==0)return N(Y);let{sig:X,kdm:G,headCph:K}=W;if(!await J.checkSigEd25519(X,K,$.publicKey))return N(3);let I=await Z.deriveFromKDM(G),z;try{z=await J.decryptXSalsa20Poly1305Combined(K,I)}catch{return N(20)}return O({kdm:G,headEnc:z})}var pV=1048576,lV=1048576,WJ=64;function YJ(V){return V.sig.length+V.kdm.length+V.headCph.length+V.bodyCph.length}async function XJ(V,$,Z,J,Q){if(J.length<1)return 0;let[W,Y]=await V.push(J);if(Y!==0)return Y;if(!W)return 27;for(let G of W){if(G.status!==0){console.error("push err",G);continue}let K=Q[G.idx];if(!K){console.error("no hash",G);continue}await $.uploads.deq(Z,[K])}let X=await $.hosts.get(Z);if(X){let G=X.lastSeq,K=G,R=[];for(let I of W)if(I.status===0)R.push(I.seq);R.sort((I,z)=>I-z);for(let I of R)if(I===G+1)G=I;if(G>K)await $.hosts.touch(Z,G)}return 0}async function o$(V,$){if($.length<1)return O([]);let Z=new Map,J=[];for(let X of $)Z.set(X.seq,X),J.push(X.seq);let[Q,W]=await V.pull(J);if(W!==0)return N(W);if(!Q)return N(27);let Y=[];for(let{seq:X,bodyCph:G}of Q){let K=Z.get(X);if(!K)continue;Y.push({dl:K,bodyCph:G})}return O(Y)}async function GJ(V,$,Z,J){if(J.length<1)return O({parts:[],hashes:[]});let Q=[],W=[],Y=[],X=new Map;for(let{dl:K,bodyCph:R}of J){let{head:I,kdm:z,seq:M,host:F}=K,w=new B;w.writeStruct(J0,I);let q=w.result(),U=await Z.blake3(q),H=await $.deriveFromKDM(z),[A,P]=await kV(q,R,H,Z);if(P!==0){let k=X.get(F)??[];k.push(M),X.set(F,k);continue}let D={head:I,body:A.bod};Y.push({key:U,data:e$(D)}),Q.push(D),W.push(U);let L=X.get(F)??[];L.push(M),X.set(F,L)}let G=await V.messages.add(Y);for(let[K,R]of X)await V.downloads.deq(K,R);for(let K=0;K<G.length;K++){let R=G[K];if(R!==0&&R!==15)console.error("ERR storing",j[R],"for message",K)}return O({parts:Q,hashes:W})}async function a$({conn:V,store:$,enclave:Z,host:J,crypto:Q,onProgress:W,peekProgressEvery:Y,peekConcurrency:X}){let G=await V.keys(),K=[],[R,I]=await V.peek(J.lastSeq);if(I!==0)return I;let z=R.length,M=Y??RV,F=X??WJ;if(W&&z>0)W({phase:"peek",host:J.label,done:0,total:z});let w=0,q=await d$(R,F,async(U)=>{let[H,A]=await nV(U,G,Z,Q),P;if(A!==0||!H)P={ok:!1,seq:U.seq,stat:A};else{let D=await Q.blake3(H.headEnc);P={ok:!0,seq:U.seq,kdm:H.kdm,headEnc:H.headEnc,headEncHash:D}}if(w+=1,W&&h$(w,z,M))W({phase:"peek",host:J.label,done:w,total:z});return P});for(let U of q){if(!U.ok){console.error("peek: decrypting item head",U.stat);continue}if(await $.messages.has(U.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await $.uploads.deq(J.label,[U.headEncHash]);continue}let A=new m(U.headEnc),[P,D]=A.readStruct(J0);if(D!==0){console.error("peek: reading item head",D);continue}K.push({kdm:U.kdm,head:P,seq:U.seq,host:J.label})}if(await $.downloads.enq(K),R.length>0){let U=Math.max(...R.map((H)=>H.seq));await $.hosts.touch(J.label,U)}if(W)W({phase:"peek",host:J.label,done:z,total:z});return 0}async function s$({conn:V,store:$,host:Z,maxPushBytes:J,onProgress:Q}){let W=J??pV,Y=await $.uploads.list(Z.label),X=Y.length,G=0;if(Q&&X>0)Q({phase:"push",host:Z.label,done:0,total:X});let K=[],R=[],I=0,z=async()=>{if(K.length<1)return 0;let M=K.length,F=await XJ(V,$,Z.label,K,R);if(K=[],R=[],I=0,F===0){if(G+=M,Q)Q({phase:"push",host:Z.label,done:G,total:X})}return F};for(let M of Y){let F=await $.messages.get(M);if(!F){G+=1;continue}let w={...F.head,bod:F.body},[q,U]=await V.seal(w);if(U!==0)return U;if(!q)return 12;let H=YJ(q);if(K.length>0&&I+H>W){let A=await z();if(A!==0)return A}if(K.push(q),R.push(M),I+=H,I>=W){let A=await z();if(A!==0)return A}}return z()}async function t$({conn:V,store:$,enclave:Z,host:J,crypto:Q,maxPullBytes:W,onProgress:Y},X){let G=W??lV,K=await $.downloads.list(),R=Array.from(K).filter((w)=>w.host===J.label);if(R.length<1)return 15;let I=c$(R,(w)=>w.head.len,G),z=R.length,M=0;if(Y)Y({phase:"pull",host:J.label,done:0,total:z});let F=o$(V,I[0]);for(let w=0;w<I.length;w++){let[q,U]=await F;if(U!==0||!q)return U;if(M+=I[w].length,Y)Y({phase:"pull",host:J.label,done:M,total:z});let H=I[w+1];if(H)F=o$(V,H);if(Y)Y({phase:"open",host:J.label,done:M,total:z});let[,A]=await GJ($,Z,Q,q);if(A!==0)return A;if(X){if(Y)Y({phase:"exec",host:J.label,done:M,total:z});await X()}}return 0}function e$({head:V,body:$}){return{eid:V.eid,...V.off!==0?{off:V.off}:{},...V.ctr!==0?{ctr:V.ctr}:{},body:$,apld:!1}}async function VZ(V,{conn:$,store:Z,enclave:J,host:Q,crypto:W,onProgress:Y},X){let G=Q.label,K=await $.keys(),R=new m(V),[I,z]=R.readStructs(QV);if(z!==0){console.error("Failed decoding notif",j[z]);return}let M=!1,w=(await Z.hosts.get(G))?.lastSeq,q=[],U=!1;for(let P of I){let[D,L]=await nV({seq:P.seq,headCph:P.headCph},K,J,W);if(L!==0){console.error("Failed decrypting notif",j[L]);continue}let k=await W.blake3(D.headEnc);if(await Z.messages.has(k))continue;let S=new m(D.headEnc),[E,x]=S.readStruct(J0);if(x!==0){console.error("Failed to parse head",j[x]);continue}if(!P.bodyCph&&E.len>0)U=!0,await Z.downloads.enq([{seq:P.seq,host:G,kdm:D.kdm,head:E}]);else q.push({...D,head:E,bodyCph:P.bodyCph,headEncHash:k});if(w===void 0||P.seq!==w+1)console.log("out of seq",P.seq,w),M=!0;else w=P.seq}if(w!==void 0)await Z.hosts.touch(Q.label,w);let H=[];for(let P of q){let D=await J.deriveFromKDM(P.kdm),[L,k]=await kV(P.headEnc,P.bodyCph,D,W);if(k!==0){console.error("Failed to open body",j[k]);continue}H.push({key:P.headEncHash,data:e$({head:P.head,body:L.bod})})}let A=await Z.messages.add(H);for(let P=0;P<A.length;P++){let D=A[P];if(D!==0&&D!==15)console.error("ERR storing",j[D],"for message",P)}if(Y&&H.length>0)Y({phase:"open",host:Q.label,done:H.length,total:H.length});if(M||U||H.length>0)X()}class hV{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new KV;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=RV;lastProgress=yV;scheduledSync;constructor(V,$,Z,J,Q,W=!0,Y=pV,X=lV,G){this.clock=V;this.state=$;this.store=Z;this.transport=J;this.crypto=Q;this.forceSkewHandlingByDefault=W;this.onScheduleSync=G;this.maxPushBytes=Y,this.maxPullBytes=X,this.clientState=new q0(()=>this.getClientState()),this.xferState=new q0(()=>this.getXferState()),this.scheduledSync=new uV(l$,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(K){console.error("Debounced sync failed:",K)}})}emitProgress=(V)=>{this.lastProgress=V,this.xferState.emit()};async setSeed(V){await this.store.seed.save(V),this.clientState.emit()}async getClientState(){let{store:V,connections:$}=this,Z=await V.seed.load(),J=await V.hosts.list(),Q=!1;for(let W of $.values())if(W.isConnected()){Q=!0;break}return{hasSeed:Z!==void 0,hasHost:Array.from(J).length>0,connected:Q}}async getXferState(){let{uploads:V,downloads:$}=this.store,Z=await V.count();return{numDownloads:await $.count(),numUploads:Z,progress:this.lastProgress}}apply=async(V,$={enqueueUpload:!0,triggerUpload:!0})=>{let Z=[],J=[];for(let{head:W,body:Y}of V){let X=new B;X.writeStruct(J0,W);let G=X.result(),K=await this.crypto.blake3(G),R={eid:W.eid,...W.off!==0?{off:W.off}:{},...W.ctr!==0?{ctr:W.ctr}:{},body:Y,apld:!1};Z.push(K),J.push({key:K,data:R})}await this.store.messages.add(J);let Q=await this.applyHashes(Z);if($.enqueueUpload){let W=[];for(let Y=0;Y<Z.length;Y++){let X=Q[Y];if(X===0||X===15)W.push(Z[Y])}if(W.length>0){let Y=await this.store.hosts.list();for(let X of Y)await this.store.uploads.enq(X.label,W);this.xferState.emit()}}if($.triggerUpload)this.scheduleSync();return Q};enqueueApplyJob(V){let $=this.applyChain.then(V,V);return this.applyChain=$.then(()=>{return},()=>{return}),$}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let V=await this.store.messages.listUnapplied();if(V.length<1)return[];return this.applyStored(V)}applyHashes=(V)=>{return this.enqueueApplyJob(async()=>{let $=[];for(let Q of V){let W=await this.store.messages.get(Q);if(W)$.push(W)}let Z=await this.applyStored($),J=new Map;for(let Q=0;Q<$.length;Q++)J.set(d($[Q].hash),Z[Q]??12);return V.map((Q)=>J.get(d(Q))??13)})};async applyStored(V){if(V.length<1)return[];let $=V.map((Q)=>({...Q.head,bod:Q.body})),Z=await this.state.apply($),J=[];for(let Q=0;Q<V.length;Q++){let W=Z[Q];if(W===0||W===15)J.push(V[Q].hash)}if(J.length>0)await this.store.messages.markApplied(J);return Z}async insertRaw(V){let{clock:$,crypto:Z}=this,[J,Q]=await p$({now:$.now(),bod:V,crypto:Z});if(Q!==0)return N(Q);return await this.apply([{head:J,body:V}]),O(J)}async upsertRaw(V,$,Z=!1){let{clock:J,crypto:Q,store:W}=this,Y=J.now(),X=await W.messages.last(V);if(X){let M=new m(V),[F,w]=M.readStruct(Y0);if(w!==0)return N(w);if(F.ts.getTime()+X.head.off>Y.getTime()){if(Z===!1)return N(4);let U=X.head.off+1,H=X.head.ctr+1,A={eid:V,off:U,ctr:H,len:0},D=(await this.apply([{head:A,body:void 0}]))[0];if(D!==0)return N(D);if($===void 0)return O(A);let[L,k]=ZV({id:F.id,ts:Y});if(k!==0)return N(k);let S={now:Y,eid:L,ctr:0,bod:$,crypto:Q},[E,x]=await GV(S);if(x!==0)return N(x);let f=(await this.apply([{head:E,body:$}]))[0];if(f!==0)return N(f);return O(E)}}let G=(X?.head.ctr??-1)+1,[K,R]=await GV({now:Y,eid:V,ctr:G,bod:$,crypto:Q});if(R!==0)return N(R);let z=(await this.apply([{head:K,body:$}]))[0];if(z!==0)return N(z);return O(K)}async insert(V){let{body:$,type:Z,gid:J,pid:Q}=V,Y=e0({body:$,type:Z,gid:J,pid:Q});return this.insertRaw(Y)}async upsert(V,$=this.forceSkewHandlingByDefault){let{eid:Z,body:J,type:Q,gid:W,pid:Y}=V;if(Z===void 0)return this.insert(V);let G=e0({body:J,type:Q,gid:W,pid:Y});return this.upsertRaw(Z,G,$)}async delete(V){return this.upsertRaw(V,void 0,!0)}async genEID(V){let{clock:$,crypto:Z}=this,J=$.now();if(V!==void 0)return ZV({id:V,ts:J});let Q=await Z.genRandomBytes(8);return ZV({id:Q,ts:J})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:V,crypto:$,store:Z}=this,J=await Z.seed.load();if(!J)return 22;await this.drainApplyQueue();for(let[Q,W]of V){let Y=await Z.hosts.get(Q);if(!Y)continue;let X={conn:W,store:Z,enclave:J,host:Y,crypto:$,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},G=await a$(X);if(G!==0)return console.error(`Failed to peek: ${G}`),G;this.xferState.emit();let K=await s$(X);if(K!==0)return console.error(`Failed to push: ${K}`),K;this.xferState.emit();let R=await t$(X,async()=>{await this.drainApplyQueue()});if(R!==0&&R!==15)return console.error(`Failed to pull: ${R}`),R;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async wipe(){this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush(),await this.store.wipe(),await this.state.clear(),this.lastProgress=yV,this.clientState.emit(),this.xferState.emit()}import=async(V,$)=>{let{crypto:Z,store:J}=this,Q=$?.onProgress,W=await J.seed.load();if(!W)return 22;console.time("import: decoding file...");let Y=await V.bytes(),[X,G]=await n$(Y,Z,W);if(G!==0)return G;console.timeEnd("import: decoding file...");let K=0;while(K<X.length){let R=0,I=0,z=K;for(let w=K;w<X.length&&I<100&&R<102400;w++)R+=X[w].head.len,I++,z=w+1;let M=X.slice(K,z);console.time(`import: applying [${K}, ${z}]`);let F=await this.apply(M,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${K}, ${z}]`);for(let w=0;w<M.length;w++){let q=F[w];if(q!==0&&q!==15)console.warn(`failed to import msg ${K+w}: ${j[q]}`)}if(Q)queueMicrotask(()=>Q(z,X.length,0));this.emitProgress({phase:"import",done:z,total:X.length}),K=z}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:V,store:$}=this,Z=await $.seed.load();if(!Z)return N(22);let J=await $.messages.list();return y$("export",0,J,V,Z)}async export(V){let[$,Z]=await this.exportBytes();if(Z!==0)return Z;if(!$)return 12;let J=new Blob([$.slice()]);return r$(J,V),0}async link(V,$=!0){if(await this.store.hosts.add(V),this.clientState.emit(),$){let Z=await this.store.hosts.get(V.label);if(Z)await this.connectToHost(Z)}}async unlink(V){await this.store.hosts.del(V),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async(V,$=!0,Z=!0)=>{let{clock:J,connections:Q,crypto:W,store:Y,transport:X}=this,G=Q.get(V.label);if(G){if(G.isConnected())return;try{G.closeListener()}catch{}Q.delete(V.label)}let K=await Y.seed.load();if(!K)return;console.info(`Connecting to ${V.handle} (${V.label})`);let R=new XV(K,W,V,J,X(V),(I)=>Y.hosts.set(V.label,I));if(await R.register(),$)await R.listen(async(I)=>{let z={conn:R,store:Y,enclave:K,host:V,crypto:W,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return VZ(I,z,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(Q.set(V.label,R),this.clientState.emit(),Z)this.scheduleSync()};async connect(V=!0,$=!0){let{connectToHost:Z,scheduleSync:J,store:Q}=this;if(!await Q.seed.load())return;await this.drainApplyQueue();let Y=await Q.hosts.list();for(let X of Y)await Z(X,V,!1);if($)J()}disconnect=async()=>{for(let V of this.connections.values())try{V.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var H0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function NV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function rV(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function l(V,...$){if(!rV(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function cV(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function $Z(V,$){l(V);let Z=$.outputLen;if(V.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function dV(V){if(typeof V!=="boolean")throw Error(`boolean expected, not ${V}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var N0=(V)=>new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4));var KJ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!KJ)throw Error("Non little-endian hardware is not supported");function RJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function IV(V){if(typeof V==="string")V=RJ(V);else if(rV(V))V=wV(V);else throw Error("Uint8Array expected, got "+typeof V);return V}function ZZ(V,$){if($==null||typeof $!=="object")throw Error("options must be defined");return Object.assign(V,$)}function JZ(V,$){if(V.length!==$.length)return!1;let Z=0;for(let J=0;J<V.length;J++)Z|=V[J]^$[J];return Z===0}var QZ=(V,$)=>{function Z(J,...Q){if(l(J),V.nonceLength!==void 0){let R=Q[0];if(!R)throw Error("nonce / iv required");if(V.varSizeNonce)l(R);else l(R,V.nonceLength)}let W=V.tagLength;if(W&&Q[1]!==void 0)l(Q[1]);let Y=$(J,...Q),X=(R,I)=>{if(I!==void 0){if(R!==2)throw Error("cipher output not supported");l(I)}},G=!1;return{encrypt(R,I){if(G)throw Error("cannot encrypt() twice with same key + nonce");return G=!0,l(R),X(Y.encrypt.length,I),Y.encrypt(R,I)},decrypt(R,I){if(l(R),W&&R.length<W)throw Error("invalid ciphertext length: smaller than tagLength="+W);return X(Y.decrypt.length,I),Y.decrypt(R,I)}}}return Object.assign(Z,V),Z};function oV(V,$,Z=!0){if($===void 0)return new Uint8Array(V);if($.length!==V)throw Error("invalid output length, expected "+V+", got: "+$.length);if(Z&&!NJ($))throw Error("invalid output, must be aligned");return $}function NJ(V){return V.byteOffset%4===0}function wV(V){return Uint8Array.from(V)}function X0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function zV(V=32){if(H0&&typeof H0.getRandomValues==="function")return H0.getRandomValues(new Uint8Array(V));if(H0&&typeof H0.randomBytes==="function")return H0.randomBytes(V);throw Error("crypto.getRandomValues must be defined")}var YZ=(V)=>Uint8Array.from(V.split("").map(($)=>$.charCodeAt(0))),IJ=YZ("expand 16-byte k"),wJ=YZ("expand 32-byte k"),zJ=N0(IJ),MJ=N0(wJ);function T(V,$){return V<<$|V>>>32-$}function aV(V){return V.byteOffset%4===0}var MV=64,FJ=16,XZ=4294967295,WZ=new Uint32Array;function PJ(V,$,Z,J,Q,W,Y,X){let G=Q.length,K=new Uint8Array(MV),R=N0(K),I=aV(Q)&&aV(W),z=I?N0(Q):WZ,M=I?N0(W):WZ;for(let F=0;F<G;Y++){if(V($,Z,J,R,Y,X),Y>=XZ)throw Error("arx: counter overflow");let w=Math.min(MV,G-F);if(I&&w===MV){let q=F/4;if(F%4!==0)throw Error("arx: invalid block position");for(let U=0,H;U<FJ;U++)H=q+U,M[H]=z[H]^R[U];F+=MV;continue}for(let q=0,U;q<w;q++)U=F+q,W[U]=Q[U]^K[q];F+=w}}function GZ(V,$){let{allowShortKeys:Z,extendNonceFn:J,counterLength:Q,counterRight:W,rounds:Y}=ZZ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},$);if(typeof V!=="function")throw Error("core must be a function");return NV(Q),NV(Y),dV(W),dV(Z),(X,G,K,R,I=0)=>{l(X),l(G),l(K);let z=K.length;if(R===void 0)R=new Uint8Array(z);if(l(R),NV(I),I<0||I>=XZ)throw Error("arx: counter overflow");if(R.length<z)throw Error(`arx: output (${R.length}) is shorter than data (${z})`);let M=[],F=X.length,w,q;if(F===32)M.push(w=wV(X)),q=MJ;else if(F===16&&Z)w=new Uint8Array(32),w.set(X),w.set(X,16),q=zJ,M.push(w);else throw Error(`arx: invalid 32-byte key, got length=${F}`);if(!aV(G))M.push(G=wV(G));let U=N0(w);if(J){if(G.length!==24)throw Error("arx: extended nonce must be 24 bytes");J(q,U,N0(G.subarray(0,16)),U),G=G.subarray(16)}let H=16-Q;if(H!==G.length)throw Error(`arx: nonce must be ${H} or 16 bytes`);if(H!==12){let P=new Uint8Array(12);P.set(G,W?0:12-G.length),G=P,M.push(G)}let A=N0(G);return PJ(V,q,U,A,K,R,I,Y),X0(...M),R}}var r=(V,$)=>V[$++]&255|(V[$++]&255)<<8;class KZ{constructor(V){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,V=IV(V),l(V,32);let $=r(V,0),Z=r(V,2),J=r(V,4),Q=r(V,6),W=r(V,8),Y=r(V,10),X=r(V,12),G=r(V,14);this.r[0]=$&8191,this.r[1]=($>>>13|Z<<3)&8191,this.r[2]=(Z>>>10|J<<6)&7939,this.r[3]=(J>>>7|Q<<9)&8191,this.r[4]=(Q>>>4|W<<12)&255,this.r[5]=W>>>1&8190,this.r[6]=(W>>>14|Y<<2)&8191,this.r[7]=(Y>>>11|X<<5)&8065,this.r[8]=(X>>>8|G<<8)&8191,this.r[9]=G>>>5&127;for(let K=0;K<8;K++)this.pad[K]=r(V,16+2*K)}process(V,$,Z=!1){let J=Z?0:2048,{h:Q,r:W}=this,Y=W[0],X=W[1],G=W[2],K=W[3],R=W[4],I=W[5],z=W[6],M=W[7],F=W[8],w=W[9],q=r(V,$+0),U=r(V,$+2),H=r(V,$+4),A=r(V,$+6),P=r(V,$+8),D=r(V,$+10),L=r(V,$+12),k=r(V,$+14),S=Q[0]+(q&8191),E=Q[1]+((q>>>13|U<<3)&8191),x=Q[2]+((U>>>10|H<<6)&8191),C=Q[3]+((H>>>7|A<<9)&8191),f=Q[4]+((A>>>4|P<<12)&8191),v=Q[5]+(P>>>1&8191),u=Q[6]+((P>>>14|D<<2)&8191),y=Q[7]+((D>>>11|L<<5)&8191),n=Q[8]+((L>>>8|k<<8)&8191),p=Q[9]+(k>>>5|J),_=0,c=_+S*Y+E*(5*w)+x*(5*F)+C*(5*M)+f*(5*z);_=c>>>13,c&=8191,c+=v*(5*I)+u*(5*R)+y*(5*K)+n*(5*G)+p*(5*X),_+=c>>>13,c&=8191;let o=_+S*X+E*Y+x*(5*w)+C*(5*F)+f*(5*M);_=o>>>13,o&=8191,o+=v*(5*z)+u*(5*I)+y*(5*R)+n*(5*K)+p*(5*G),_+=o>>>13,o&=8191;let e=_+S*G+E*X+x*Y+C*(5*w)+f*(5*F);_=e>>>13,e&=8191,e+=v*(5*M)+u*(5*z)+y*(5*I)+n*(5*R)+p*(5*K),_+=e>>>13,e&=8191;let g=_+S*K+E*G+x*X+C*Y+f*(5*w);_=g>>>13,g&=8191,g+=v*(5*F)+u*(5*M)+y*(5*z)+n*(5*I)+p*(5*R),_+=g>>>13,g&=8191;let K0=_+S*R+E*K+x*G+C*X+f*Y;_=K0>>>13,K0&=8191,K0+=v*(5*w)+u*(5*F)+y*(5*M)+n*(5*z)+p*(5*I),_+=K0>>>13,K0&=8191;let A0=_+S*I+E*R+x*K+C*G+f*X;_=A0>>>13,A0&=8191,A0+=v*Y+u*(5*w)+y*(5*F)+n*(5*M)+p*(5*z),_+=A0>>>13,A0&=8191;let D0=_+S*z+E*I+x*R+C*K+f*G;_=D0>>>13,D0&=8191,D0+=v*X+u*Y+y*(5*w)+n*(5*F)+p*(5*M),_+=D0>>>13,D0&=8191;let _0=_+S*M+E*z+x*I+C*R+f*K;_=_0>>>13,_0&=8191,_0+=v*G+u*X+y*Y+n*(5*w)+p*(5*F),_+=_0>>>13,_0&=8191;let j0=_+S*F+E*M+x*z+C*I+f*R;_=j0>>>13,j0&=8191,j0+=v*K+u*G+y*X+n*Y+p*(5*w),_+=j0>>>13,j0&=8191;let L0=_+S*w+E*F+x*M+C*z+f*I;_=L0>>>13,L0&=8191,L0+=v*R+u*K+y*G+n*X+p*Y,_+=L0>>>13,L0&=8191,_=(_<<2)+_|0,_=_+c|0,c=_&8191,_=_>>>13,o+=_,Q[0]=c,Q[1]=o,Q[2]=e,Q[3]=g,Q[4]=K0,Q[5]=A0,Q[6]=D0,Q[7]=_0,Q[8]=j0,Q[9]=L0}finalize(){let{h:V,pad:$}=this,Z=new Uint16Array(10),J=V[1]>>>13;V[1]&=8191;for(let Y=2;Y<10;Y++)V[Y]+=J,J=V[Y]>>>13,V[Y]&=8191;V[0]+=J*5,J=V[0]>>>13,V[0]&=8191,V[1]+=J,J=V[1]>>>13,V[1]&=8191,V[2]+=J,Z[0]=V[0]+5,J=Z[0]>>>13,Z[0]&=8191;for(let Y=1;Y<10;Y++)Z[Y]=V[Y]+J,J=Z[Y]>>>13,Z[Y]&=8191;Z[9]-=8192;let Q=(J^1)-1;for(let Y=0;Y<10;Y++)Z[Y]&=Q;Q=~Q;for(let Y=0;Y<10;Y++)V[Y]=V[Y]&Q|Z[Y];V[0]=(V[0]|V[1]<<13)&65535,V[1]=(V[1]>>>3|V[2]<<10)&65535,V[2]=(V[2]>>>6|V[3]<<7)&65535,V[3]=(V[3]>>>9|V[4]<<4)&65535,V[4]=(V[4]>>>12|V[5]<<1|V[6]<<14)&65535,V[5]=(V[6]>>>2|V[7]<<11)&65535,V[6]=(V[7]>>>5|V[8]<<8)&65535,V[7]=(V[8]>>>8|V[9]<<5)&65535;let W=V[0]+$[0];V[0]=W&65535;for(let Y=1;Y<8;Y++)W=(V[Y]+$[Y]|0)+(W>>>16)|0,V[Y]=W&65535;X0(Z)}update(V){cV(this);let{buffer:$,blockLen:Z}=this;V=IV(V);let J=V.length;for(let Q=0;Q<J;){let W=Math.min(Z-this.pos,J-Q);if(W===Z){for(;Z<=J-Q;Q+=Z)this.process(V,Q);continue}if($.set(V.subarray(Q,Q+W),this.pos),this.pos+=W,Q+=W,this.pos===Z)this.process($,0,!1),this.pos=0}return this}destroy(){X0(this.h,this.r,this.buffer,this.pad)}digestInto(V){cV(this),$Z(V,this),this.finished=!0;let{buffer:$,h:Z}=this,{pos:J}=this;if(J){$[J++]=1;for(;J<16;J++)$[J]=0;this.process($,0,!0)}this.finalize();let Q=0;for(let W=0;W<8;W++)V[Q++]=Z[W]>>>0,V[Q++]=Z[W]>>>8;return V}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Z=V.slice(0,$);return this.destroy(),Z}}function UJ(V){let $=(J,Q)=>V(Q).update(IV(J)).digest(),Z=V(new Uint8Array(32));return $.outputLen=Z.outputLen,$.blockLen=Z.blockLen,$.create=(J)=>V(J),$}var sV=UJ((V)=>new KZ(V));function qJ(V,$,Z,J,Q,W=20){let Y=V[0],X=$[0],G=$[1],K=$[2],R=$[3],I=V[1],z=Z[0],M=Z[1],F=Q,w=0,q=V[2],U=$[4],H=$[5],A=$[6],P=$[7],D=V[3],L=Y,k=X,S=G,E=K,x=R,C=I,f=z,v=M,u=F,y=w,n=q,p=U,_=H,c=A,o=P,e=D;for(let K0=0;K0<W;K0+=2)x^=T(L+_|0,7),u^=T(x+L|0,9),_^=T(u+x|0,13),L^=T(_+u|0,18),y^=T(C+k|0,7),c^=T(y+C|0,9),k^=T(c+y|0,13),C^=T(k+c|0,18),o^=T(n+f|0,7),S^=T(o+n|0,9),f^=T(S+o|0,13),n^=T(f+S|0,18),E^=T(e+p|0,7),v^=T(E+e|0,9),p^=T(v+E|0,13),e^=T(p+v|0,18),k^=T(L+E|0,7),S^=T(k+L|0,9),E^=T(S+k|0,13),L^=T(E+S|0,18),f^=T(C+x|0,7),v^=T(f+C|0,9),x^=T(v+f|0,13),C^=T(x+v|0,18),p^=T(n+y|0,7),u^=T(p+n|0,9),y^=T(u+p|0,13),n^=T(y+u|0,18),_^=T(e+o|0,7),c^=T(_+e|0,9),o^=T(c+_|0,13),e^=T(o+c|0,18);let g=0;J[g++]=Y+L|0,J[g++]=X+k|0,J[g++]=G+S|0,J[g++]=K+E|0,J[g++]=R+x|0,J[g++]=I+C|0,J[g++]=z+f|0,J[g++]=M+v|0,J[g++]=F+u|0,J[g++]=w+y|0,J[g++]=q+n|0,J[g++]=U+p|0,J[g++]=H+_|0,J[g++]=A+c|0,J[g++]=P+o|0,J[g++]=D+e|0}function OJ(V,$,Z,J){let Q=V[0],W=$[0],Y=$[1],X=$[2],G=$[3],K=V[1],R=Z[0],I=Z[1],z=Z[2],M=Z[3],F=V[2],w=$[4],q=$[5],U=$[6],H=$[7],A=V[3];for(let D=0;D<20;D+=2)G^=T(Q+q|0,7),z^=T(G+Q|0,9),q^=T(z+G|0,13),Q^=T(q+z|0,18),M^=T(K+W|0,7),U^=T(M+K|0,9),W^=T(U+M|0,13),K^=T(W+U|0,18),H^=T(F+R|0,7),Y^=T(H+F|0,9),R^=T(Y+H|0,13),F^=T(R+Y|0,18),X^=T(A+w|0,7),I^=T(X+A|0,9),w^=T(I+X|0,13),A^=T(w+I|0,18),W^=T(Q+X|0,7),Y^=T(W+Q|0,9),X^=T(Y+W|0,13),Q^=T(X+Y|0,18),R^=T(K+G|0,7),I^=T(R+K|0,9),G^=T(I+R|0,13),K^=T(G+I|0,18),w^=T(F+M|0,7),z^=T(w+F|0,9),M^=T(z+w|0,13),F^=T(M+z|0,18),q^=T(A+H|0,7),U^=T(q+A|0,9),H^=T(U+q|0,13),A^=T(H+U|0,18);let P=0;J[P++]=Q,J[P++]=K,J[P++]=F,J[P++]=A,J[P++]=R,J[P++]=I,J[P++]=z,J[P++]=M}var tV=GZ(qJ,{counterRight:!0,extendNonceFn:OJ}),eV=QZ({blockSize:64,nonceLength:24,tagLength:16},(V,$)=>{return{encrypt(Z,J){J=oV(Z.length+32,J,!1);let Q=J.subarray(0,32),W=J.subarray(32);J.set(Z,32),X0(Q),tV(V,$,J,J);let Y=sV(W,Q);return J.set(Y,16),X0(J.subarray(0,16),Y),J.subarray(16)},decrypt(Z,J){l(Z),J=oV(Z.length+32,J,!1);let Q=J.subarray(0,32),W=J.subarray(32,48),Y=J.subarray(48);J.set(Z,32),X0(Q);let X=tV(V,$,Q,Q),G=sV(Y,X);if(!JZ(W,G))throw Error("invalid tag");return tV(V,$,J.subarray(16),J.subarray(16)),X0(Q,W,G),Y}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function HJ(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function l0(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function C0(V,...$){if(!HJ(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function h0(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function FV(V,$){C0(V);let Z=$.outputLen;if(V.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function RZ(V){return new Uint8Array(V.buffer,V.byteOffset,V.byteLength)}function x0(V){return new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4))}function B0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function r0(V,$){return V<<32-$|V>>>$}var NZ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function IZ(V){return V<<24&4278190080|V<<8&16711680|V>>>8&65280|V>>>24&255}var wZ=NZ?(V)=>V:(V)=>IZ(V);function CJ(V){for(let $=0;$<V.length;$++)V[$]=IZ(V[$]);return V}var s=NZ?(V)=>V:CJ;function TJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function f0(V){if(typeof V==="string")V=TJ(V);return C0(V),V}class V${}function zZ(V){let $=(J,Q)=>V(Q).update(f0(J)).digest(),Z=V({});return $.outputLen=Z.outputLen,$.blockLen=Z.blockLen,$.create=(J)=>V(J),$}var MZ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var PV=BigInt(4294967295),FZ=BigInt(32);function $$(V,$=!1){if($)return{h:Number(V&PV),l:Number(V>>FZ&PV)};return{h:Number(V>>FZ&PV)|0,l:Number(V&PV)|0}}function I0(V,$,Z,J,Q){return V=V+$+Q|0,J=r0(J^V,16),Z=Z+J|0,$=r0($^Z,12),{a:V,b:$,c:Z,d:J}}function w0(V,$,Z,J,Q){return V=V+$+Q|0,J=r0(J^V,8),Z=Z+J|0,$=r0($^Z,7),{a:V,b:$,c:Z,d:J}}class Z$ extends V${constructor(V,$){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,l0(V),l0($),this.blockLen=V,this.outputLen=$,this.buffer=new Uint8Array(V),this.buffer32=x0(this.buffer)}update(V){h0(this),V=f0(V),C0(V);let{blockLen:$,buffer:Z,buffer32:J}=this,Q=V.length,W=V.byteOffset,Y=V.buffer;for(let X=0;X<Q;){if(this.pos===$)s(J),this.compress(J,0,!1),s(J),this.pos=0;let G=Math.min($-this.pos,Q-X),K=W+X;if(G===$&&!(K%4)&&X+G<Q){let R=new Uint32Array(Y,K,Math.floor((Q-X)/4));s(R);for(let I=0;X+$<Q;I+=J.length,X+=$)this.length+=$,this.compress(R,I,!1);s(R);continue}Z.set(V.subarray(X,X+G),this.pos),this.pos+=G,this.length+=G,X+=G}return this}digestInto(V){h0(this),FV(V,this);let{pos:$,buffer32:Z}=this;this.finished=!0,B0(this.buffer.subarray($)),s(Z),this.compress(Z,0,!0),s(Z);let J=x0(V);this.get().forEach((Q,W)=>J[W]=wZ(Q))}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Z=V.slice(0,$);return this.destroy(),Z}_cloneInto(V){let{buffer:$,length:Z,finished:J,destroyed:Q,outputLen:W,pos:Y}=this;return V||(V=new this.constructor({dkLen:W})),V.set(...this.get()),V.buffer.set($),V.destroyed=Q,V.finished=J,V.length=Z,V.pos=Y,V.outputLen=W,V}clone(){return this._cloneInto()}}function J$(V,$,Z,J,Q,W,Y,X,G,K,R,I,z,M,F,w,q,U,H,A){let P=0;for(let D=0;D<J;D++)({a:Q,b:G,c:z,d:q}=I0(Q,G,z,q,Z[$+V[P++]])),{a:Q,b:G,c:z,d:q}=w0(Q,G,z,q,Z[$+V[P++]]),{a:W,b:K,c:M,d:U}=I0(W,K,M,U,Z[$+V[P++]]),{a:W,b:K,c:M,d:U}=w0(W,K,M,U,Z[$+V[P++]]),{a:Y,b:R,c:F,d:H}=I0(Y,R,F,H,Z[$+V[P++]]),{a:Y,b:R,c:F,d:H}=w0(Y,R,F,H,Z[$+V[P++]]),{a:X,b:I,c:w,d:A}=I0(X,I,w,A,Z[$+V[P++]]),{a:X,b:I,c:w,d:A}=w0(X,I,w,A,Z[$+V[P++]]),{a:Q,b:K,c:F,d:A}=I0(Q,K,F,A,Z[$+V[P++]]),{a:Q,b:K,c:F,d:A}=w0(Q,K,F,A,Z[$+V[P++]]),{a:W,b:R,c:w,d:q}=I0(W,R,w,q,Z[$+V[P++]]),{a:W,b:R,c:w,d:q}=w0(W,R,w,q,Z[$+V[P++]]),{a:Y,b:I,c:z,d:U}=I0(Y,I,z,U,Z[$+V[P++]]),{a:Y,b:I,c:z,d:U}=w0(Y,I,z,U,Z[$+V[P++]]),{a:X,b:G,c:M,d:H}=I0(X,G,M,H,Z[$+V[P++]]),{a:X,b:G,c:M,d:H}=w0(X,G,M,H,Z[$+V[P++]]);return{v0:Q,v1:W,v2:Y,v3:X,v4:G,v5:K,v6:R,v7:I,v8:z,v9:M,v10:F,v11:w,v12:q,v13:U,v14:H,v15:A}}var G0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},z0=MZ.slice(),PZ=(()=>{let V=Array.from({length:16},(J,Q)=>Q),$=(J)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((Q)=>J[Q]),Z=[];for(let J=0,Q=V;J<7;J++,Q=$(Q))Z.push(...Q);return Uint8Array.from(Z)})();class Q$ extends Z${constructor(V={},$=0){super(64,V.dkLen===void 0?32:V.dkLen);this.chunkPos=0,this.chunksDone=0,this.flags=0,this.stack=[],this.posOut=0,this.bufferOut32=new Uint32Array(16),this.chunkOut=0,this.enableXOF=!0;let{key:Z,context:J}=V,Q=J!==void 0;if(Z!==void 0){if(Q)throw Error('Only "key" or "context" can be specified at same time');let W=f0(Z).slice();C0(W,32),this.IV=x0(W),s(this.IV),this.flags=$|G0.KEYED_HASH}else if(Q){let W=f0(J),Y=new Q$({dkLen:32},G0.DERIVE_KEY_CONTEXT).update(W).digest();this.IV=x0(Y),s(this.IV),this.flags=$|G0.DERIVE_KEY_MATERIAL}else this.IV=z0.slice(),this.flags=$;this.state=this.IV.slice(),this.bufferOut=RZ(this.bufferOut32)}get(){return[]}set(){}b2Compress(V,$,Z,J=0){let{state:Q,pos:W}=this,{h:Y,l:X}=$$(BigInt(V),!0),{v0:G,v1:K,v2:R,v3:I,v4:z,v5:M,v6:F,v7:w,v8:q,v9:U,v10:H,v11:A,v12:P,v13:D,v14:L,v15:k}=J$(PZ,J,Z,7,Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7],z0[0],z0[1],z0[2],z0[3],Y,X,W,$);Q[0]=G^q,Q[1]=K^U,Q[2]=R^H,Q[3]=I^A,Q[4]=z^P,Q[5]=M^D,Q[6]=F^L,Q[7]=w^k}compress(V,$=0,Z=!1){let J=this.flags;if(!this.chunkPos)J|=G0.CHUNK_START;if(this.chunkPos===15||Z)J|=G0.CHUNK_END;if(!Z)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,J,V,$),this.chunkPos+=1,this.chunkPos===16||Z){let Q=this.state;this.state=this.IV.slice();for(let W,Y=this.chunksDone+1;Z||!(Y&1);Y>>=1){if(!(W=this.stack.pop()))break;this.buffer32.set(W,0),this.buffer32.set(Q,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|G0.PARENT,this.buffer32,0),Q=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(Q)}this.pos=0}_cloneInto(V){V=super._cloneInto(V);let{IV:$,flags:Z,state:J,chunkPos:Q,posOut:W,chunkOut:Y,stack:X,chunksDone:G}=this;return V.state.set(J.slice()),V.stack=X.map((K)=>Uint32Array.from(K)),V.IV.set($),V.flags=Z,V.chunkPos=Q,V.chunksDone=G,V.posOut=W,V.chunkOut=Y,V.enableXOF=this.enableXOF,V.bufferOut32.set(this.bufferOut32),V}destroy(){this.destroyed=!0,B0(this.state,this.buffer32,this.IV,this.bufferOut32),B0(...this.stack)}b2CompressOut(){let{state:V,pos:$,flags:Z,buffer32:J,bufferOut32:Q}=this,{h:W,l:Y}=$$(BigInt(this.chunkOut++));s(J);let{v0:X,v1:G,v2:K,v3:R,v4:I,v5:z,v6:M,v7:F,v8:w,v9:q,v10:U,v11:H,v12:A,v13:P,v14:D,v15:L}=J$(PZ,0,J,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],z0[0],z0[1],z0[2],z0[3],Y,W,$,Z);Q[0]=X^w,Q[1]=G^q,Q[2]=K^U,Q[3]=R^H,Q[4]=I^A,Q[5]=z^P,Q[6]=M^D,Q[7]=F^L,Q[8]=V[0]^w,Q[9]=V[1]^q,Q[10]=V[2]^U,Q[11]=V[3]^H,Q[12]=V[4]^A,Q[13]=V[5]^P,Q[14]=V[6]^D,Q[15]=V[7]^L,s(J),s(Q),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,B0(this.buffer.subarray(this.pos));let V=this.flags|G0.ROOT;if(this.stack.length)V|=G0.PARENT,s(this.buffer32),this.compress(this.buffer32,0,!0),s(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else V|=(!this.chunkPos?G0.CHUNK_START:0)|G0.CHUNK_END;this.flags=V,this.b2CompressOut()}writeInto(V){h0(this,!1),C0(V),this.finish();let{blockLen:$,bufferOut:Z}=this;for(let J=0,Q=V.length;J<Q;){if(this.posOut>=$)this.b2CompressOut();let W=Math.min($-this.posOut,Q-J);V.set(Z.subarray(this.posOut,this.posOut+W),J),this.posOut+=W,J+=W}return V}xofInto(V){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(V)}xof(V){return l0(V),this.xofInto(new Uint8Array(V))}digestInto(V){if(FV(V,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto(V),this.destroy(),V}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var UZ=zZ((V)=>new Q$(V));var W$=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function qZ(V){let $=new Uint8Array(W$.length+32);return $.set(W$),$.set(V.subarray(0,32),W$.length),$}function OZ(V){return typeof V==="string"?new TextEncoder().encode(V):V}function m0(V){let $=new ArrayBuffer(V.byteLength);return new Uint8Array($).set(V),$}class Y${verifyKeys=new Map;signKeys=new Map;async genRandomBytes(V){return zV(V)}async gen256BitSecureRandomSeed(){return zV(32)}async encryptXSalsa20Poly1305Combined(V,$){let Z=zV(24),Q=eV($,Z).encrypt(V);return new Uint8Array([...Z,...Q])}async decryptXSalsa20Poly1305Combined(V,$){let Z=V.slice(0,24),J=V.slice(24);return eV($,Z).decrypt(J)}async deriveEd25519KeyPair(V){let $=V,Z=qZ($),J=await globalThis.crypto.subtle.importKey("pkcs8",m0(Z),{name:"Ed25519"},!0,["sign"]),Q=await globalThis.crypto.subtle.exportKey("jwk",J);if(typeof Q.x!=="string")throw Error("Ed25519 JWK missing x");let W=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:Q.x},{name:"Ed25519"},!0,["verify"]),Y=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",W)),X=new Uint8Array(64);return X.set($,0),X.set(Y,32),this.signKeys.set(Q0($),J),this.verifyKeys.set(Q0(Y),W),{keyType:"ed25519",privateKey:X,publicKey:Y}}async importSignKey(V){let $=V.subarray(0,32),Z=Q0($),J=this.signKeys.get(Z);if(J)return J;let Q=qZ($),W=await globalThis.crypto.subtle.importKey("pkcs8",m0(Q),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Z,W),W}async importVerifyKey(V){let $=Q0(V),Z=this.verifyKeys.get($);if(Z)return Z;let J=await globalThis.crypto.subtle.importKey("raw",m0(V),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set($,J),J}async signEd25519(V,$){let Z=OZ(V),J=await this.importSignKey($),Q=await globalThis.crypto.subtle.sign({name:"Ed25519"},J,m0(Z));return new Uint8Array(Q)}async checkSigEd25519(V,$,Z){let J=OZ($);try{let Q=await this.importVerifyKey(Z);return await globalThis.crypto.subtle.verify({name:"Ed25519"},Q,m0(V),m0(J))}catch{return!1}}async blake3(V){return UZ(V)}}var AJ=new Y$,g0=AJ;var WG=Symbol("EntityID");function HZ(V){return"type"in V}var YG=Symbol("MasterSeed"),XG=Symbol("DerivationSeed"),GG=Symbol("PublicKey"),KG=Symbol("PrivateKey"),RG=Symbol("HostSpecificKeyPair"),NG=Symbol("Hash");function DJ(V){if(!V)return!1;if(typeof V!=="object")return!1;if("body"in V===!1)return!1;if("type"in V===!1)return!1;return!0}function _J(V){if(!V.bod||V.bod.length===0){let J={off:V.off,ctr:V.ctr,eid:V.eid};return O(J)}let $=_V(V.bod);if(DJ($)===!1)return console.warn("msg body invalid",$),N(14);let Z={off:V.off,ctr:V.ctr,eid:V.eid,gid:$.gid,pid:$.pid,type:$.type,body:$.body};return O(Z)}class UV{applier;emitter=new y0;clearer;onTypes;constructor(V,$,Z){this.applier=V;this.clearer=$,this.onTypes=Z}apply=async(V)=>{let $=[],Z=[];for(let Y of V){let[X,G]=_J(Y);if(Z.push(G),G!==0)continue;$.push(X)}let{stats:J,types:Q}=await this.applier($),W=[];for(let Y=0;Y<V.length;Y++){let X=Z[Y],G=J[Y];if(X!==0){W.push(X);continue}if(G!==0){W.push(G);continue}W.push(0)}for(let Y of Q)this.emitter.emit(Y,null);if(Q.size>0)this.onTypes?.(Q);return W};clear=async()=>{let V=await this.clearer();if(V!==0)return V;return this.emitter.emitAll(null),V};notify=(V)=>{for(let $ of V)this.emitter.emit($,null)};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}function CZ(V,$){let Z=new m($.eid),[J,Q]=Z.readStruct(Y0);if(Q!==0)return N(Q);let W=new Date(J.ts.getTime()+$.off);if(V!==void 0&&W<=V.updatedAt)return N(15);if(HZ($))return O({eid:$.eid,gid:$.gid,pid:$.pid,type:$.type,createdAt:J.ts,updatedAt:W,ctr:$.ctr,body:$.body});else return O(void 0)}var b="entities",qV="entity_type_created_at",X$="entity_type_updated_at",G$="entity_type_group_id",K$="entity_type_parent_id";function jJ(V){let $={bod:V.body,crd:V.createdAt,...V.ctr!==0?{ctr:V.ctr}:{},eid:d(V.eid),gid:V.gid,pid:V.pid?d(V.pid):void 0,typ:V.type,upd:V.updatedAt};if($.gid===void 0)delete $.gid;if($.pid===void 0)delete $.pid;if($.ctr===void 0)delete $.ctr;return $}function v0(V){return{body:V.bod,createdAt:V.crd,updatedAt:V.upd,ctr:V.ctr??0,type:V.typ,eid:R0(V.eid),gid:V.gid,pid:V.pid?R0(V.pid):void 0}}class TZ{db;async init(){this.db=await new Promise((V,$)=>{let Z=indexedDB.open("db",11);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!Q)throw Error("Transaction is null during upgrade");if(!J.objectStoreNames.contains(b))J.createObjectStore(b,{keyPath:"eid",autoIncrement:!1});let W=Q.objectStore(b);if(!W.indexNames.contains(qV))W.createIndex(qV,["typ","crd"],{unique:!1});if(!W.indexNames.contains(X$))W.createIndex(X$,["typ","upd"],{unique:!1});if(!W.indexNames.contains(G$))W.createIndex(G$,["typ","gid"],{unique:!1});if(!W.indexNames.contains(K$))W.createIndex(K$,["typ","pid"],{unique:!1})},Z.onsuccess=()=>V(Z.result),Z.onerror=()=>$(Z.error)})}apply=async(V)=>{let $=new Set;if(!this.db)return{stats:V.map(()=>16),types:$};let Z=this.db.transaction(b,"readwrite"),J=Z.objectStore(b);return new Promise((Q)=>{let W=Array(V.length).fill(0);if(V.length<1){Q({stats:[],types:$});return}Z.oncomplete=()=>{Q({stats:W,types:$})},Z.onerror=()=>{for(let X=0;X<W.length;X++)if(W[X]===void 0)W[X]=18;Q({stats:W,types:$})};let Y=new Map;for(let X=0;X<V.length;X++){let G=V[X],K=d(G.eid),R={op:G,index:X},I=Y.get(K);if(I)I.push(R);else Y.set(K,[R])}for(let[X,G]of Y){if(G.length<1)continue;let K=J.get(X);K.onsuccess=()=>{let R=K.result,I=R?v0(R):void 0;for(let{op:z,index:M}of G){let[F,w]=CZ(I,z);if(w!==0){W[M]=w;continue}if(F)$.add(F.type);else if(I)$.add(I.type);I=F}if(I){let z=jJ(I),M=J.put(z);M.onerror=(F)=>{F.preventDefault();for(let{index:w}of G)W[w]=18}}else{let z=J.delete(X);z.onerror=()=>{for(let{index:M}of G)W[M]=18}}},K.onerror=()=>{for(let{index:R}of G)W[R]=18}}})};async clear(){if(!this.db)return 16;let V=this.db.transaction(b,"readwrite"),$=V.objectStore(b);return new Promise((Z)=>{V.oncomplete=()=>Z(0),V.onerror=()=>Z(18),$.clear()})}async getEnt(V){if(!this.db)return N(16);let $=d(V),J=this.db.transaction(b,"readonly").objectStore(b);return new Promise((Q)=>{let W=J.get($);W.onsuccess=()=>{let Y=W.result;if(!Y)Q(O(void 0));else{let X=v0(Y);Q(O(X))}},W.onerror=()=>Q(N(18))})}async getAllOfTypeUpdatedBetween(V,$,Z){if(!this.db)return N(16);let Q=this.db.transaction(b,"readonly").objectStore(b).index(X$);return new Promise((W)=>{let Y=Q.getAll(IDBKeyRange.bound([V,$],[V,Z]));Y.onsuccess=()=>{let X=Y.result;W(O(X.map(v0)))},Y.onerror=()=>W(N(18))})}async getGroupMembers(V,$){if(!this.db)return N(16);let J=this.db.transaction(b,"readonly").objectStore(b).index(G$);return new Promise((Q)=>{let W=J.getAll(IDBKeyRange.only([V,$]));W.onsuccess=()=>{let Y=W.result;Q(O(Y.map(v0)))},W.onerror=()=>Q(N(18))})}async getAllOfType(V){if(!this.db)return N(16);let Z=this.db.transaction(b,"readonly").objectStore(b).index(qV);return new Promise((J)=>{let Q=Z.getAll(IDBKeyRange.bound([V],[V,[]]));Q.onsuccess=()=>{let W=Q.result;J(O(W.map(v0)))},Q.onerror=()=>J(N(18))})}async getAllEntities(V){if(!this.db)return N(16);if("pid"in V){let $=d(V.pid),J=this.db.transaction(b,"readonly").objectStore(b).index(K$);return new Promise((Q)=>{let W=J.getAll(IDBKeyRange.only([V.type,$]));W.onsuccess=()=>{let X=W.result.map(v0);Q(O(X))},W.onerror=()=>Q(N(18))})}else if("gid"in V)return await this.getGroupMembers(V.type,V.gid);else if("updatedBetween"in V)return await this.getAllOfTypeUpdatedBetween(V.type,V.updatedBetween.start,V.updatedBetween.end);return await this.getAllOfType(V.type)}async getEntities(V){let[$,Z]=await this.getAllEntities(V);if(Z!==0)return N(Z);return O($)}async countEntities({type:V}){if(!this.db)return N(16);let Z=this.db.transaction(b,"readonly").objectStore(b).index(qV);return new Promise((J)=>{let Q=IDBKeyRange.bound([V],[V,[]]),W=Z.count(Q);W.onsuccess=()=>J(O(W.result)),W.onerror=()=>J(N(18))})}}async function AZ(){let V=new TZ;return await V.init(),V}class R${db;constructor(V){this.db=V}async enq(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction($0,"readwrite"),J=Z.objectStore($0);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=`${Y.host}:${Y.seq}`;J.put(Y,X)}})}async deq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction($0,"readwrite"),Q=J.objectStore($0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let G=`${V}:${X}`;Q.delete(G)}})}async list(){let $=this.db.transaction($0,"readonly").objectStore($0);return new Promise((Z,J)=>{let Q=$.getAll();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async count(){let $=this.db.transaction($0,"readonly").objectStore($0);return new Promise((Z,J)=>{let Q=$.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction($0,"readwrite"),$=V.objectStore($0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}function DZ(V){return{label:V.label,handle:new URL(V.handle),idx:V.idx,lastSeq:V.lastSeq||0,clockOffset:V.clockOffset,subscription:V.subscription}}class N${db;constructor(V){this.db=V}async add(V){return this.put(V)}async put(V){let $={...V,handle:V.handle.toString(),lastSeq:V.lastSeq??0},Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error),J.put($)})}async touch(V,$){let Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);let Y=J.get(V);Y.onsuccess=()=>{let X=Y.result;if(!X)return;let G=X.lastSeq||0;if($<=G)return;J.put({...X,lastSeq:$})}})}async get(V){let Z=this.db.transaction(t,"readonly").objectStore(t);return new Promise((J,Q)=>{let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)J(void 0);else J(DZ(Y))},W.onerror=()=>Q(W.error)})}async set(V,$){let Z=await this.get(V);if(!Z)return 13;try{return await this.put({...Z,...$}),0}catch{return 18}}async del(V){let $=this.db.transaction(t,"readwrite"),Z=$.objectStore(t);return new Promise((J,Q)=>{$.oncomplete=()=>J(),$.onerror=()=>Q($.error),Z.delete(V)})}async list(){let $=this.db.transaction(t,"readonly").objectStore(t);return new Promise((Z,J)=>{let Q=$.getAll();Q.onsuccess=()=>{let W=Q.result;Z(W.map(DZ))},Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(t,"readwrite"),$=V.objectStore(t);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}function LJ(V){return V===!0||V==="t"}function I$(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld===void 0?!1:LJ(V.apld)}}async function c0(V,$,Z){let J=I$($),Q=J.body?.length??0,W;if(J.body&&Q>0)W=await Z.blake3(J.body);let Y={eid:J.eid,off:J.off??0,ctr:J.ctr??0,len:Q,hsh:W};return{hash:V,head:Y,body:J.body,applied:J.apld}}function _Z(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld?"t":"f"}}class w${crypto;db;constructor(V,$){this.crypto=$;this.db=V}async add(V){let $=this.db.transaction(i,"readwrite"),Z=$.objectStore(i);return new Promise((J)=>{if(V.length===0){J([]);return}let Q=Array(V.length).fill(0);$.oncomplete=()=>J(Q),$.onerror=()=>{for(let W=0;W<Q.length;W++)Q[W]=18;J(Q)};for(let W=0;W<V.length;W++){let{key:Y,data:X}=V[W],G=d(Y),K=Z.put(_Z(X),G);K.onerror=(R)=>{R.preventDefault(),Q[W]=18}}})}async del(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(i,"readwrite"),J=Z.objectStore(i);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=d(Y);J.delete(X)}})}async get(V){let Z=this.db.transaction(i,"readonly").objectStore(i);return new Promise((J,Q)=>{let W=d(V),Y=Z.get(W);Y.onsuccess=async()=>{let X=Y.result;if(X)J(await c0(V,X,this.crypto));else J(void 0)},Y.onerror=()=>Q(Y.error)})}async has(V){return await this.get(V)!==void 0}async list(){let $=this.db.transaction(i,"readonly").objectStore(i);return new Promise((Z,J)=>{let Q=[],W=$.openCursor();W.onsuccess=async(Y)=>{let X=Y.target.result;if(X){let{key:G,value:K}=X,R=R0(G),I=await c0(R,K,this.crypto);Q.push(I),X.continue()}else Z(Q)},W.onerror=()=>J(W.error)})}async last(V){let Z=this.db.transaction(i,"readonly").objectStore(i);return new Promise((J,Q)=>{let W,Y=Z.openCursor();Y.onsuccess=async(X)=>{let G=X.target.result;if(G){let{key:K,value:R}=G;if(O0(V,R.eid)){if(!W||(R.ctr??0)>(W.data.ctr??0)||(R.ctr??0)===(W.data.ctr??0)&&(R.off??0)>(W.data.off??0))W={key:K,data:R}}G.continue()}else if(W){let K=R0(W.key);J(await c0(K,W.data,this.crypto))}else J(void 0)},Y.onerror=()=>Q(Y.error)})}async listUnapplied(){let Z=this.db.transaction(i,"readonly").objectStore(i).index(OV);return new Promise((J,Q)=>{let W=[],Y=Z.openCursor(IDBKeyRange.only("f"));Y.onsuccess=(X)=>{let G=X.target.result;if(G){let{primaryKey:K,value:R}=G;W.push({hash:R0(K),data:R}),G.continue()}else Promise.all(W.map(({hash:K,data:R})=>c0(K,R,this.crypto))).then(J).catch(Q)},Y.onerror=()=>Q(Y.error)})}async markApplied(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(i,"readwrite"),J=Z.objectStore(i);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=d(Y),G=J.get(X);G.onsuccess=()=>{let K=G.result;if(!K)return;let R=I$(K);J.put(_Z({...R,apld:!0}),X)},G.onerror=(K)=>{K.preventDefault()}}})}async wipe(){let V=this.db.transaction(i,"readwrite"),$=V.objectStore(i);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}class HV{seed;crypto;constructor(V,$){this.seed=V,this.crypto=$}async deriveFromKDM(V){let $=n0(this.seed,V);return await this.crypto.blake3($)}async derive(V,$=0){let Z=new TextEncoder().encode(V),J=new Uint8Array(8);new DataView(J.buffer).setBigUint64(0,BigInt($),!1);let Q=n0(Z,J);return await this.deriveFromKDM(Q)}}class z${enclave;db;constructor(V){this.db=V}async save(V){let $=Q0(V),Z=this.db.transaction(M0,"readwrite"),J=Z.objectStore(M0);return new Promise((Q,W)=>{Z.oncomplete=()=>{this.enclave=new HV(V,g0),Q(this.enclave)},Z.onerror=()=>W(Z.error),J.put($,"seed")})}async load(){if(this.enclave)return this.enclave;let $=this.db.transaction(M0,"readonly").objectStore(M0);return new Promise((Z,J)=>{let Q=$.get("seed");Q.onsuccess=()=>{let W=Q.result;if(!W)Z(void 0);else{let Y=JV(W);this.enclave=new HV(Y,g0),Z(this.enclave)}},Q.onerror=()=>J(Q.error)})}async wipe(){this.enclave=void 0;let V=this.db.transaction(M0,"readwrite"),$=V.objectStore(M0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.delete("seed")})}}class M${db;constructor(V){this.db=V}async enq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(Z0,"readwrite"),Q=J.objectStore(Z0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let G=Q0(X);Q.put({host:V,hash:G})}})}async deq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(Z0,"readwrite"),Q=J.objectStore(Z0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let G=Q0(X);Q.delete([V,G])}})}async list(V){let Z=this.db.transaction(Z0,"readonly").objectStore(Z0);return new Promise((J,Q)=>{let W=Z.getAll();W.onsuccess=()=>{let X=W.result.filter((G)=>G.host===V).map((G)=>G.hash);J(X.map((G)=>JV(G)))},W.onerror=()=>Q(W.error)})}async count(){let $=this.db.transaction(Z0,"readonly").objectStore(Z0);return new Promise((Z,J)=>{let Q=$.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(Z0,"readwrite"),$=V.objectStore(Z0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}var M0="seedMeta",t="hosts",Z0="uploadQueue",$0="downloadQueue",i="messages",OV="apld",kJ=3;class jZ{seed;hosts;uploads;downloads;messages;db;constructor(V,$){this.db=V,this.seed=new z$(V),this.hosts=new N$(V),this.uploads=new M$(V),this.downloads=new R$(V),this.messages=new w$(V,$)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function EJ(){return new Promise((V,$)=>{let Z=indexedDB.open("diplomatic-store-db",kJ);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!J.objectStoreNames.contains(M0))J.createObjectStore(M0);if(!J.objectStoreNames.contains(t))J.createObjectStore(t,{keyPath:"label"});if(!J.objectStoreNames.contains(Z0))J.createObjectStore(Z0,{keyPath:["host","hash"]});if(!J.objectStoreNames.contains($0))J.createObjectStore($0);let W;if(!J.objectStoreNames.contains(i))W=J.createObjectStore(i);else{if(!Q)throw Error("missing upgrade transaction for messages store");W=Q.objectStore(i)}if(!W.indexNames.contains(OV))W.createIndex(OV,"apld",{unique:!1})},Z.onsuccess=()=>V(Z.result),Z.onerror=()=>$(Z.error)})}async function LZ(V){let $=await EJ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new jZ($,V)}class F${client;post;whenReady;resolveReady;rejectReady;constructor(V){this.post=V,this.whenReady=new Promise(($,Z)=>{this.resolveReady=$,this.rejectReady=Z})}async init(){try{let V=await LZ(g0),$=await AZ(),Z=new UV($.apply,()=>$.clear(),(W)=>{this.post({kind:"dirty",types:Array.from(W)})}),J=Z.clear;Z.clear=async()=>{let W=await J();if(W===0)this.post({kind:"wiped"});return W};let Q=new hV(new EV,Z,V,u$,g0);this.client=Q,Q.clientState.listen(()=>{this.emitClientState()}),Q.xferState.listen(()=>{this.emitXferState()}),this.post({kind:"ready"}),this.markReady(),await this.emitClientState(),await this.emitXferState()}catch(V){let $=V instanceof Error?V:Error(String(V));throw this.failReady($),$}}markReady(){let V=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V()}failReady(V){let $=this.rejectReady;if(this.resolveReady=void 0,this.rejectReady=void 0,$)$(V)}requireClient(){if(!this.client)throw Error("WorkerRuntime not initialized");return this.client}async emitClientState(){let V=this.client;if(!V)return;let $=await V.clientState.get();this.post({kind:"clientState",state:$})}async emitXferState(){let V=this.client;if(!V)return;let $=await V.xferState.get();this.post({kind:"xferState",state:$})}hostFromSerialized(V){return{handle:new URL(V.handle),label:V.label,idx:V.idx}}async handle(V){await this.whenReady;let $=this.requireClient();switch(V.op){case"ping":return"pong";case"setSeed":{await $.setSeed(SJ(V.seed));return}case"link":{await $.link(this.hostFromSerialized(V.host),V.connect??!0);return}case"unlink":{await $.unlink(V.label);return}case"connect":{await $.connect(V.listen??!0,V.sync??!0);return}case"disconnect":{await $.disconnect();return}case"sync":return await $.sync();case"wipe":{await $.wipe();return}case"insertRaw":{let[Z,J]=await $.insertRaw(kZ(V.body));if(J!==0)throw new W0(J);return Z}case"upsertRaw":{let[Z,J]=await $.upsertRaw(d0(V.eid),V.body!==void 0?kZ(V.body):void 0,V.force);if(J!==0)throw new W0(J);return Z}case"insert":{let[Z,J]=await $.insert({type:V.params.type,body:V.params.body,gid:V.params.gid,pid:V.params.pid!==void 0?d0(V.params.pid):void 0});if(J!==0)throw new W0(J);return Z}case"upsert":{let[Z,J]=await $.upsert({type:V.params.type,body:V.params.body,eid:V.params.eid!==void 0?d0(V.params.eid):void 0,gid:V.params.gid,pid:V.params.pid!==void 0?d0(V.params.pid):void 0},V.force);if(J!==0)throw new W0(J);return Z}case"delete":{let[Z,J]=await $.delete(d0(V.eid));if(J!==0)throw new W0(J);return Z}case"import":{let Z=V.bytes.slice(),J=new Blob([Z]),Q=new File([J],"import.dip");return await $.import(Q)}case"export":{let[Z,J]=await $.exportBytes();if(J!==0)throw new W0(J);if(!Z)throw new W0(12);return Z}case"getClientState":return await $.clientState.get();case"getXferState":return await $.xferState.get();default:{let Z=V;throw Error("unknown worker command")}}}}class W0 extends Error{status;constructor(V){super(`WorkerStatusError: ${j[V]}`);this.status=V;this.name="WorkerStatusError"}}function P$(V,$){return{kind:"reply",id:V,ok:!0,result:$}}function U$(V,$){return{kind:"reply",id:V,ok:!1,status:$}}function SJ(V){if(V.length!==32)throw new W0(10);return V}function d0(V){return V}function kZ(V){return V}var T0=globalThis,EZ=new F$((V,$)=>{if($&&$.length>0)T0.postMessage(V,$);else T0.postMessage(V)});T0.onmessage=(V)=>{let $=V.data;if(!C$($))return;xJ($)};async function xJ(V){try{let $=await EZ.handle(V);if(V.op==="export"&&$ instanceof Uint8Array){let Z=$.slice();T0.postMessage(P$(V.id,Z),[Z.buffer]);return}T0.postMessage(P$(V.id,$))}catch($){if($ instanceof W0){T0.postMessage(U$(V.id,$.status));return}console.error("worker command failed",$),T0.postMessage(U$(V.id,12))}}EZ.init().catch((V)=>{console.error("worker init failed",V)});
|