@interncom/diplomatic 0.8.2 → 0.8.4

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.
@@ -1 +1 @@
1
- var M0=64;var fV=32,O0=8;var $$=32;var SV=30000,kV=512,L;((q)=>{q[q.Success=0]="Success";q[q.InvalidSignature=3]="InvalidSignature";q[q.ClockOutOfSync=4]="ClockOutOfSync";q[q.UserNotRegistered=5]="UserNotRegistered";q[q.ServerMisconfigured=6]="ServerMisconfigured";q[q.MissingBody=7]="MissingBody";q[q.ExtraBodyContent=8]="ExtraBodyContent";q[q.MissingParam=9]="MissingParam";q[q.InvalidParam=10]="InvalidParam";q[q.InvalidRequest=11]="InvalidRequest";q[q.InternalError=12]="InternalError";q[q.NotFound=13]="NotFound";q[q.InvalidMessage=14]="InvalidMessage";q[q.NoChange=15]="NoChange";q[q.DatabaseClosed=16]="DatabaseClosed";q[q.StorageError=17]="StorageError";q[q.DatabaseError=18]="DatabaseError";q[q.HashMismatch=19]="HashMismatch";q[q.DecryptionError=20]="DecryptionError";q[q.NotImplemented=21]="NotImplemented";q[q.MissingSeed=22]="MissingSeed";q[q.OutOfBounds=23]="OutOfBounds";q[q.HostError=24]="HostError";q[q.CommunicationError=25]="CommunicationError";q[q.VarLimitExceeded=26]="VarLimitExceeded";q[q.InvalidResponse=27]="InvalidResponse";q[q.ConnectionClosed=28]="ConnectionClosed"})(L||={});function BV($){if(!$||typeof $!=="object")return!1;if(!("op"in $)||!("id"in $))return!1;return typeof $.op==="string"&&typeof $.id==="number"}function mV($){let V=$.length,Z=0,J=0;while(J<V){let Q=$.charCodeAt(J++);if((Q&4294967168)===0){Z++;continue}else if((Q&4294965248)===0)Z+=2;else{if(Q>=55296&&Q<=56319){if(J<V){let Y=$.charCodeAt(J);if((Y&64512)===56320)++J,Q=((Q&1023)<<10)+(Y&1023)+65536}}if((Q&4294901760)===0)Z+=3;else Z+=4}}return Z}function rZ($,V,Z){let J=$.length,Q=Z,Y=0;while(Y<J){let X=$.charCodeAt(Y++);if((X&4294967168)===0){V[Q++]=X;continue}else if((X&4294965248)===0)V[Q++]=X>>6&31|192;else{if(X>=55296&&X<=56319){if(Y<J){let W=$.charCodeAt(Y);if((W&64512)===56320)++Y,X=((X&1023)<<10)+(W&1023)+65536}}if((X&4294901760)===0)V[Q++]=X>>12&15|224,V[Q++]=X>>6&63|128;else V[Q++]=X>>18&7|240,V[Q++]=X>>12&63|128,V[Q++]=X>>6&63|128}V[Q++]=X&63|128}}var oZ=new TextEncoder,aZ=50;function sZ($,V,Z){oZ.encodeInto($,V.subarray(Z))}function gV($,V,Z){if($.length>aZ)sZ($,V,Z);else rZ($,V,Z)}var tZ=4096;function E$($,V,Z){let J=V,Q=J+Z,Y=[],X="";while(J<Q){let W=$[J++];if((W&128)===0)Y.push(W);else if((W&224)===192){let G=$[J++]&63;Y.push((W&31)<<6|G)}else if((W&240)===224){let G=$[J++]&63,K=$[J++]&63;Y.push((W&31)<<12|G<<6|K)}else if((W&248)===240){let G=$[J++]&63,K=$[J++]&63,z=$[J++]&63,R=(W&7)<<18|G<<12|K<<6|z;if(R>65535)R-=65536,Y.push(R>>>10&1023|55296),R=56320|R&1023;Y.push(R)}else Y.push(W);if(Y.length>=tZ)X+=String.fromCharCode(...Y),Y.length=0}if(Y.length>0)X+=String.fromCharCode(...Y);return X}var eZ=new TextDecoder,$J=200;function VJ($,V,Z){let J=$.subarray(V,V+Z);return eZ.decode(J)}function vV($,V,Z){if(Z>$J)return VJ($,V,Z);else return E$($,V,Z)}class S0{type;data;constructor($,V){this.type=$,this.data=V}}class a extends Error{constructor($){super($);let V=Object.create(a.prototype);Object.setPrototypeOf(this,V),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:a.name})}}var k0=4294967295;function bV($,V,Z){let J=Z/4294967296,Q=Z;$.setUint32(V,J),$.setUint32(V+4,Q)}function V$($,V,Z){let J=Math.floor(Z/4294967296),Q=Z;$.setUint32(V,J),$.setUint32(V+4,Q)}function Z$($,V){let Z=$.getInt32(V),J=$.getUint32(V+4);return Z*4294967296+J}function yV($,V){let Z=$.getUint32(V),J=$.getUint32(V+4);return Z*4294967296+J}var ZJ=-1,JJ=4294967295,QJ=17179869183;function YJ({sec:$,nsec:V}){if($>=0&&V>=0&&$<=QJ)if(V===0&&$<=JJ){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,$),Z}else{let Z=$/4294967296,J=$&4294967295,Q=new Uint8Array(8),Y=new DataView(Q.buffer);return Y.setUint32(0,V<<2|Z&3),Y.setUint32(4,J),Q}else{let Z=new Uint8Array(12),J=new DataView(Z.buffer);return J.setUint32(0,V),V$(J,4,$),Z}}function XJ($){let V=$.getTime(),Z=Math.floor(V/1000),J=(V-Z*1000)*1e6,Q=Math.floor(J/1e9);return{sec:Z+Q,nsec:J-Q*1e9}}function WJ($){if($ instanceof Date){let V=XJ($);return YJ(V)}else return null}function GJ($){let V=new DataView($.buffer,$.byteOffset,$.byteLength);switch($.byteLength){case 4:{let Z=V.getUint32(0),J=0;return{sec:Z,nsec:0}}case 8:{let Z=V.getUint32(0),J=V.getUint32(4),Q=(Z&3)*4294967296+J,Y=Z>>>2;return{sec:Q,nsec:Y}}case 12:{let Z=Z$(V,4),J=V.getUint32(0);return{sec:Z,nsec:J}}default:throw new a(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${$.length}`)}}function KJ($){let V=GJ($);return new Date(V.sec*1000+V.nsec/1e6)}var iV={type:ZJ,encode:WJ,decode:KJ};class B0{static defaultCodec=new B0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(iV)}register({type:$,encode:V,decode:Z}){if($>=0)this.encoders[$]=V,this.decoders[$]=Z;else{let J=-1-$;this.builtInEncoders[J]=V,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 Y=-1-Z;return new S0(Y,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 S0(Z,Q)}}if($ instanceof S0)return $;return null}decode($,V,Z){let J=V<0?this.builtInDecoders[-1-V]:this.decoders[V];if(J)return J($,V,Z);else return new S0(V,$)}}function zJ($){return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer}function h0($){if($ instanceof Uint8Array)return $;else if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);else if(zJ($))return new Uint8Array($);else return Uint8Array.from($)}var NJ=100,RJ=2048;class J${extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??B0.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.maxDepth=$?.maxDepth??NJ,this.initialBufferSize=$?.initialBufferSize??RJ,this.sortKeys=$?.sortKeys??!1,this.forceFloat32=$?.forceFloat32??!1,this.ignoreUndefined=$?.ignoreUndefined??!1,this.forceIntegerToFloat=$?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new J$({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($){if(this.entered)return this.clone().encodeSharedRef($);try{return this.entered=!0,this.reinitializeState(),this.doEncode($,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode($){if(this.entered)return this.clone().encode($);try{return this.entered=!0,this.reinitializeState(),this.doEncode($,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode($,V){if(V>this.maxDepth)throw Error(`Too deep objects in depth ${V}`);if($==null)this.encodeNil();else if(typeof $==="boolean")this.encodeBoolean($);else if(typeof $==="number")if(!this.forceIntegerToFloat)this.encodeNumber($);else this.encodeNumberAsFloat($);else if(typeof $==="string")this.encodeString($);else if(this.useBigInt64&&typeof $==="bigint")this.encodeBigInt64($);else this.encodeObject($,V)}ensureBufferSizeToWrite($){let V=this.pos+$;if(this.view.byteLength<V)this.resizeBuffer(V*2)}resizeBuffer($){let V=new ArrayBuffer($),Z=new Uint8Array(V),J=new DataView(V);Z.set(this.bytes),this.view=J,this.bytes=Z}encodeNil(){this.writeU8(192)}encodeBoolean($){if($===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber($){if(!this.forceIntegerToFloat&&Number.isSafeInteger($))if($>=0)if($<128)this.writeU8($);else if($<256)this.writeU8(204),this.writeU8($);else if($<65536)this.writeU8(205),this.writeU16($);else if($<4294967296)this.writeU8(206),this.writeU32($);else if(!this.useBigInt64)this.writeU8(207),this.writeU64($);else this.encodeNumberAsFloat($);else if($>=-32)this.writeU8(224|$+32);else if($>=-128)this.writeU8(208),this.writeI8($);else if($>=-32768)this.writeU8(209),this.writeI16($);else if($>=-2147483648)this.writeU8(210),this.writeI32($);else if(!this.useBigInt64)this.writeU8(211),this.writeI64($);else this.encodeNumberAsFloat($);else this.encodeNumberAsFloat($)}encodeNumberAsFloat($){if(this.forceFloat32)this.writeU8(202),this.writeF32($);else this.writeU8(203),this.writeF64($)}encodeBigInt64($){if($>=BigInt(0))this.writeU8(207),this.writeBigUint64($);else this.writeU8(211),this.writeBigInt64($)}writeStringHeader($){if($<32)this.writeU8(160+$);else if($<256)this.writeU8(217),this.writeU8($);else if($<65536)this.writeU8(218),this.writeU16($);else if($<4294967296)this.writeU8(219),this.writeU32($);else throw Error(`Too long string: ${$} bytes in UTF-8`)}encodeString($){let Z=mV($);this.ensureBufferSizeToWrite(5+Z),this.writeStringHeader(Z),gV($,this.bytes,this.pos),this.pos+=Z}encodeObject($,V){let Z=this.extensionCodec.tryToEncode($,this.context);if(Z!=null)this.encodeExtension(Z);else if(Array.isArray($))this.encodeArray($,V);else if(ArrayBuffer.isView($))this.encodeBinary($);else if(typeof $==="object")this.encodeMap($,V);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply($)}`)}encodeBinary($){let V=$.byteLength;if(V<256)this.writeU8(196),this.writeU8(V);else if(V<65536)this.writeU8(197),this.writeU16(V);else if(V<4294967296)this.writeU8(198),this.writeU32(V);else throw Error(`Too large binary: ${V}`);let Z=h0($);this.writeU8a(Z)}encodeArray($,V){let Z=$.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 $)this.doEncode(J,V+1)}countWithoutUndefined($,V){let Z=0;for(let J of V)if($[J]!==void 0)Z++;return Z}encodeMap($,V){let Z=Object.keys($);if(this.sortKeys)Z.sort();let J=this.ignoreUndefined?this.countWithoutUndefined($,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 Y=$[Q];if(!(this.ignoreUndefined&&Y===void 0))this.encodeString(Q),this.doEncode(Y,V+1)}}encodeExtension($){if(typeof $.data==="function"){let Z=$.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($.type),this.writeU8a(Z);return}let V=$.data.length;if(V===1)this.writeU8(212);else if(V===2)this.writeU8(213);else if(V===4)this.writeU8(214);else if(V===8)this.writeU8(215);else if(V===16)this.writeU8(216);else if(V<256)this.writeU8(199),this.writeU8(V);else if(V<65536)this.writeU8(200),this.writeU16(V);else if(V<4294967296)this.writeU8(201),this.writeU32(V);else throw Error(`Too large extension object: ${V}`);this.writeI8($.type),this.writeU8a($.data)}writeU8($){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,$),this.pos++}writeU8a($){let V=$.length;this.ensureBufferSizeToWrite(V),this.bytes.set($,this.pos),this.pos+=V}writeI8($){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,$),this.pos++}writeU16($){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,$),this.pos+=2}writeI16($){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,$),this.pos+=2}writeU32($){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,$),this.pos+=4}writeI32($){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,$),this.pos+=4}writeF32($){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,$),this.pos+=4}writeF64($){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,$),this.pos+=8}writeU64($){this.ensureBufferSizeToWrite(8),bV(this.view,this.pos,$),this.pos+=8}writeI64($){this.ensureBufferSizeToWrite(8),V$(this.view,this.pos,$),this.pos+=8}writeBigUint64($){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,$),this.pos+=8}writeBigInt64($){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,$),this.pos+=8}}function P0($,V){return new J$(V).encodeSharedRef($)}function Q$($){return`${$<0?"-":""}0x${Math.abs($).toString(16).padStart(2,"0")}`}var FJ=16,IJ=16;class f${hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor($=FJ,V=IJ){this.maxKeyLength=$,this.maxLengthPerKey=V,this.caches=[];for(let Z=0;Z<this.maxKeyLength;Z++)this.caches.push([])}canBeCached($){return $>0&&$<=this.maxKeyLength}find($,V,Z){let J=this.caches[Z-1];$:for(let Q of J){let Y=Q.bytes;for(let X=0;X<Z;X++)if(Y[X]!==$[V+X])continue $;return Q.str}return null}store($,V){let Z=this.caches[$.length-1],J={bytes:$,str:V};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=E$($,V,Z),Y=Uint8Array.prototype.slice.call($,V,V+Z);return this.store(Y,Q),Q}}var S$="array",n0="map_key",lV="map_value",UJ=($)=>{if(typeof $==="string"||typeof $==="number")return $;throw new a("The type of key must be string or number but "+typeof $)};class hV{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState($){let V=this.getUninitializedStateFromPool();V.type=S$,V.position=0,V.size=$,V.array=Array($)}pushMapState($){let V=this.getUninitializedStateFromPool();V.type=n0,V.readCount=0,V.size=$,V.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let $={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push($)}return this.stack[this.stackHeadPosition]}release($){if(this.stack[this.stackHeadPosition]!==$)throw Error("Invalid stack state. Released state is not on top of the stack.");if($.type===S$){let Z=$;Z.size=0,Z.array=void 0,Z.position=0,Z.type=void 0}if($.type===n0||$.type===lV){let Z=$;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 p0=-1,k$=new DataView(new ArrayBuffer(0)),wJ=new Uint8Array(k$.buffer);try{k$.getInt8(0)}catch($){if(!($ 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 uV=RangeError("Insufficient data"),MJ=new f$;class Y${extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=k$;bytes=wJ;headByte=p0;stack=new hV;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??B0.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.rawStrings=$?.rawStrings??!1,this.maxStrLength=$?.maxStrLength??k0,this.maxBinLength=$?.maxBinLength??k0,this.maxArrayLength=$?.maxArrayLength??k0,this.maxMapLength=$?.maxMapLength??k0,this.maxExtLength=$?.maxExtLength??k0,this.keyDecoder=$?.keyDecoder!==void 0?$.keyDecoder:MJ,this.mapKeyConverter=$?.mapKeyConverter??UJ}clone(){return new Y$({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=p0,this.stack.reset()}setBuffer($){let V=h0($);this.bytes=V,this.view=new DataView(V.buffer,V.byteOffset,V.byteLength),this.pos=0}appendBuffer($){if(this.headByte===p0&&!this.hasRemaining(1))this.setBuffer($);else{let V=this.bytes.subarray(this.pos),Z=h0($),J=new Uint8Array(V.length+Z.length);J.set(V),J.set(Z,V.length),this.setBuffer(J)}}hasRemaining($){return this.view.byteLength-this.pos>=$}createExtraByteError($){let{view:V,pos:Z}=this;return RangeError(`Extra ${V.byteLength-Z} of ${V.byteLength} byte(s) found at buffer[${$}]`)}decode($){if(this.entered)return this.clone().decode($);try{this.entered=!0,this.reinitializeState(),this.setBuffer($);let V=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return V}finally{this.entered=!1}}*decodeMulti($){if(this.entered){yield*this.clone().decodeMulti($);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer($);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync($){if(this.entered)return this.clone().decodeAsync($);try{this.entered=!0;let V=!1,Z;for await(let X of $){if(V)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(X);try{Z=this.doDecodeSync(),V=!0}catch(W){if(!(W instanceof RangeError))throw W}this.totalPos+=this.pos}if(V){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Z}let{headByte:J,pos:Q,totalPos:Y}=this;throw RangeError(`Insufficient data in parsing ${Q$(J)} at ${Y} (${Q} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream($){return this.decodeMultiAsync($,!0)}decodeStream($){return this.decodeMultiAsync($,!1)}async*decodeMultiAsync($,V){if(this.entered){yield*this.clone().decodeMultiAsync($,V);return}try{this.entered=!0;let Z=V,J=-1;for await(let Q of $){if(V&&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(Y){if(!(Y instanceof RangeError))throw Y}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){$:while(!0){let $=this.readHeadByte(),V;if($>=224)V=$-256;else if($<192)if($<128)V=$;else if($<144){let J=$-128;if(J!==0){this.pushMapState(J),this.complete();continue $}else V={}}else if($<160){let J=$-144;if(J!==0){this.pushArrayState(J),this.complete();continue $}else V=[]}else{let J=$-160;V=this.decodeString(J,0)}else if($===192)V=null;else if($===194)V=!1;else if($===195)V=!0;else if($===202)V=this.readF32();else if($===203)V=this.readF64();else if($===204)V=this.readU8();else if($===205)V=this.readU16();else if($===206)V=this.readU32();else if($===207)if(this.useBigInt64)V=this.readU64AsBigInt();else V=this.readU64();else if($===208)V=this.readI8();else if($===209)V=this.readI16();else if($===210)V=this.readI32();else if($===211)if(this.useBigInt64)V=this.readI64AsBigInt();else V=this.readI64();else if($===217){let J=this.lookU8();V=this.decodeString(J,1)}else if($===218){let J=this.lookU16();V=this.decodeString(J,2)}else if($===219){let J=this.lookU32();V=this.decodeString(J,4)}else if($===220){let J=this.readU16();if(J!==0){this.pushArrayState(J),this.complete();continue $}else V=[]}else if($===221){let J=this.readU32();if(J!==0){this.pushArrayState(J),this.complete();continue $}else V=[]}else if($===222){let J=this.readU16();if(J!==0){this.pushMapState(J),this.complete();continue $}else V={}}else if($===223){let J=this.readU32();if(J!==0){this.pushMapState(J),this.complete();continue $}else V={}}else if($===196){let J=this.lookU8();V=this.decodeBinary(J,1)}else if($===197){let J=this.lookU16();V=this.decodeBinary(J,2)}else if($===198){let J=this.lookU32();V=this.decodeBinary(J,4)}else if($===212)V=this.decodeExtension(1,0);else if($===213)V=this.decodeExtension(2,0);else if($===214)V=this.decodeExtension(4,0);else if($===215)V=this.decodeExtension(8,0);else if($===216)V=this.decodeExtension(16,0);else if($===199){let J=this.lookU8();V=this.decodeExtension(J,1)}else if($===200){let J=this.lookU16();V=this.decodeExtension(J,2)}else if($===201){let J=this.lookU32();V=this.decodeExtension(J,4)}else throw new a(`Unrecognized type byte: ${Q$($)}`);this.complete();let Z=this.stack;while(Z.length>0){let J=Z.top();if(J.type===S$)if(J.array[J.position]=V,J.position++,J.position===J.size)V=J.array,Z.release(J);else continue $;else if(J.type===n0){if(V==="__proto__")throw new a("The key __proto__ is not allowed");J.key=this.mapKeyConverter(V),J.type=lV;continue $}else if(J.map[J.key]=V,J.readCount++,J.readCount===J.size)V=J.map,Z.release(J);else{J.key=null,J.type=n0;continue $}}return V}}readHeadByte(){if(this.headByte===p0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=p0}readArraySize(){let $=this.readHeadByte();switch($){case 220:return this.readU16();case 221:return this.readU32();default:if($<160)return $-144;else throw new a(`Unrecognized array type byte: ${Q$($)}`)}}pushMapState($){if($>this.maxMapLength)throw new a(`Max length exceeded: map length (${$}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState($)}pushArrayState($){if($>this.maxArrayLength)throw new a(`Max length exceeded: array length (${$}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState($)}decodeString($,V){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String($,V);return this.decodeBinary($,V)}decodeUtf8String($,V){if($>this.maxStrLength)throw new a(`Max length exceeded: UTF-8 byte length (${$}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+V+$)throw uV;let Z=this.pos+V,J;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached($))J=this.keyDecoder.decode(this.bytes,Z,$);else J=vV(this.bytes,Z,$);return this.pos+=V+$,J}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===n0;return!1}decodeBinary($,V){if($>this.maxBinLength)throw new a(`Max length exceeded: bin length (${$}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining($+V))throw uV;let Z=this.pos+V,J=this.bytes.subarray(Z,Z+$);return this.pos+=V+$,J}decodeExtension($,V){if($>this.maxExtLength)throw new a(`Max length exceeded: ext length (${$}) > maxExtLength (${this.maxExtLength})`);let Z=this.view.getInt8(this.pos+V),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 $=this.view.getUint8(this.pos);return this.pos++,$}readI8(){let $=this.view.getInt8(this.pos);return this.pos++,$}readU16(){let $=this.view.getUint16(this.pos);return this.pos+=2,$}readI16(){let $=this.view.getInt16(this.pos);return this.pos+=2,$}readU32(){let $=this.view.getUint32(this.pos);return this.pos+=4,$}readI32(){let $=this.view.getInt32(this.pos);return this.pos+=4,$}readU64(){let $=yV(this.view,this.pos);return this.pos+=8,$}readI64(){let $=Z$(this.view,this.pos);return this.pos+=8,$}readU64AsBigInt(){let $=this.view.getBigUint64(this.pos);return this.pos+=8,$}readI64AsBigInt(){let $=this.view.getBigInt64(this.pos);return this.pos+=8,$}readF32(){let $=this.view.getFloat32(this.pos);return this.pos+=4,$}readF64(){let $=this.view.getFloat64(this.pos);return this.pos+=8,$}}function B$($,V){return new Y$(V).decode($)}class c0{listeners=new Map;addEventListener($,V){let Z=this.listeners.get($);if(!Z)Z=new Set,this.listeners.set($,Z);return Z.add(V),()=>{this.removeEventListener($,V)}}removeEventListener($,V){let Z=this.listeners.get($);if(Z){if(Z.delete(V),Z.size===0)this.listeners.delete($)}}emit($,V){let Z=this.listeners.get($);if(Z){let J=Array.from(Z);for(let Q of J)Q(V)}}emitAll($){let V=Array.from(this.listeners.keys());for(let Z of V)this.emit(Z,$)}}class C0{getter;static eventName="update";emitter;constructor($){this.getter=$;this.emitter=new c0}get=()=>this.getter();async emit(){let $=await this.getter();queueMicrotask(()=>this.emitter.emit(C0.eventName,$))}listen($){return this.emitter.addEventListener(C0.eventName,$),()=>{this.emitter.removeEventListener(C0.eventName,$)}}}function M($){return[$,0]}function N($){return[void 0,$]}function OJ($){if($<0)console.info("N",$),console.trace();if(typeof $!=="bigint")$=BigInt($);if($<0n)return N(10);let V=[];while($>0n){let Z=Number($&0x7fn);if($>>=7n,$>0n)V.push(Z|128);else V.push(Z)}if(V.length===0)return M(new Uint8Array([0]));if(V.length>8)return N(26);return M(new Uint8Array(V))}function HJ($,V=0){let Z=0n,J=0,Q=V;while(!0){if(Q>=$.length)return N(14);let Y=$[Q++];if(Y===void 0)return N(14);if(Z|=BigInt(Y&127)<<BigInt(J),(Y&128)===0){if(Q-V>8)return N(26);return M({value:Z>0x1fffffffffffffn?Z:Number(Z),bytesRead:Q-V})}if(J+=7,J>=56)return N(26)}}class v{data;pos=0;constructor($){this.data=$}static async fromResponse($){let V=await $.arrayBuffer(),Z=new Uint8Array(V);return new v(Z)}readBigInt(){if(this.pos+8>this.data.length)return N(7);let $=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,M($)}readDate(){let[$,V]=this.readVarInt();if(V!==0)return N(V);return M(new Date($))}readVarInt(){let[$,V]=HJ(this.data,this.pos);if(V!==0)return N(V);this.pos+=$.bytesRead;let Z=$.value;return M(typeof Z==="bigint"?Number(Z):Z)}readVarString(){let[$,V]=this.readVarInt();if(V!==0)return N(V);let[Z,J]=this.readBytes($);if(J!==0)return N(J);let Q=new TextDecoder().decode(Z);return M(Q)}readBytes($){if($<0)return N(10);if(this.pos+$>this.data.length)return N(23);let V=this.data.slice(this.pos,this.pos+$);return this.pos+=$,M(V)}readVarBytes(){let[$,V]=this.readVarInt();if(V!==0)return N(V);return this.readBytes($)}readStruct($){return $.decode(this)}readStructs($){let V=[];while(!this.done()){let[Z,J]=this.readStruct($);if(J!==0)return N(J);V.push(Z)}return M(V)}readBytesSeq($){let V=[];while(!this.done()){let[Z,J]=this.readBytes($);if(J!==0)return N(J);V.push(Z)}return M(V)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class b{parts=[];writeBigInt($){let V=new Uint8Array(8);new DataView(V.buffer).setBigUint64(0,$,!1),this.parts.push(V)}writeDate($){let V=$.getTime();return this.writeVarInt(V)}writeVarInt($){let[V,Z]=OJ($);if(Z!==0)return Z;return this.parts.push(V),0}writeVarString($){let V=new TextEncoder().encode($),Z=this.writeVarInt(V.length);if(Z!==0)return Z;return this.writeBytes(V),0}prependBytes($){this.parts.unshift($)}writeBytes($){this.parts.push($)}writeVarBytes($){let V=this.writeVarInt($.length);if(V!==0)return V;return this.writeBytes($),0}writeStruct($,V){return $.encode(this,V)}writeStructs($,V){for(let Z of V){let J=this.writeStruct($,Z);if(J!==0)return J}return 0}writeBytesSeq($){for(let V of $)this.writeBytes(V)}result(){let $=this.parts.reduce((J,Q)=>J+Q.length,0),V=new Uint8Array($),Z=0;for(let J of this.parts)V.set(J,Z),Z+=J.length;return V}*scan(){for(let $ of this.parts)yield $}}async function m$($,V){let Z=new b,J=Z.writeDate(V);if(J!==0)return N(J);let Q=Z.result(),Y=await $.sign(Q);return M({pubKey:$.publicKey,sig:Y,timestamp:V})}async function H0($,V,Z){let J=Z.now().getTime(),Q=$.timestamp.getTime();if(Math.abs(J-Q)>SV)return 4;let X=new b;X.writeDate($.timestamp);let W=X.result();if(!await V.checkSigEd25519($.sig,W,$.pubKey))return 3;return 0}var $0={encode($,V){let Z=$.writeVarBytes(V.id);if(Z!==0)return Z;let J=$.writeDate(V.ts);if(J!==0)return J;return 0},decode($){let[V,Z]=$.readVarBytes();if(Z!==0)return N(Z);let[J,Q]=$.readDate();if(Q!==0)return N(Q);return M({id:V,ts:J})}};function X$($){let V=new b,Z=V.writeStruct($0,$);if(Z!==0)return N(Z);let J=V.result();return M(J)}var J0={encode($,V){let Z=$.writeVarBytes(V.eid);if(Z!==0)return Z;let J=$.writeVarInt(V.off);if(J!==0)return J;let Q=$.writeVarInt(V.ctr);if(Q!==0)return Q;let Y=$.writeVarInt(V.len);if(Y!==0)return Y;if(V.hsh)$.writeBytes(V.hsh);return 0},decode($){let[V,Z]=$.readVarBytes();if(Z!==0)return N(Z);let J=new v(V),[,Q]=$0.decode(J);if(Q!==0)return N(Q);let[Y,X]=$.readVarInt();if(X!==0)return N(X);let[W,G]=$.readVarInt();if(G!==0)return N(G);let[K,z]=$.readVarInt();if(z!==0)return N(z);let R;if(K>0){let[F,U]=$.readBytes($$);if(U!==0)return N(U);R=F}return M({eid:V,off:Y,ctr:W,len:K,hsh:R})}};function X0($){return Array.from($).map((Z)=>Z.toString(16).padStart(2,"0")).join("")}function W$($){if($.length%2!==0)throw Error("Invalid hex string");let V=new Uint8Array($.length/2);for(let Z=0;Z<$.length;Z+=2)V[Z/2]=Number.parseInt($.substr(Z,2),16);return V}function V0($,V){if($===V)return!0;if($.byteLength!==V.byteLength)return!1;return $.every((Z,J)=>Z===V[J])}var k;if(typeof Uint8Array.prototype.toBase64==="function")k=($)=>$.toBase64();else k=($)=>btoa(String.fromCharCode(...$));var N0;if(typeof Uint8Array.fromBase64==="function")N0=($)=>Uint8Array.fromBase64($);else N0=($)=>Uint8Array.from(atob($),(V)=>V.charCodeAt(0));function G$($,V){let Z=new Uint8Array($.length+V.length);return Z.set($,0),Z.set(V,$.length),Z}function pV($,V,Z){return Z.checkSigEd25519($.sig,$.headCph,V)}async function nV($,V,Z,J){let Q;if($.bod&&$.len>0)Q=await Z.blake3($.bod);let Y=new b,X=J0.encode(Y,{...$,hsh:Q});if(X!==0)return N(X);let W=Y.result(),G=await V.kdmFor(W),K=J.deriveCipher(G,"encrypt"),z=await K.encrypt(W),R=$.bod?await K.encrypt($.bod):new Uint8Array(0),F=await V.sign(z);return M({sig:F,kdm:G,headCph:z,bodyCph:R})}async function g$($,V,Z,J,Q){let Y=new v($),[X,W]=J0.decode(Y);if(W!==0)return N(14);let G;try{G=V&&V.length>0?await Z.decrypt(V):void 0}catch{return N(20)}let K=X.hsh&&G===void 0,z=X.hsh===void 0&&G!==void 0;if(K||z)return N(19);if(X.hsh&&G){let F=await J.blake3(G);if(!V0(F,X.hsh))return N(19)}let R=Q??await J.blake3($);return M({msgHead:X,bod:G,headHash:R})}class v${now(){return new Date}}function cV($,V,Z,J){let Q=V.getTime()-$.getTime(),Y=Z.getTime()-J.getTime();return(Q+Y)/2}var d0={encode($,V){if($.writeVarInt(V.quota),V.quota>0){if(V.usage===void 0)return 9;$.writeVarInt(V.usage)}return 0},decode($){let[V,Z]=$.readVarInt();if(Z!==0)return N(Z);let J;if(V>0){let[Q,Y]=$.readVarInt();if(Y!==0)return N(Y);J=Q}return M({quota:V,usage:J})}};var b$={encode($,V){$.writeBytes(new Uint8Array([V.status]));let Z=$.writeDate(V.timeRcvd);if(Z!==0)return Z;let J=$.writeDate(V.timeSent);if(J!==0)return J;let Q=$.writeVarInt(V.subscription.term);if(Q!==0)return Q;let Y=$.writeVarInt(V.subscription.elapsed);if(Y!==0)return Y;let X=$.writeStruct(d0,V.subscription.stat);if(X!==0)return X;let W=$.writeStruct(d0,V.subscription.dyn);if(W!==0)return W;return 0},decode($){let[V,Z]=$.readBytes(1);if(Z!==0)return N(Z);let J=V[0],[Q,Y]=$.readDate();if(Y!==0)return N(Y);let[X,W]=$.readDate();if(W!==0)return N(W);let[G,K]=$.readVarInt();if(K!==0)return N(K);let[z,R]=$.readVarInt();if(R!==0)return N(R);let[F,U]=$.readStruct(d0);if(U!==0)return N(U);let[w,I]=$.readStruct(d0);if(I!==0)return N(I);return M({status:J,timeRcvd:Q,timeSent:X,subscription:{term:G,elapsed:z,stat:F,dyn:w}})}};var y$={encode($,V){let Z=$.writeVarBytes(V.headCph);if(Z!==0)return Z;let J=$.writeVarInt(V.seq);if(J!==0)return J;return 0},decode($){let[V,Z]=$.readVarBytes();if(Z!==0)return N(Z);let[J,Q]=$.readVarInt();if(Q!==0)return N(Q);return M({headCph:V,seq:J})}};var Z0={encode($,V){$.writeBytes(V.pubKey),$.writeBytes(V.sig);let Z=$.writeDate(V.timestamp);if(Z!==0)return Z;return 0},decode($){let[V,Z]=$.readBytes(fV);if(Z!==0)return N(Z);let[J,Q]=$.readBytes(M0);if(Q!==0)return N(Q);let[Y,X]=$.readDate();if(X!==0)return N(X);return M({pubKey:V,sig:J,timestamp:Y})}};var dV={async encodeReq($,V,Z,J,Q){let Y=Q.writeStruct(Z0,Z);if(Y!==0)return Y;for(let X of J)Q.writeVarInt(X);return 0},async handleReq($,V,Z){let{clock:J,crypto:Q,storage:Y}=$,[X,W]=V.readStruct(Z0);if(W!==0)return W;let G=await H0(X,Q,J);if(G!==0)return G;let{pubKey:K}=X,[z,R]=await Y.hasUser(K);if(R!==0)return R;if(!z)return 5;let[F,U]=V.readVarInt();if(U!==0)return U;if(!V.done())return 8;let[w,I]=await Y.listHeads(K,F);if(I!==0)return I;return Z.writeStructs(y$,w)},decodeResp($){return $.readStructs(y$)}};var i$={encode($,V){$.writeVarInt(V.seq);let Z=$.writeVarBytes(V.bodyCph);if(Z!==0)return Z;return 0},decode($){let[V,Z]=$.readVarInt();if(Z!==0)return N(Z);let[J,Q]=$.readVarBytes();if(Q!==0)return N(Q);return M({seq:V,bodyCph:J})}};var rV={async encodeReq($,V,Z,J,Q){let Y=Q.writeStruct(Z0,Z);if(Y!==0)return Y;for(let X of J){let W=Q.writeVarInt(X);if(W!==0)return W}return 0},async handleReq($,V,Z){let{clock:J,crypto:Q,storage:Y}=$,[X,W]=V.readStruct(Z0);if(W!==0)return W;let G=await H0(X,Q,J);if(G!==0)return G;let{pubKey:K}=X,[z,R]=await Y.hasUser(K);if(R!==0)return R;if(!z)return 5;let F=[];while(!V.done()){let[I,O]=V.readVarInt();if(O!==0)return O;F.push(I)}console.info(`PULL: ${F.length} bags`);let[U,w]=await Y.getBodies(K,F);if(w!==0)return w;if(!U)return 17;for(let{seq:I,bodyCph:O}of U){let P={seq:I,bodyCph:O},C=Z.writeStruct(i$,P);if(C!==0)return C}return 0},decodeResp($){return $.readStructs(i$)}};var u$={encode($,V){$.writeBytes(V.sig),$.writeBytes(V.kdm);let Z=$.writeVarBytes(V.headCph);if(Z!==0)return Z;let J=$.writeVarBytes(V.bodyCph);if(J!==0)return J;return 0},decode($){let[V,Z]=$.readBytes(M0);if(Z!==0)return N(Z);let[J,Q]=$.readBytes(O0);if(Q!==0)return N(Q);let[Y,X]=$.readVarBytes();if(X!==0)return N(X);let[W,G]=$.readVarBytes();if(G!==0)return N(G);return M({sig:V,kdm:J,headCph:Y,bodyCph:W})}};var K$={encode($,V){let Z=$.writeVarInt(V.seq);if(Z!==0)return Z;let J=$.writeVarBytes(V.headCph);if(J!==0)return J;let Q=V.bodyCph?V.bodyCph.length:0,Y=$.writeVarInt(Q);if(Y!==0)return Y;if(Q>0){if(!V.bodyCph)return 10;$.writeBytes(V.bodyCph)}return 0},decode($){let[V,Z]=$.readVarInt();if(Z!==0)return N(Z);let[J,Q]=$.readVarBytes();if(Q!==0)return N(Q);let[Y,X]=$.readVarInt();if(X!==0)return N(X);let W;if(Y>0){let[G,K]=$.readBytes(Y);if(K!==0)return N(K);W=G}return M({seq:V,headCph:J,bodyCph:W})}};var z$={encode($,V){$.writeBytes(V.sig),$.writeBytes(V.kdm);let Z=$.writeVarBytes(V.headCph);if(Z!==0)return Z;return 0},decode($){let[V,Z]=$.readBytes(M0);if(Z!==0)return N(Z);let[J,Q]=$.readBytes(O0);if(Q!==0)return N(Q);let[Y,X]=$.readVarBytes();if(X!==0)return N(X);return M({sig:V,kdm:J,headCph:Y})}};var N$={encode($,V){if($.writeVarInt(V.idx),$.writeBytes(new Uint8Array([V.status])),V.status===0)$.writeVarInt(V.seq);return 0},decode($){let[V,Z]=$.readVarInt();if(Z!==0)return N(Z);let[J,Q]=$.readBytes(1);if(Q!==0)return N(Q);let Y=J[0];if(Y!==0)return M({idx:V,status:Y});let[X,W]=$.readVarInt();if(W!==0)return N(W);return M({idx:V,status:Y,seq:X})}};var oV={async encodeReq($,V,Z,J,Q){let Y=Q.writeStruct(Z0,Z);if(Y!==0)return Y;let X=Q.writeStructs(u$,J);if(X!==0)return X;return 0},async handleReq($,V,Z){let{clock:J,crypto:Q,storage:Y,notifier:X}=$,[W,G]=V.readStruct(Z0);if(G!==0)return G;let K=await H0(W,Q,J);if(K!==0)return K;let{pubKey:z}=W,[R,F]=await Y.hasUser(z);if(F!==0)return F;if(!R)return 5;let[U,w]=V.readStructs(u$);if(w!==0)return w;console.info(`PUSH: ${U.length} bags`);let I=[],O=[];for(let H=0;H<U.length;H++){let _=U[H];if(!await pV(_,z,Q)){let x={idx:H,status:3},E=Z.writeStruct(N$,x);if(E!==0)return E;continue}I.push(H),O.push(_)}let[P,C]=await Y.setBags(z,O);if(C!==0)return C;if(!P||P.length!==O.length)return 17;let A=[];for(let H=0;H<O.length;H++){let _=O[H],D=I[H],x=P[H],E=new b,f=E.writeStruct(z$,_);if(f!==0)return f;let m=E.result(),q={seq:x,headCph:m};if(U.length===1&&_.bodyCph.length<=kV)q.bodyCph=_.bodyCph;A.push(q);let y={idx:D,status:0,seq:x},l=Z.writeStruct(N$,y);if(l!==0)return l}if(A.length>0){let H=new b,_=H.writeStructs(K$,A);if(_!==0)return _;let D=H.result();await Promise.resolve(X.push(z,D))}return 0},decodeResp($){return $.readStructs(N$)}};var aV={async encodeReq($,V,Z,J,Q){return Q.writeStruct(Z0,Z)},async handleReq($,V,Z){let{clock:J,crypto:Q,storage:Y}=$,[X,W]=V.readStruct(Z0);if(W!==0)return W;let G=await H0(X,Q,J);if(G!==0)return G;let{pubKey:K}=X;if(!V.done())return 8;let[z,R]=await Y.addUser(K);if(R!==0)return R;return 0},decodeResp($){return M(void 0)}};class l${url;websocket;constructor($){this.url=$}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 Y=new b;Y.writeStruct(Z0,$);let X=Y.result(),W=X0(X);return Q.searchParams.set("t",W),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);V(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 d={user:{path:"/user",endpoint:aV,name:0},push:{path:"/push",endpoint:oV,name:2},peek:{path:"/peek",endpoint:dV,name:1},pull:{path:"/pull",endpoint:rV,name:3}},qJ={0:d.user,2:d.push,1:d.peek,3:d.pull},RW={[d.user.path]:d.user,[d.push.path]:d.push,[d.peek.path]:d.peek,[d.pull.path]:d.pull};class sV{url;listener;constructor($){this.url=$;this.listener=new l$($)}async call($,V){let{path:Z}=qJ[$],J=new URL(Z,this.url);try{return await PJ(J,V)}catch{return N(25)}}}var tV=($)=>{return new sV($.handle)};async function PJ($,V){let Z=await fetch($,{method:"POST",body:V.result().slice()});if(!Z.ok)return N(24);let J=await v.fromResponse(Z);return M(J)}class R${enclave;crypto;host;clock;transport;updateHostMeta;constructor($,V,Z,J,Q,Y){this.enclave=$;this.crypto=V;this.host=Z;this.clock=J;this.transport=Q;this.updateHostMeta=Y}async call($,V){let{clock:Z,transport:J}=this,{endpoint:Q,name:Y}=$,X=await this.identity(),W=Z.now(),[G,K]=await m$(X,W);if(K!==0)return N(K);let z=new b,R=await Q.encodeReq(this,X,G,V,z);if(R!==0)return N(R);let F=Z.now(),[U,w]=await J.call(Y,z),I=Z.now();if(w!==0)return N(w);let[O,P]=U.readStruct(b$);if(P!==0)return N(P);if(O.status!==0)return N(O.status);let A={clockOffset:cV(F,O.timeRcvd,O.timeSent,I),subscription:O.subscription},H=await this.updateHostMeta(A);if(H!==0)return N(H);return Q.decodeResp(U)}identity=()=>{let{host:$,enclave:V}=this;return V.deriveIdentity($.label,$.idx??0)};seal=async($)=>{let{crypto:V,enclave:Z}=this,J=await this.identity();return nV($,J,V,Z)};register=()=>this.call(d.user,[]);peek=($)=>this.call(d.peek,[$]);push=($)=>this.call(d.push,$);pull=($)=>this.call(d.pull,$);listen=async($,V,Z)=>{let{clock:J,transport:Q}=this,{listener:Y}=Q,X=await this.identity(),W=J.now(),[G,K]=await m$(X,W);if(K!==0)return K;return await Y.connect(G,$,V,Z)};isConnected(){let $=this.transport?.listener;if($&&typeof $.connected==="function")return $.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var h$={encode($,V){let Z=$.writeVarString(V.lbl);if(Z!==0)return Z;let J=$.writeVarInt(V.idx);if(J!==0)return J;let Q=$.writeVarInt(V.num);if(Q!==0)return Q;return $.writeBytes(V.hsh),$.writeBytes(V.sig),0},decode($){let[V,Z]=$.readVarString();if(Z!==0)return N(Z);let[J,Q]=$.readVarInt();if(Q!==0)return N(Q);let[Y,X]=$.readVarInt();if(X!==0)return N(X);let[W,G]=$.readBytes($$);if(G!==0)return N(G);let[K,z]=$.readBytes(M0);if(z!==0)return N(z);return M({lbl:V,idx:J,num:Y,hsh:W,sig:K})}};var p$={encode($,V){let Z=$.writeStruct(h$,V.head);if(Z!==0)return Z;let J=$.writeVarBytes(V.indexEnc);if(J!==0)return J;let Q=$.writeVarBytes(V.bodyEnc);if(Q!==0)return Q;return 0},decode($){let[V,Z]=$.readStruct(h$);if(Z!==0)return N(Z);let[J,Q]=$.readVarBytes();if(Q!==0)return N(Q);let[Y,X]=$.readVarBytes();if(X!==0)return N(X);return M({head:V,indexEnc:J,bodyEnc:Y})}};var n$={encode($,V){$.writeBytes(V.kdm);let Z=$.writeVarBytes(V.headCph);if(Z!==0)return Z;let J=$.writeVarInt(V.lenBody);if(J!==0)return J;if(V.lenBody>0&&V.offBody!==void 0){let Q=$.writeVarInt(V.offBody);if(Q!==0)return Q}return 0},decode($){let[V,Z]=$.readBytes(O0);if(Z!==0)return N(Z);let[J,Q]=$.readVarBytes();if(Q!==0)return N(Q);let[Y,X]=$.readVarInt();if(X!==0)return N(X);let W;if(Y>0){let[G,K]=$.readVarInt();if(K!==0)return N(K);W=G}return M({kdm:V,headCph:J,lenBody:Y,offBody:W})}};async function eV($,V,Z,J,Q){let Y=await Q.deriveIdentity($,V),X=new b,W=new b,G=0,K=0;for(let P of Z){let C=new b,A=C.writeStruct(J0,P.head);if(A!==0)return N(A);let H=C.result(),_=await Y.kdmFor(H),D=Q.deriveCipher(_,"encrypt"),x=await D.encrypt(H),E=P.body?await D.encrypt(P.body):new Uint8Array(0),f=P.head.len>0&&P.head.hsh!==void 0?E.length:0,m={kdm:_,headCph:x,lenBody:f,offBody:f>0?K:void 0},q=X.writeStruct(n$,m);if(q!==0)return N(q);if(P.body)W.writeBytes(E),K+=E.length;G++}let z=W.result(),R=X.result(),F=await J.blake3(R),U=await Y.sign(F),w={lbl:$,idx:V,num:G,hsh:F,sig:U},I=new b;I.writeStruct(p$,{head:w,indexEnc:R,bodyEnc:z});let O=I.result();return M(O)}async function $Z($,V,Z){let[J,Q]=p$.decode(new v($));if(Q!==0)return N(Q);let{head:Y,indexEnc:X,bodyEnc:W}=J,G=await Z.deriveIdentity(Y.lbl,Y.idx);if(!await V.checkSigEd25519(Y.sig,Y.hsh,G.publicKey))return N(3);let z=await V.blake3(X);if(!V0(z,Y.hsh))return N(19);let R=new v(X),F=[];for(let w=0;w<Y.num;w++){let[I,O]=R.readStruct(n$);if(O!==0)return N(O);F.push(I)}if(F.length!==Y.num)return N(14);let U=[];for(let w of F){let I=Z.deriveCipher(w.kdm,"decrypt"),O;try{O=await I.decrypt(w.headCph)}catch{return N(20)}let[P,C]=J0.decode(new v(O));if(C!==0)return N(C);let A;if(w.lenBody>0&&w.offBody!==void 0){if(P.hsh===void 0)return N(14);let H=W.slice(w.offBody,w.offBody+w.lenBody);try{A=await I.decrypt(H)}catch{return N(20)}let _=await V.blake3(A);if(!V0(_,P.hsh))return N(19)}U.push({head:P,body:A})}return M(U)}async function VZ({now:$,bod:V,crypto:Z}){let J=await Z.genRandomBytes(8),Q=new b,Y=Q.writeStruct($0,{id:J,ts:$});if(Y!==0)return N(Y);let X=Q.result();return F$({now:$,eid:X,ctr:0,bod:V,crypto:Z})}async function F$({now:$,eid:V,ctr:Z,bod:J,crypto:Q}){let Y=new v(V),[X,W]=$0.decode(Y);if(W!==0)return N(W);let G=$.getTime()-X.ts.getTime(),K,z=J?.length??0;if(J&&z>0)K=await Q.blake3(J);return M({eid:V,off:G,ctr:Z,len:z,hsh:K})}function CJ($,V){let Z=$.length<V.length?$.length:V.length;for(let J=0;J<Z;J++)if($[J]!==V[J])return $[J]-V[J];return $.length-V.length}async function r0($,V){let Z=Array.from($);Z.sort(CJ);let J=0;for(let X of Z)J+=X.length;let Q=new Uint8Array(J),Y=0;for(let X of Z)Q.set(X,Y),Y+=X.length;return V.blake3(Q)}function TJ($){let V=new b,Z=V.writeVarBytes($.eid);if(Z!==0)return N(Z);let J=V.writeDate($.updatedAt);if(J!==0)return N(J);let Q=V.writeVarInt($.ctr);if(Q!==0)return N(Q);return M(V.result())}async function I$($,V){let Z=[];for(let J of $){let[Q,Y]=TJ(J);if(Y!==0||!Q)return N(Y);Z.push(Q)}return M(await r0(Z,V))}var J8=Symbol("EntityID");function ZZ($){return"type"in $}var Q8=Symbol("MasterSeed"),Y8=Symbol("DerivationSeed"),X8=Symbol("PublicKey"),W8=Symbol("PrivateKey"),G8=Symbol("HostSpecificKeyPair"),K8=Symbol("Hash");function AJ($){if(!$)return!1;if(typeof $!=="object")return!1;if("body"in $===!1)return!1;if("type"in $===!1)return!1;return!0}function DJ($){if(!$.bod||$.bod.length===0){let J={off:$.off,ctr:$.ctr,eid:$.eid};return M(J)}let V=B$($.bod);if(AJ(V)===!1)return console.warn("msg body invalid",V),N(14);let Z={off:$.off,ctr:$.ctr,eid:$.eid,gid:V.gid,pid:V.pid,tags:V.tags,type:V.type,body:V.body};return M(Z)}class U${applier;emitter=new c0;clearer;onDirtyEids;cacheDriven;peerIngest;constructor($,V,Z,J){this.applier=$;this.clearer=V,this.onDirtyEids=Z,this.cacheDriven=J?.cacheDriven??!1,this.peerIngest=J?.peerIngest}apply=async($)=>{let V=[],Z=[];for(let W of $){let[G,K]=DJ(W);if(Z.push(K),K!==0)continue;V.push(G)}let{stats:J,types:Q,eids:Y}=await this.applier(V),X=[];for(let W=0;W<$.length;W++){let G=Z[W],K=J[W];if(G!==0){X.push(G);continue}if(K!==0){X.push(K);continue}X.push(0)}if(!this.cacheDriven)for(let W of Q)this.emitter.emit(W,null);if(Y.length>0)this.onDirtyEids?.(Y);return X};clear=async()=>{let $=await this.clearer();if($!==0)return $;return this.emitter.emitAll(null),$};notify=($)=>{for(let V of $)this.emitter.emit(V,null)};refresh=async($)=>{if(this.peerIngest){await this.peerIngest($);return}};on=($,V)=>{this.emitter.addEventListener($,V)};off=($,V)=>{this.emitter.removeEventListener($,V)}}var p="entities",w$="entity_type_created_at",c$="entity_type_updated_at",d$="entity_type_group_id",r$="entity_type_parent_id",o$="entity_tags",JZ="db",QZ=12;function _J($){let V={bod:$.body,crd:$.createdAt,...$.ctr!==0?{ctr:$.ctr}:{},eid:k($.eid),gid:$.gid,pid:$.pid?k($.pid):void 0,tags:$.tags,typ:$.type,upd:$.updatedAt};if(V.gid===void 0)delete V.gid;if(V.pid===void 0)delete V.pid;if(V.tags===void 0)delete V.tags;if(V.ctr===void 0)delete V.ctr;return V}function q0($){return{body:$.bod,createdAt:$.crd,updatedAt:$.upd,ctr:$.ctr??0,type:$.typ,eid:N0($.eid),gid:$.gid,pid:$.pid?N0($.pid):void 0,...$.tags!==void 0?{tags:$.tags}:{}}}class YZ{db;opening;async init(){await this.ensureDb()}async ensureDb(){if(this.db)return this.db;if(this.opening)return this.opening;return this.opening=LJ().then(($)=>{return $.onversionchange=()=>{if($.close(),this.db===$)this.db=void 0},this.db=$,this.opening=void 0,$},($)=>{throw this.opening=void 0,$}),this.opening}apply=async($)=>{let V=new Set,Z=[],J;try{J=await this.ensureDb()}catch{return{stats:$.map(()=>16),types:V,eids:Z}}let Q=J.transaction(p,"readwrite"),Y=Q.objectStore(p);return new Promise((X)=>{let W=Array($.length).fill(0);if($.length<1){X({stats:[],types:V,eids:Z});return}Q.oncomplete=()=>{X({stats:W,types:V,eids:Z})},Q.onerror=()=>{for(let K=0;K<W.length;K++)if(W[K]===void 0)W[K]=18;X({stats:W,types:V,eids:Z})};let G=new Map;for(let K=0;K<$.length;K++){let z=$[K],R=k(z.eid),F={op:z,index:K},U=G.get(R);if(U)U.push(F);else G.set(R,[F])}for(let[K,z]of G){if(z.length<1)continue;let R=Y.get(K);R.onsuccess=()=>{let F=R.result,U=F?q0(F):void 0,w=!1;for(let{op:I,index:O}of z){let[P,C]=m0(U,I);if(C!==0){W[O]=C;continue}if(w=!0,P)V.add(P.type);else if(U)V.add(U.type);U=P}if(w)Z.push(z[0].op.eid);if(U){let I=_J(U),O=Y.put(I);O.onerror=(P)=>{P.preventDefault();for(let{index:C}of z)W[C]=18}}else{let I=Y.delete(K);I.onerror=()=>{for(let{index:O}of z)W[O]=18}}},R.onerror=()=>{for(let{index:F}of z)W[F]=18}}})};async clear(){let $;try{$=await this.ensureDb()}catch{return 16}let V=$.transaction(p,"readwrite"),Z=V.objectStore(p);return new Promise((J)=>{V.oncomplete=()=>J(0),V.onerror=()=>J(18),Z.clear()})}async getEnt($){let V;try{V=await this.ensureDb()}catch{return N(16)}let Z=k($),Q=V.transaction(p,"readonly").objectStore(p);return new Promise((Y)=>{let X=Q.get(Z);X.onsuccess=()=>{let W=X.result;if(!W)Y(M(void 0));else{let G=q0(W);Y(M(G))}},X.onerror=()=>Y(N(18))})}async getAllOfTypeUpdatedBetween($,V,Z){let J;try{J=await this.ensureDb()}catch{return N(16)}let Y=J.transaction(p,"readonly").objectStore(p).index(c$);return new Promise((X)=>{let W=Y.getAll(IDBKeyRange.bound([$,V],[$,Z]));W.onsuccess=()=>{let G=W.result;X(M(G.map(q0)))},W.onerror=()=>X(N(18))})}async getGroupMembers($,V){let Z;try{Z=await this.ensureDb()}catch{return N(16)}let Q=Z.transaction(p,"readonly").objectStore(p).index(d$);return new Promise((Y)=>{let X=Q.getAll(IDBKeyRange.only([$,V]));X.onsuccess=()=>{let W=X.result;Y(M(W.map(q0)))},X.onerror=()=>Y(N(18))})}async getAllOfType($){let V;try{V=await this.ensureDb()}catch{return N(16)}let J=V.transaction(p,"readonly").objectStore(p).index(w$);return new Promise((Q)=>{let Y=J.getAll(IDBKeyRange.bound([$],[$,[]]));Y.onsuccess=()=>{let X=Y.result;Q(M(X.map(q0)))},Y.onerror=()=>Q(N(18))})}async getByTag($,V){let Z;try{Z=await this.ensureDb()}catch{return N(16)}let Q=Z.transaction(p,"readonly").objectStore(p).index(o$);return new Promise((Y)=>{let X=Q.getAll(IDBKeyRange.only(V));X.onsuccess=()=>{let G=X.result.filter((K)=>K.typ===$).map(q0);Y(M(G))},X.onerror=()=>Y(N(18))})}async getAllEntities($){if("pid"in $){let V;try{V=await this.ensureDb()}catch{return N(16)}let Z=k($.pid),Q=V.transaction(p,"readonly").objectStore(p).index(r$);return new Promise((Y)=>{let X=Q.getAll(IDBKeyRange.only([$.type,Z]));X.onsuccess=()=>{let G=X.result.map(q0);Y(M(G))},X.onerror=()=>Y(N(18))})}else if("gid"in $)return await this.getGroupMembers($.type,$.gid);else if("tag"in $)return await this.getByTag($.type,$.tag);else if("updatedBetween"in $)return await this.getAllOfTypeUpdatedBetween($.type,$.updatedBetween.start,$.updatedBetween.end);return await this.getAllOfType($.type)}async getEntities($){let[V,Z]=await this.getAllEntities($);if(Z!==0)return N(Z);return M(V)}async countEntities({type:$}){let V;try{V=await this.ensureDb()}catch{return N(16)}let J=V.transaction(p,"readonly").objectStore(p).index(w$);return new Promise((Q)=>{let Y=IDBKeyRange.bound([$],[$,[]]),X=J.count(Y);X.onsuccess=()=>Q(M(X.result)),X.onerror=()=>Q(N(18))})}async checksum($){let V;try{V=await this.ensureDb()}catch{return N(16)}let J=V.transaction(p,"readonly").objectStore(p),Q=[];return new Promise((Y)=>{let X=J.openCursor();X.onsuccess=()=>{let W=X.result;if(W){let G=W.value;Q.push(M$(q0(G))),W.continue()}else I$(Q,$).then(Y)},X.onerror=()=>Y(N(18))})}}function jJ($,V){if(!$.objectStoreNames.contains(p))$.createObjectStore(p,{keyPath:"eid",autoIncrement:!1});let Z=V.objectStore(p);if(!Z.indexNames.contains(w$))Z.createIndex(w$,["typ","crd"],{unique:!1});if(!Z.indexNames.contains(c$))Z.createIndex(c$,["typ","upd"],{unique:!1});if(!Z.indexNames.contains(d$))Z.createIndex(d$,["typ","gid"],{unique:!1});if(!Z.indexNames.contains(r$))Z.createIndex(r$,["typ","pid"],{unique:!1});if(!Z.indexNames.contains(o$))Z.createIndex(o$,"tags",{unique:!1,multiEntry:!0})}function LJ(){return new Promise(($,V)=>{let Z=indexedDB.open(JZ,QZ);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!Q){V(Error("Transaction is null during EntDB upgrade"));return}try{jJ(J,Q)}catch(Y){V(Y instanceof Error?Y:Error(String(Y)))}},Z.onblocked=()=>{console.warn(`[DIPLOMATIC] EntDB IDB upgrade blocked (${JZ} → v${QZ}); waiting for other connections to close`)},Z.onsuccess=()=>$(Z.result),Z.onerror=()=>V(Z.error??Error("EntDB IndexedDB open failed"))})}async function XZ(){let $=new YZ;return await $.init(),$}class a${ents=new Map;useIndex;byType=new Map;byTypePid=new Map;byTypeGid=new Map;byTypeTag=new Map;constructor($=[],V){this.useIndex=V?.indexes!==!1;for(let Z of $)this.put(Z)}put($){let V=k($.eid),Z=this.ents.get(V);if(Z)this.unindex(V,Z);this.ents.set(V,$),this.index(V,$)}del($){let V=this.ents.get($);if(!V)return;this.unindex($,V),this.ents.delete($)}index($,V){if(!this.useIndex)return;let Z=this.byType.get(V.type);if(!Z)Z=new Map,this.byType.set(V.type,Z);if(Z.set($,V),V.pid){let J=k(V.pid),Q=this.byTypePid.get(V.type);if(!Q)Q=new Map,this.byTypePid.set(V.type,Q);let Y=Q.get(J);if(!Y)Y=new Map,Q.set(J,Y);Y.set($,V)}if(typeof V.gid==="string"){let J=this.byTypeGid.get(V.type);if(!J)J=new Map,this.byTypeGid.set(V.type,J);let Q=J.get(V.gid);if(!Q)Q=new Map,J.set(V.gid,Q);Q.set($,V)}if(V.tags){let J=this.byTypeTag.get(V.type);if(!J)J=new Map,this.byTypeTag.set(V.type,J);for(let Q of V.tags){let Y=J.get(Q);if(!Y)Y=new Map,J.set(Q,Y);Y.set($,V)}}}unindex($,V){if(!this.useIndex)return;let Z=this.byType.get(V.type);if(Z){if(Z.delete($),Z.size===0)this.byType.delete(V.type)}if(V.pid){let J=k(V.pid),Q=this.byTypePid.get(V.type),Y=Q?.get(J);if(Y){if(Y.delete($),Y.size===0)Q?.delete(J)}if(Q&&Q.size===0)this.byTypePid.delete(V.type)}if(typeof V.gid==="string"){let J=this.byTypeGid.get(V.type),Q=J?.get(V.gid);if(Q){if(Q.delete($),Q.size===0)J?.delete(V.gid)}if(J&&J.size===0)this.byTypeGid.delete(V.type)}if(V.tags){let J=this.byTypeTag.get(V.type);if(J){for(let Q of V.tags){let Y=J.get(Q);if(Y){if(Y.delete($),Y.size===0)J.delete(Q)}}if(J.size===0)this.byTypeTag.delete(V.type)}}}clearIndexes(){this.byType.clear(),this.byTypePid.clear(),this.byTypeGid.clear(),this.byTypeTag.clear()}bucketList($){if(!$||$.size===0)return[];let V=[];for(let Z of $.values())V.push(Z);return V}async apply($){let V=new Set,Z=[],J=[];for(let Q of $){let Y=k(Q.eid),X=this.ents.get(Y),[W,G]=m0(X,Q);if(G!==0){J.push(G);continue}if(W)V.add(W.type);else if(X)V.add(X.type);if(W)this.put(W);else this.del(Y);Z.push(Q.eid),J.push(0)}return{stats:J,types:V,eids:Z}}async clear(){return this.ents.clear(),this.clearIndexes(),0}async getEnt($){let V=k($),Z=this.ents.get(V);return M(Z)}async getAllEntities({type:$,gid:V,pid:Z,tag:J,updatedBetween:Q}){if(this.useIndex){if(Z!==void 0){let X=k(Z);return M(this.bucketList(this.byTypePid.get($)?.get(X)))}if(V!==void 0)return M(this.bucketList(this.byTypeGid.get($)?.get(V)));if(J!==void 0)return M(this.bucketList(this.byTypeTag.get($)?.get(J)));if(Q!==void 0){let X=[],W=this.byType.get($);if(W){for(let G of W.values())if(G.updatedAt>=Q.start&&G.updatedAt<=Q.end)X.push(G)}return M(X)}return M(this.bucketList(this.byType.get($)))}let Y=[];if(Z!==void 0){for(let X of this.ents.values())if(X.type===$&&X.pid&&V0(X.pid,Z))Y.push(X)}else if(V!==void 0){for(let X of this.ents.values())if(X.type===$&&(typeof X.gid==="string"&&X.gid===V))Y.push(X)}else if(J!==void 0){for(let X of this.ents.values())if(X.type===$&&X.tags&&X.tags.includes(J))Y.push(X)}else if(Q!==void 0){for(let X of this.ents.values())if(X.type===$&&X.updatedAt>=Q.start&&X.updatedAt<=Q.end)Y.push(X)}else for(let X of this.ents.values())if(X.type===$)Y.push(X);return M(Y)}async getEntities($){let[V,Z]=await this.getAllEntities($);if(Z!==0)return N(Z);return M(V)}async countEntities({type:$}){if(this.useIndex)return M(this.byType.get($)?.size??0);let V=0;for(let Z of this.ents.values())if(Z.type===$)V+=1;return M(V)}async checksum($){let V=[];for(let Z of this.ents.values())V.push(M$(Z));return I$(V,$)}}async function WZ($){let V=await XZ();if($?.cache===!1)return V;return new s$(V,void 0,{indexes:$?.indexes})}class s${mem;durable;warmed=new Set;listeners=new Set;chain=Promise.resolve();constructor($,V,Z){if(this.durable=$,this.mem=new a$(V??[],{indexes:Z?.indexes}),V)for(let J of V)this.warmed.add(J.type)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}emit($){if($.size<1)return;for(let V of this.listeners)V($)}run($){let V=this.chain.then($,$);return this.chain=V.then(()=>{return},()=>{return}),V}apply($){return this.run(async()=>{let V=BJ(this.mem,$);this.emit(V.types);let Z=await this.durable.apply($),{changed:J,status:Q}=await this.pullEids($.map((Y)=>Y.eid));if(this.emit(J),Q!==0)return{stats:$.map(()=>Q),types:Z.types,eids:Z.eids};return Z})}clear(){return this.run(async()=>{let $=await this.durable.clear();if($!==0)return $;let V=this.mem.ents.size>0;return await this.mem.clear(),this.warmed.clear(),0})}ingestFromDurable($){return this.run(async()=>{let{changed:V,status:Z}=await this.pullEids($);return this.emit(V),Z})}async pullEids($){let V=new Set,Z=new Set;for(let J of $){let Q=k(J);if(Z.has(Q))continue;Z.add(Q);let Y=this.mem.ents.get(Q),[X,W]=await this.durable.getEnt(J);if(W!==0)return{changed:V,status:W};if(X){if(this.mem.put(X),!Y||!xJ(Y,X)){if(V.add(X.type),Y&&Y.type!==X.type)V.add(Y.type)}}else if(Y)this.mem.del(Q),V.add(Y.type)}return{changed:V,status:0}}async warmType($){if(this.warmed.has($))return 0;let[V,Z]=await this.durable.getEntities({type:$});if(Z!==0)return Z;if(V)for(let J of V){let Q=k(J.eid),Y=this.mem.ents.get(Q);if(!Y||kJ(J,Y))this.mem.put(J)}return this.warmed.add($),0}async getEnt($){let V=k($);if(this.mem.ents.has(V))return this.mem.getEnt($);return this.run(async()=>{if(this.mem.ents.has(V))return this.mem.getEnt($);let[Z,J]=await this.durable.getEnt($);if(J!==0)return N(J);if(Z)this.mem.put(Z);return M(Z)})}async getEntities($){if(!this.warmed.has($.type)){let V=await this.run(()=>this.warmType($.type));if(V!==0)return N(V)}return this.mem.getEntities($)}async countEntities({type:$}){if(!this.warmed.has($)){let V=await this.run(()=>this.warmType($));if(V!==0)return N(V)}return this.mem.countEntities({type:$})}async checksum($){return this.durable.checksum($)}}function xJ($,V){if($.ctr!==V.ctr)return!1;if($.updatedAt.getTime()!==V.updatedAt.getTime())return!1;if($.createdAt.getTime()!==V.createdAt.getTime())return!1;if($.type!==V.type)return!1;if($.gid!==V.gid)return!1;if(!V0($.eid,V.eid))return!1;if(!fJ($.pid,V.pid))return!1;if(!EJ($.tags,V.tags))return!1;return SJ($.body,V.body)}function EJ($,V){if($===V)return!0;if($===void 0||V===void 0)return!1;if($.length!==V.length)return!1;for(let Z=0;Z<$.length;Z++)if($[Z]!==V[Z])return!1;return!0}function fJ($,V){if($===void 0&&V===void 0)return!0;if($===void 0||V===void 0)return!1;return V0($,V)}function SJ($,V){if(Object.is($,V))return!0;if($ instanceof Uint8Array&&V instanceof Uint8Array)return V0($,V);if($ instanceof Date&&V instanceof Date)return $.getTime()===V.getTime();try{return V0(P0($),P0(V))}catch{return!1}}function kJ($,V){let Z=$.updatedAt.getTime(),J=V.updatedAt.getTime();if(Z!==J)return Z>J;return $.ctr>V.ctr}function BJ($,V){let Z=new Set,J=[];for(let Q of V){let Y=k(Q.eid),X=$.ents.get(Y),[W,G]=m0(X,Q);if(G!==0){J.push(G);continue}if(W)Z.add(W.type);else if(X)Z.add(X.type);if(W)$.put(W);else $.del(Y);J.push(0)}return{stats:J,types:Z}}function mJ($){if(!Array.isArray($)||$.length===0)return;let V=new Set,Z=[];for(let J of $){if(typeof J!=="string"||J.length===0)continue;if(V.has(J))continue;V.add(J),Z.push(J)}return Z.length>0?Z:void 0}function M$($){return{eid:$.eid,ctr:$.ctr,updatedAt:$.updatedAt}}function GZ($){let V=new v($.eid),[Z,J]=V.readStruct($0);if(J!==0)return N(J);return M({eid:$.eid,ctr:$.ctr,updatedAt:new Date(Z.ts.getTime()+$.off)})}function m0($,V){let Z=new v(V.eid),[J,Q]=Z.readStruct($0);if(Q!==0)return N(Q);let Y=new Date(J.ts.getTime()+V.off);if($!==void 0&&Y<=$.updatedAt)return N(15);if(ZZ(V)){let X=mJ(V.tags);return M({eid:V.eid,gid:V.gid,pid:V.pid,...X!==void 0?{tags:X}:{},type:V.type,createdAt:J.ts,updatedAt:Y,ctr:V.ctr,body:V.body})}else return M(void 0)}class O${inflight=null;again=!1;run($){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain($),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain($){try{this.again=!1;let V=await $();while(this.again)this.again=!1,V=await $();return V}finally{this.inflight=null}}}var KZ=100;class t${timer=null;delayMs;work;tail=new O$;constructor($,V){this.delayMs=$<0?0:$,this.work=V}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)}}function zZ($){let V=new v($.eid),[Z,J]=$0.decode(V);if(J!==0)return;return Z.ts.getTime()+$.off}function gJ($,V){let Z=zZ($),J=zZ(V);if(Z===void 0&&J===void 0)return 0;if(Z===void 0)return 1;if(J===void 0)return-1;if(J!==Z)return J-Z;return V.ctr-$.ctr}function g0($,V){return $.slice().sort((Z,J)=>gJ(V(Z),V(J)))}var e$={phase:"idle"},o0=50;function $V($,V,Z){if($<=0||V<=0)return!1;if($===1||$===V)return!0;return $%Z===0}function NZ($,V){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob($,V);return}let Z=URL.createObjectURL($),J=document.createElement("a");J.href=Z,J.download=V,document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL(Z)}function RZ($,V,Z){let J=[],Q=[],Y=0;for(let X of $){let W=V(X);if(Q.length>0&&Y+W>Z)J.push(Q),Q=[],Y=0;if(Q.push(X),Y+=W,Y>=Z)J.push(Q),Q=[],Y=0}if(Q.length>0)J.push(Q);return J}async function VV($,V,Z){let J=$.length;if(J<1)return[];let Q=Array(J),Y=0,X=Math.min(Math.max(1,V),J),W=async()=>{while(!0){let K=Y;if(Y+=1,K>=J)return;Q[K]=await Z($[K],K)}},G=[];for(let K=0;K<X;K++)G.push(W());return await Promise.all(G),Q}async function H$($,V,Z,J){let Q=new v($.headCph),[Y,X]=Q.readStruct(z$);if(X!==0)return N(X);let{sig:W,kdm:G,headCph:K}=Y;if(!await J.checkSigEd25519(W,K,V))return N(3);let R=Z.deriveCipher(G,"decrypt"),F;try{F=await R.decrypt(K)}catch{return N(20)}return M({kdm:G,headEnc:F})}var b0="f",q$="t",v0="e";function vJ($){if($===!0||$===q$)return q$;if($===v0)return v0;return b0}function FZ($){return $!==0&&$!==15&&$!==18&&$!==17}function ZV($,V,Z){if($.apld=V,V===v0&&Z!==void 0)$.err=Z;else delete $.err}async function P$($,V,Z,J){let Q=J?.body!==!1,Y=vJ(V.apld),X=V.body,W=X?.length??0,G;if(Q&&X&&W>0)G=await Z.blake3(X);let K={eid:V.eid,off:V.off??0,ctr:V.ctr??0,len:W,hsh:G},z={hash:$,head:K,apld:Y};if(Q&&X!==void 0)z.body=X;if(Y===v0&&V.err!==void 0)z.err=V.err;return z}var JV=1048576,QV=1048576,UZ=64;function bJ($){return $.sig.length+$.kdm.length+$.headCph.length+$.bodyCph.length}async function yJ($,V,Z,J,Q){if(J.length<1)return 0;let[Y,X]=await $.push(J);if(X!==0)return X;if(!Y)return 27;for(let G of Y){if(G.status!==0){console.error("push err",G);continue}let K=Q[G.idx];if(!K){console.error("no hash",G);continue}await V.uploads.deq(Z,[K])}let W=await V.hosts.get(Z);if(W){let G=W.lastSeq,K=G,z=[];for(let R of Y)if(R.status===0)z.push(R.seq);z.sort((R,F)=>R-F);for(let R of z)if(R===G+1)G=R;if(G>K)await V.hosts.touch(Z,G)}return 0}async function IZ($,V){if(V.length<1)return M([]);let Z=new Map,J=[];for(let W of V)Z.set(W.seq,W),J.push(W.seq);let[Q,Y]=await $.pull(J);if(Y!==0)return N(Y);if(!Q)return N(27);let X=[];for(let{seq:W,bodyCph:G}of Q){let K=Z.get(W);if(!K)continue;X.push({dl:K,bodyCph:G})}return M(X)}async function iJ($,V,Z,J){if(J.length<1)return M({parts:[],hashes:[]});let Q=[],Y=[],X=[],W=new Map;for(let{dl:K,bodyCph:z}of J){let{head:R,kdm:F,seq:U,host:w}=K,[I,O]=await wZ(K,Z);if(O!==0||!I){let f=W.get(w)??[];f.push(U),W.set(w,f);continue}let{headEnc:P,headEncHash:C}=I,A=V.deriveCipher(F,"decrypt"),[H,_]=await g$(P,z,A,Z,C);if(_!==0||!H){let f=W.get(w)??[];f.push(U),W.set(w,f);continue}let D={head:R,body:H.bod},x=H.headHash;X.push({key:x,data:HZ(D)}),Q.push(D),Y.push(x);let E=W.get(w)??[];E.push(U),W.set(w,E)}let G=await $.messages.add(X);for(let[K,z]of W)await $.downloads.deq(K,z);for(let K=0;K<G.length;K++){let z=G[K];if(z!==0&&z!==15)console.error("ERR storing",L[z],"for message",K)}return M({parts:Q,hashes:Y})}async function wZ($,V){let Z=$.headEnc;if(!Z){let Q=new b,Y=Q.writeStruct(J0,$.head);if(Y!==0)return N(Y);Z=Q.result()}if($.headEncHash)return M({headEnc:Z,headEncHash:$.headEncHash});let J=await V.blake3(Z);return M({headEnc:Z,headEncHash:J})}async function MZ($,V,Z){let J=new Set;for(let X of V)J.add(k(X));if(J.size<1)return;let Q=Array.from(await $.downloads.list());if(Q.length<1)return;let Y=new Map;for(let X of Q){let W;if(X.headEncHash)W=k(X.headEncHash);else{let[K,z]=await wZ(X,Z);if(z!==0||!K)continue;W=k(K.headEncHash)}if(!J.has(W))continue;let G=Y.get(X.host)??[];G.push(X.seq),Y.set(X.host,G)}for(let[X,W]of Y)await $.downloads.deq(X,W)}async function YV({conn:$,store:V,enclave:Z,host:J,crypto:Q,onProgress:Y,peekProgressEvery:X,peekConcurrency:W}){let G=await $.identity(),K=[],[z,R]=await $.peek(J.lastSeq);if(R!==0)return R;let F=z.length,U=X??o0,w=W??UZ;if(Y&&F>0)Y({phase:"peek",host:J.label,done:0,total:F});let I=0,O=await VV(z,w,async(D)=>{let[x,E]=await H$(D,G.publicKey,Z,Q),f;if(E!==0||!x)f={ok:!1,seq:D.seq,stat:E};else{let m=await Q.blake3(x.headEnc);f={ok:!0,seq:D.seq,kdm:x.kdm,headEnc:x.headEnc,headEncHash:m}}if(I+=1,Y&&$V(I,F,U))Y({phase:"peek",host:J.label,done:I,total:F});return f}),P=new Map,C=new Set,A=0,H=await V.uploads.list(J.label),_=new Set(H.map((D)=>k(D)));for(let D of O){if(!D.ok){console.error("peek: decrypting item head",D.stat);continue}let x=k(D.headEncHash),E=(P.get(x)??0)+1;if(P.set(x,E),E>1)A+=1;if(await V.messages.has(D.headEncHash)){if(console.info("peek: local msg; skip download, deq upload"),E===1&&!_.has(x))A+=1;_.delete(x),await V.uploads.deq(J.label,[D.headEncHash]),await V.downloads.deq(J.label,[D.seq]);continue}if(C.has(x)){await V.downloads.deq(J.label,[D.seq]);continue}let m=new v(D.headEnc),[q,y]=m.readStruct(J0);if(y!==0){console.error("peek: reading item head",y);continue}C.add(x),K.push({kdm:D.kdm,head:q,seq:D.seq,host:J.label,headEnc:D.headEnc,headEncHash:D.headEncHash})}if(await V.downloads.enq(K),z.length>0){let D=Math.max(...z.map((x)=>x.seq));await V.hosts.recordStats(J.label,{lastSeq:D,bagDelta:z.length,dupeDelta:A>0?A:void 0})}if(Y)Y({phase:"peek",host:J.label,done:F,total:F});return 0}async function OZ({conn:$,store:V,host:Z,maxPushBytes:J,onProgress:Q}){let Y=J??JV,X=await V.uploads.list(Z.label),W=X.length,G=0;if(Q&&W>0)Q({phase:"push",host:Z.label,done:0,total:W});let K=[],z=[],R=0,F=async()=>{if(K.length<1)return 0;let U=K.length,w=await yJ($,V,Z.label,K,z);if(K=[],z=[],R=0,w===0){if(G+=U,Q)Q({phase:"push",host:Z.label,done:G,total:W})}return w};for(let U of X){let w=await V.messages.get(U);if(!w){G+=1;continue}let I={...w.head,bod:w.body},[O,P]=await $.seal(I);if(P!==0)return P;if(!O)return 12;let C=bJ(O);if(K.length>0&&R+C>Y){let A=await F();if(A!==0)return A}if(K.push(O),z.push(U),R+=C,R>=Y){let A=await F();if(A!==0)return A}}return F()}async function XV({conn:$,store:V,enclave:Z,host:J,crypto:Q,maxPullBytes:Y,onProgress:X},W){let G=Y??QV,K=await V.downloads.list(),z=Array.from(K).filter((O)=>O.host===J.label);if(z.length<1)return 15;let R=g0(z,(O)=>O.head),F=RZ(R,(O)=>O.head.len,G),U=R.length,w=0;if(X)X({phase:"pull",host:J.label,done:0,total:U});let I=IZ($,F[0]);for(let O=0;O<F.length;O++){let[P,C]=await I;if(C!==0||!P)return C;if(w+=F[O].length,X)X({phase:"pull",host:J.label,done:w,total:U});let A=F[O+1];if(A)I=IZ($,A);if(X)X({phase:"open",host:J.label,done:w,total:U});let H=g0(P,(D)=>D.dl.head),[,_]=await iJ(V,Z,Q,H);if(_!==0)return _;if(W){if(X)X({phase:"exec",host:J.label,done:w,total:U});await W()}}return 0}function HZ({head:$,body:V}){let Z={eid:$.eid,body:V,apld:b0};if($.off!==0)Z.off=$.off;if($.ctr!==0)Z.ctr=$.ctr;return Z}async function qZ($,{conn:V,store:Z,enclave:J,host:Q,crypto:Y,onProgress:X},W){let G=Q.label,K=await V.identity(),z=new v($),[R,F]=z.readStructs(K$);if(F!==0){console.error("Failed decoding notif",L[F]);return}let U=!1,I=(await Z.hosts.get(G))?.lastSeq,O=[],P=!1;for(let H of R){let[_,D]=await H$({seq:H.seq,headCph:H.headCph},K.publicKey,J,Y);if(D!==0){console.error("Failed decrypting notif",L[D]);continue}let x=await Y.blake3(_.headEnc);if(await Z.messages.has(x))continue;let E=new v(_.headEnc),[f,m]=E.readStruct(J0);if(m!==0){console.error("Failed to parse head",L[m]);continue}if(!H.bodyCph&&f.len>0)P=!0,await Z.downloads.enq([{seq:H.seq,host:G,kdm:_.kdm,head:f,headEnc:_.headEnc,headEncHash:x}]);else O.push({..._,head:f,bodyCph:H.bodyCph,headEncHash:x});if(I===void 0||H.seq!==I+1)console.log("out of seq",H.seq,I),U=!0;else I=H.seq}if(I!==void 0)await Z.hosts.touch(Q.label,I);let C=[];for(let H of O){let _=J.deriveCipher(H.kdm,"decrypt"),[D,x]=await g$(H.headEnc,H.bodyCph,_,Y);if(x!==0){console.error("Failed to open body",L[x]);continue}C.push({key:H.headEncHash,data:HZ({head:H.head,body:D.bod})})}let A=await Z.messages.add(C);for(let H=0;H<A.length;H++){let _=A[H];if(_!==0&&_!==15)console.error("ERR storing",L[_],"for message",H)}if(X&&C.length>0)X({phase:"open",host:Q.label,done:C.length,total:C.length});if(U||P||C.length>0)W()}async function PZ($,V={}){let Z=V.pull!==!1,J=V.push===!0,{conn:Q,store:Y,enclave:X,host:W,crypto:G,onProgress:K,peekProgressEvery:z,peekConcurrency:R}=$,F=await Q.identity(),[U,w]=await Q.peek(0);if(w!==0)return N(w);let I=U.length,O=z??o0,P=R??UZ;if(K&&I>0)K({phase:"peek",host:W.label,done:0,total:I});let C=0,A=await VV(U,P,async(S)=>{let[g,B]=await H$(S,F.publicKey,X,G),i;if(B!==0||!g)i={ok:!1,seq:S.seq,stat:B};else{let j=await G.blake3(g.headEnc);i={ok:!0,seq:S.seq,kdm:g.kdm,headEnc:g.headEnc,headEncHash:j}}if(C+=1,K&&$V(C,I,O))K({phase:"peek",host:W.label,done:C,total:I});return i}),H=new Map;for(let S of A){if(!S.ok)continue;let g=k(S.headEncHash),B=H.get(g);if(B)B.count+=1;else H.set(g,{hash:S.headEncHash,count:1,sample:S})}let _=0,D=[];for(let S of H.values()){if(S.count>1)_+=S.count-1;D.push(S.hash)}let x=U.length,E=H.size,f=await r0(D,G),m=[],q=0;for(let S of H.values()){if(await Y.messages.has(S.hash)){await Y.uploads.deq(W.label,[S.hash]);continue}if(q+=1,!Z)continue;let B=S.sample,i=new v(B.headEnc),[j,n]=i.readStruct(J0);if(n!==0){console.error("reconcile: reading msg header",n);continue}m.push({kdm:B.kdm,head:j,seq:B.seq,host:W.label,headEnc:B.headEnc,headEncHash:B.headEncHash})}if(m.length>0)await Y.downloads.enq(m);let y=0;if(J){let S=await Y.messages.listKeys(),g=new Set(H.keys()),B=[];for(let i of S)if(!g.has(k(i)))y+=1,B.push(i);if(B.length>0)await Y.uploads.enq(W.label,B)}else{let S=await Y.messages.listKeys(),g=new Set(H.keys());for(let B of S)if(!g.has(k(B)))y+=1}let l=U.length>0?Math.max(...U.map((S)=>S.seq)):0;if(await Y.hosts.recordStats(W.label,{numBags:x,numDupes:_,setLastSeq:l}),K)K({phase:"peek",host:W.label,done:I,total:I});return M({msgcheck:f,bagCount:x,uniqueMsgs:E,numDupes:_,missingLocal:q,missingHost:y})}class WV{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new O$;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=o0;lastProgress=e$;scheduledSync;constructor($,V,Z,J,Q,Y=!0,X=JV,W=QV,G){this.clock=$;this.state=V;this.store=Z;this.transport=J;this.crypto=Q;this.forceSkewHandlingByDefault=Y;this.onScheduleSync=G;this.maxPushBytes=X,this.maxPullBytes=W,this.clientState=new C0(()=>this.getClientState()),this.xferState=new C0(()=>this.getXferState()),this.scheduledSync=new t$(KZ,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(K){console.error("Debounced sync failed:",K)}})}emitProgress=($)=>{this.lastProgress=$,this.xferState.emit()};async setSeed($){await this.store.seed.save($),this.clientState.emit()}async getClientState(){let{store:$,connections:V}=this,Z=await $.seed.load(),J=await $.hosts.list(),Q=!1;for(let Y of V.values())if(Y.isConnected()){Q=!0;break}return{hasSeed:Z!==void 0,hasHost:Array.from(J).length>0,connected:Q}}async getXferState(){let{uploads:$,downloads:V}=this.store,Z=await $.count();return{numDownloads:await V.count(),numUploads:Z,progress:this.lastProgress}}apply=($,V)=>{return this.enqueueApplyJob(()=>this.doApply($,V))};async doApply($,V={enqueueUpload:!0,triggerUpload:!0}){let Z=[],J=[];for(let{head:Y,body:X}of $){let W=new b;W.writeStruct(J0,Y);let G=W.result(),K=await this.crypto.blake3(G),z={eid:Y.eid,body:X,apld:b0};if(Y.off!==0)z.off=Y.off;if(Y.ctr!==0)z.ctr=Y.ctr;Z.push(K),J.push({key:K,data:z})}await this.store.messages.add(J),await MZ(this.store,Z,this.crypto);let Q=await this.doApplyHashes(Z);if(V.enqueueUpload){let Y=[];for(let X=0;X<Z.length;X++){let W=Q[X];if(W===0||W===15)Y.push(Z[X])}if(Y.length>0){let X=await this.store.hosts.list();for(let W of X)await this.store.uploads.enq(W.label,Y);this.xferState.emit()}}if(V.triggerUpload)this.scheduleSync();return Q}enqueueApplyJob($){let V=this.applyChain.then($,$);return this.applyChain=V.then(()=>{return},()=>{return}),V}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let $=await this.store.messages.list({apld:b0});if($.length<1)return[];let V=g0($,(Z)=>Z.head);return this.applyStored(V)}applyHashes=($)=>{return this.enqueueApplyJob(()=>this.doApplyHashes($))};async doApplyHashes($){let V=[];for(let Q of $){let Y=await this.store.messages.get(Q);if(Y)V.push(Y)}let Z=await this.applyStored(V),J=new Map;for(let Q=0;Q<V.length;Q++)J.set(k(V[Q].hash),Z[Q]??12);return $.map((Q)=>J.get(k(Q))??13)}async applyStored($){if($.length<1)return[];let V=$.map((Y)=>({...Y.head,bod:Y.body})),Z=await this.state.apply(V),J=[],Q=[];for(let Y=0;Y<$.length;Y++){let X=Z[Y];if(X===0||X===15)J.push($[Y].hash);else if(X!==void 0&&FZ(X))Q.push({key:$[Y].hash,err:X})}if(J.length>0)await this.store.messages.markApplied(J);if(Q.length>0)await this.store.messages.markFailed(Q);return Z}async insertRaw($){let{clock:V,crypto:Z}=this,[J,Q]=await VZ({now:V.now(),bod:$,crypto:Z});if(Q!==0)return N(Q);let X=(await this.apply([{head:J,body:$}]))[0];if(X!==0&&X!==15)return N(X??12);return M(J)}async makeUpdate($,V){let{clock:Z,crypto:J}=this,Q=Z.now();if($.updatedAt.getTime()>Q.getTime())return N(4);let Y=$.ctr+1,[X,W]=await F$({now:Q,eid:$.eid,ctr:Y,bod:V,crypto:J});if(W!==0)return N(W);return M({head:X,body:V})}async updateWithSkew($,V,Z){if(Z===!1)return N(4);let{clock:J,crypto:Q}=this,Y=J.now(),X=new v($.eid),[W,G]=X.readStruct($0);if(G!==0)return N(G);let K=$.updatedAt.getTime()-W.ts.getTime(),z={eid:$.eid,off:K+1,ctr:$.ctr+1,len:0},F=(await this.apply([{head:z,body:void 0}]))[0];if(F!==0&&F!==15)return N(F??12);if(V===void 0)return M(z);let[U,w]=X$({id:W.id,ts:Y});if(w!==0)return N(w);let[I,O]=await F$({now:Y,eid:U,ctr:0,bod:V,crypto:Q});if(O!==0)return N(O);let C=(await this.apply([{head:I,body:V}]))[0];if(C!==0&&C!==15)return N(C??12);return M(I)}async updateRaw($,V,Z=this.forceSkewHandlingByDefault){if($.updatedAt.getTime()>this.clock.now().getTime())return this.updateWithSkew($,V,Z);return this.enqueueApplyJob(async()=>{let[J,Q]=await this.makeUpdate($,V);if(Q!==0)return N(Q);let X=(await this.doApply([J]))[0];if(X!==0&&X!==15)return N(X??12);return M(J.head)})}async insert($){let{body:V,type:Z,gid:J,pid:Q,tags:Y}=$,W=P0({body:V,type:Z,gid:J,pid:Q,tags:Y});return this.insertRaw(W)}async update($){let{prior:V,body:Z,type:J,gid:Q,pid:Y,tags:X,force:W}=$,K=P0({body:Z,type:J,gid:Q,pid:Y,tags:X});return this.updateRaw(V,K,W??this.forceSkewHandlingByDefault)}async delete($){let V=$.force??!0;if("prior"in $)return this.updateRaw($.prior,void 0,V);let[Z,J]=await this.revFromArchive($.eid);if(J!==0)return N(J);return this.updateRaw(Z,void 0,V)}async revFromArchive($){let V=await this.store.messages.last($);if(V)return GZ(V.head);let Z=new v($),[J,Q]=Z.readStruct($0);if(Q!==0)return N(Q);return M({eid:$,ctr:-1,updatedAt:J.ts})}async genEID($){let{clock:V,crypto:Z}=this,J=V.now();if($!==void 0)return X$({id:$,ts:J});let Q=await Z.genRandomBytes(8);return X$({id:Q,ts:J})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:$,crypto:V,store:Z}=this,J=await Z.seed.load();if(!J)return 22;await this.drainApplyQueue();for(let[Q,Y]of $){let X=await Z.hosts.get(Q);if(!X)continue;let W={conn:Y,store:Z,enclave:J,host:X,crypto:V,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},G=await YV(W);if(G!==0)return console.error(`Failed to peek: ${G}`),this.emitProgress({phase:"idle"}),G;this.xferState.emit();let K=await OZ(W);if(K!==0)return console.error(`Failed to push: ${K}`),this.emitProgress({phase:"idle"}),K;this.xferState.emit();let z=await XV(W,async()=>{await this.drainApplyQueue()});if(z!==0&&z!==15)return console.error(`Failed to pull: ${z}`),this.emitProgress({phase:"idle"}),z;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async rebuild($){if(this.scheduledSync.cancel(),await this.syncRuns.flush(),$?.checkHost??!0){let Z=await this.repull();if(Z!==0)return Z}return this.enqueueApplyJob(()=>this.replay())}async msgcheck(){let $=await this.store.messages.listKeys();return r0($,this.crypto)}listMsgs($){return this.store.messages.list($)}countMsgs($){return this.store.messages.count($)}async reconcile($,V){this.scheduledSync.cancel(),await this.syncRuns.flush();let{connections:Z,crypto:J,store:Q}=this,Y=await Q.seed.load();if(!Y)return N(22);let X=await Q.hosts.get($);if(!X)return N(13);let W=Z.get($);if(!W||!W.isConnected()){if(await this.connectToHost(X,!1,!1),X=await Q.hosts.get($),!X)return N(13);W=Z.get($)}if(!W)return N(12);let[G,K]=await PZ({conn:W,store:Q,enclave:Y,host:X,crypto:J,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},V);if(this.xferState.emit(),K!==0)return this.emitProgress({phase:"idle"}),N(K);if(!G)return this.emitProgress({phase:"idle"}),N(12);if(V?.sync!==!1){let z=await this.sync();if(z!==0)return N(z)}else this.emitProgress({phase:"idle"});return M(G.msgcheck)}async repull(){let{connections:$,crypto:V,store:Z}=this,J=await Z.seed.load();if(!J)return 22;let Q=Array.from(await Z.hosts.list());if(Q.length<1)return 0;for(let Y of Q){let X=$.get(Y.label);if(!X||!X.isConnected())await this.connectToHost(Y,!1,!1)}for(let[Y,X]of $){let W=await Z.hosts.get(Y);if(!W)continue;let G={conn:X,store:Z,enclave:J,host:{...W,lastSeq:0},crypto:V,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},K=await YV(G);if(K!==0)return console.error(`rebuild: failed to peek: ${K}`),this.emitProgress({phase:"idle"}),K;this.xferState.emit();let z=await XV(G);if(z!==0&&z!==15)return console.error(`rebuild: failed to pull: ${z}`),this.emitProgress({phase:"idle"}),z;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async replay(){let $=await this.state.clear();if($!==0)return $;let V=await this.store.messages.list(),Z=g0(V,(Y)=>Y.head),J=Z.length;if(J<1)return this.emitProgress({phase:"idle"}),0;let Q=0;while(Q<Z.length){let Y=0,X=0,W=Q;for(let K=Q;K<Z.length&&X<100&&Y<102400;K++)Y+=Z[K].head.len,X++,W=K+1;let G=Z.slice(Q,W);await this.applyStored(G),this.emitProgress({phase:"exec",done:W,total:J}),Q=W}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=e$,this.clientState.emit(),this.xferState.emit()}import=async($,V)=>{let{crypto:Z,store:J}=this,Q=V?.onProgress,Y=await J.seed.load();if(!Y)return 22;console.time("import: decoding file...");let X=await $.bytes(),[W,G]=await $Z(X,Z,Y);if(G!==0)return G;console.timeEnd("import: decoding file...");let K=0;while(K<W.length){let z=0,R=0,F=K;for(let I=K;I<W.length&&R<100&&z<102400;I++)z+=W[I].head.len,R++,F=I+1;let U=W.slice(K,F);console.time(`import: applying [${K}, ${F}]`);let w=await this.apply(U,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${K}, ${F}]`);for(let I=0;I<U.length;I++){let O=w[I];if(O!==0&&O!==15)console.warn(`failed to import msg ${K+I}: ${L[O]}`)}if(Q)queueMicrotask(()=>Q(F,W.length,0));this.emitProgress({phase:"import",done:F,total:W.length}),K=F}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:$,store:V}=this,Z=await V.seed.load();if(!Z)return N(22);let J=await V.messages.list();return eV("export",0,J,$,Z)}async export($){let[V,Z]=await this.exportBytes();if(Z!==0)return Z;if(!V)return 12;let J=new Blob([V.slice()]);return NZ(J,$),0}async link($,V=!0){if(await this.store.hosts.add($),this.clientState.emit(),V){let Z=await this.store.hosts.get($.label);if(Z)await this.connectToHost(Z)}}async unlink($){await this.store.hosts.del($),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:Y,store:X,transport:W}=this,G=Q.get($.label);if(G){if(G.isConnected())return;try{G.closeListener()}catch{}Q.delete($.label)}let K=await X.seed.load();if(!K)return;console.info(`Connecting to ${$.handle} (${$.label})`);let z=new R$(K,Y,$,J,W($),(R)=>X.hosts.set($.label,R));if(await z.register(),V)await z.listen(async(R)=>{let F={conn:z,store:X,enclave:K,host:$,crypto:Y,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return qZ(R,F,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(Q.set($.label,z),this.clientState.emit(),Z)this.scheduleSync()};async connect($=!0,V=!0){let{connectToHost:Z,scheduleSync:J,store:Q}=this;if(!await Q.seed.load())return;await this.drainApplyQueue();let X=await Q.hosts.list();for(let W of X)await Z(W,$,!1);if(V)J()}disconnect=async()=>{for(let $ of this.connections.values())try{$.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var T0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function C$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function GV($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function c($,...V){if(!GV($))throw Error("Uint8Array expected");if(V.length>0&&!V.includes($.length))throw Error("Uint8Array expected of length "+V+", got length="+$.length)}function KV($,V=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(V&&$.finished)throw Error("Hash#digest() has already been called")}function CZ($,V){c($);let Z=V.outputLen;if($.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function zV($){if(typeof $!=="boolean")throw Error(`boolean expected, not ${$}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var R0=($)=>new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4));var uJ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!uJ)throw Error("Non little-endian hardware is not supported");function lJ($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function T$($){if(typeof $==="string")$=lJ($);else if(GV($))$=A$($);else throw Error("Uint8Array expected, got "+typeof $);return $}function TZ($,V){if(V==null||typeof V!=="object")throw Error("options must be defined");return Object.assign($,V)}function AZ($,V){if($.length!==V.length)return!1;let Z=0;for(let J=0;J<$.length;J++)Z|=$[J]^V[J];return Z===0}var DZ=($,V)=>{function Z(J,...Q){if(c(J),$.nonceLength!==void 0){let z=Q[0];if(!z)throw Error("nonce / iv required");if($.varSizeNonce)c(z);else c(z,$.nonceLength)}let Y=$.tagLength;if(Y&&Q[1]!==void 0)c(Q[1]);let X=V(J,...Q),W=(z,R)=>{if(R!==void 0){if(z!==2)throw Error("cipher output not supported");c(R)}},G=!1;return{encrypt(z,R){if(G)throw Error("cannot encrypt() twice with same key + nonce");return G=!0,c(z),W(X.encrypt.length,R),X.encrypt(z,R)},decrypt(z,R){if(c(z),Y&&z.length<Y)throw Error("invalid ciphertext length: smaller than tagLength="+Y);return W(X.decrypt.length,R),X.decrypt(z,R)}}}return Object.assign(Z,$),Z};function NV($,V,Z=!0){if(V===void 0)return new Uint8Array($);if(V.length!==$)throw Error("invalid output length, expected "+$+", got: "+V.length);if(Z&&!hJ(V))throw Error("invalid output, must be aligned");return V}function hJ($){return $.byteOffset%4===0}function A$($){return Uint8Array.from($)}function G0(...$){for(let V=0;V<$.length;V++)$[V].fill(0)}function D$($=32){if(T0&&typeof T0.getRandomValues==="function")return T0.getRandomValues(new Uint8Array($));if(T0&&typeof T0.randomBytes==="function")return T0.randomBytes($);throw Error("crypto.getRandomValues must be defined")}var jZ=($)=>Uint8Array.from($.split("").map((V)=>V.charCodeAt(0))),pJ=jZ("expand 16-byte k"),nJ=jZ("expand 32-byte k"),cJ=R0(pJ),dJ=R0(nJ);function T($,V){return $<<V|$>>>32-V}function RV($){return $.byteOffset%4===0}var _$=64,rJ=16,LZ=4294967295,_Z=new Uint32Array;function oJ($,V,Z,J,Q,Y,X,W){let G=Q.length,K=new Uint8Array(_$),z=R0(K),R=RV(Q)&&RV(Y),F=R?R0(Q):_Z,U=R?R0(Y):_Z;for(let w=0;w<G;X++){if($(V,Z,J,z,X,W),X>=LZ)throw Error("arx: counter overflow");let I=Math.min(_$,G-w);if(R&&I===_$){let O=w/4;if(w%4!==0)throw Error("arx: invalid block position");for(let P=0,C;P<rJ;P++)C=O+P,U[C]=F[C]^z[P];w+=_$;continue}for(let O=0,P;O<I;O++)P=w+O,Y[P]=Q[P]^K[O];w+=I}}function xZ($,V){let{allowShortKeys:Z,extendNonceFn:J,counterLength:Q,counterRight:Y,rounds:X}=TZ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},V);if(typeof $!=="function")throw Error("core must be a function");return C$(Q),C$(X),zV(Y),zV(Z),(W,G,K,z,R=0)=>{c(W),c(G),c(K);let F=K.length;if(z===void 0)z=new Uint8Array(F);if(c(z),C$(R),R<0||R>=LZ)throw Error("arx: counter overflow");if(z.length<F)throw Error(`arx: output (${z.length}) is shorter than data (${F})`);let U=[],w=W.length,I,O;if(w===32)U.push(I=A$(W)),O=dJ;else if(w===16&&Z)I=new Uint8Array(32),I.set(W),I.set(W,16),O=cJ,U.push(I);else throw Error(`arx: invalid 32-byte key, got length=${w}`);if(!RV(G))U.push(G=A$(G));let P=R0(I);if(J){if(G.length!==24)throw Error("arx: extended nonce must be 24 bytes");J(O,P,R0(G.subarray(0,16)),P),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 H=new Uint8Array(12);H.set(G,Y?0:12-G.length),G=H,U.push(G)}let A=R0(G);return oJ($,O,P,A,K,z,R,X),G0(...U),z}}var r=($,V)=>$[V++]&255|($[V++]&255)<<8;class EZ{constructor($){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,$=T$($),c($,32);let V=r($,0),Z=r($,2),J=r($,4),Q=r($,6),Y=r($,8),X=r($,10),W=r($,12),G=r($,14);this.r[0]=V&8191,this.r[1]=(V>>>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|Y<<12)&255,this.r[5]=Y>>>1&8190,this.r[6]=(Y>>>14|X<<2)&8191,this.r[7]=(X>>>11|W<<5)&8065,this.r[8]=(W>>>8|G<<8)&8191,this.r[9]=G>>>5&127;for(let K=0;K<8;K++)this.pad[K]=r($,16+2*K)}process($,V,Z=!1){let J=Z?0:2048,{h:Q,r:Y}=this,X=Y[0],W=Y[1],G=Y[2],K=Y[3],z=Y[4],R=Y[5],F=Y[6],U=Y[7],w=Y[8],I=Y[9],O=r($,V+0),P=r($,V+2),C=r($,V+4),A=r($,V+6),H=r($,V+8),_=r($,V+10),D=r($,V+12),x=r($,V+14),E=Q[0]+(O&8191),f=Q[1]+((O>>>13|P<<3)&8191),m=Q[2]+((P>>>10|C<<6)&8191),q=Q[3]+((C>>>7|A<<9)&8191),y=Q[4]+((A>>>4|H<<12)&8191),l=Q[5]+(H>>>1&8191),S=Q[6]+((H>>>14|_<<2)&8191),g=Q[7]+((_>>>11|D<<5)&8191),B=Q[8]+((D>>>8|x<<8)&8191),i=Q[9]+(x>>>5|J),j=0,n=j+E*X+f*(5*I)+m*(5*w)+q*(5*U)+y*(5*F);j=n>>>13,n&=8191,n+=l*(5*R)+S*(5*z)+g*(5*K)+B*(5*G)+i*(5*W),j+=n>>>13,n&=8191;let o=j+E*W+f*X+m*(5*I)+q*(5*w)+y*(5*U);j=o>>>13,o&=8191,o+=l*(5*F)+S*(5*R)+g*(5*z)+B*(5*K)+i*(5*G),j+=o>>>13,o&=8191;let e=j+E*G+f*W+m*X+q*(5*I)+y*(5*w);j=e>>>13,e&=8191,e+=l*(5*U)+S*(5*F)+g*(5*R)+B*(5*z)+i*(5*K),j+=e>>>13,e&=8191;let h=j+E*K+f*G+m*W+q*X+y*(5*I);j=h>>>13,h&=8191,h+=l*(5*w)+S*(5*U)+g*(5*F)+B*(5*R)+i*(5*z),j+=h>>>13,h&=8191;let z0=j+E*z+f*K+m*G+q*W+y*X;j=z0>>>13,z0&=8191,z0+=l*(5*I)+S*(5*w)+g*(5*U)+B*(5*F)+i*(5*R),j+=z0>>>13,z0&=8191;let j0=j+E*R+f*z+m*K+q*G+y*W;j=j0>>>13,j0&=8191,j0+=l*X+S*(5*I)+g*(5*w)+B*(5*U)+i*(5*F),j+=j0>>>13,j0&=8191;let L0=j+E*F+f*R+m*z+q*K+y*G;j=L0>>>13,L0&=8191,L0+=l*W+S*X+g*(5*I)+B*(5*w)+i*(5*U),j+=L0>>>13,L0&=8191;let x0=j+E*U+f*F+m*R+q*z+y*K;j=x0>>>13,x0&=8191,x0+=l*G+S*W+g*X+B*(5*I)+i*(5*w),j+=x0>>>13,x0&=8191;let E0=j+E*w+f*U+m*F+q*R+y*z;j=E0>>>13,E0&=8191,E0+=l*K+S*G+g*W+B*X+i*(5*I),j+=E0>>>13,E0&=8191;let f0=j+E*I+f*w+m*U+q*F+y*R;j=f0>>>13,f0&=8191,f0+=l*z+S*K+g*G+B*W+i*X,j+=f0>>>13,f0&=8191,j=(j<<2)+j|0,j=j+n|0,n=j&8191,j=j>>>13,o+=j,Q[0]=n,Q[1]=o,Q[2]=e,Q[3]=h,Q[4]=z0,Q[5]=j0,Q[6]=L0,Q[7]=x0,Q[8]=E0,Q[9]=f0}finalize(){let{h:$,pad:V}=this,Z=new Uint16Array(10),J=$[1]>>>13;$[1]&=8191;for(let X=2;X<10;X++)$[X]+=J,J=$[X]>>>13,$[X]&=8191;$[0]+=J*5,J=$[0]>>>13,$[0]&=8191,$[1]+=J,J=$[1]>>>13,$[1]&=8191,$[2]+=J,Z[0]=$[0]+5,J=Z[0]>>>13,Z[0]&=8191;for(let X=1;X<10;X++)Z[X]=$[X]+J,J=Z[X]>>>13,Z[X]&=8191;Z[9]-=8192;let Q=(J^1)-1;for(let X=0;X<10;X++)Z[X]&=Q;Q=~Q;for(let X=0;X<10;X++)$[X]=$[X]&Q|Z[X];$[0]=($[0]|$[1]<<13)&65535,$[1]=($[1]>>>3|$[2]<<10)&65535,$[2]=($[2]>>>6|$[3]<<7)&65535,$[3]=($[3]>>>9|$[4]<<4)&65535,$[4]=($[4]>>>12|$[5]<<1|$[6]<<14)&65535,$[5]=($[6]>>>2|$[7]<<11)&65535,$[6]=($[7]>>>5|$[8]<<8)&65535,$[7]=($[8]>>>8|$[9]<<5)&65535;let Y=$[0]+V[0];$[0]=Y&65535;for(let X=1;X<8;X++)Y=($[X]+V[X]|0)+(Y>>>16)|0,$[X]=Y&65535;G0(Z)}update($){KV(this);let{buffer:V,blockLen:Z}=this;$=T$($);let J=$.length;for(let Q=0;Q<J;){let Y=Math.min(Z-this.pos,J-Q);if(Y===Z){for(;Z<=J-Q;Q+=Z)this.process($,Q);continue}if(V.set($.subarray(Q,Q+Y),this.pos),this.pos+=Y,Q+=Y,this.pos===Z)this.process(V,0,!1),this.pos=0}return this}destroy(){G0(this.h,this.r,this.buffer,this.pad)}digestInto($){KV(this),CZ($,this),this.finished=!0;let{buffer:V,h:Z}=this,{pos:J}=this;if(J){V[J++]=1;for(;J<16;J++)V[J]=0;this.process(V,0,!0)}this.finalize();let Q=0;for(let Y=0;Y<8;Y++)$[Q++]=Z[Y]>>>0,$[Q++]=Z[Y]>>>8;return $}digest(){let{buffer:$,outputLen:V}=this;this.digestInto($);let Z=$.slice(0,V);return this.destroy(),Z}}function aJ($){let V=(J,Q)=>$(Q).update(T$(J)).digest(),Z=$(new Uint8Array(32));return V.outputLen=Z.outputLen,V.blockLen=Z.blockLen,V.create=(J)=>$(J),V}var FV=aJ(($)=>new EZ($));function sJ($,V,Z,J,Q,Y=20){let X=$[0],W=V[0],G=V[1],K=V[2],z=V[3],R=$[1],F=Z[0],U=Z[1],w=Q,I=0,O=$[2],P=V[4],C=V[5],A=V[6],H=V[7],_=$[3],D=X,x=W,E=G,f=K,m=z,q=R,y=F,l=U,S=w,g=I,B=O,i=P,j=C,n=A,o=H,e=_;for(let z0=0;z0<Y;z0+=2)m^=T(D+j|0,7),S^=T(m+D|0,9),j^=T(S+m|0,13),D^=T(j+S|0,18),g^=T(q+x|0,7),n^=T(g+q|0,9),x^=T(n+g|0,13),q^=T(x+n|0,18),o^=T(B+y|0,7),E^=T(o+B|0,9),y^=T(E+o|0,13),B^=T(y+E|0,18),f^=T(e+i|0,7),l^=T(f+e|0,9),i^=T(l+f|0,13),e^=T(i+l|0,18),x^=T(D+f|0,7),E^=T(x+D|0,9),f^=T(E+x|0,13),D^=T(f+E|0,18),y^=T(q+m|0,7),l^=T(y+q|0,9),m^=T(l+y|0,13),q^=T(m+l|0,18),i^=T(B+g|0,7),S^=T(i+B|0,9),g^=T(S+i|0,13),B^=T(g+S|0,18),j^=T(e+o|0,7),n^=T(j+e|0,9),o^=T(n+j|0,13),e^=T(o+n|0,18);let h=0;J[h++]=X+D|0,J[h++]=W+x|0,J[h++]=G+E|0,J[h++]=K+f|0,J[h++]=z+m|0,J[h++]=R+q|0,J[h++]=F+y|0,J[h++]=U+l|0,J[h++]=w+S|0,J[h++]=I+g|0,J[h++]=O+B|0,J[h++]=P+i|0,J[h++]=C+j|0,J[h++]=A+n|0,J[h++]=H+o|0,J[h++]=_+e|0}function tJ($,V,Z,J){let Q=$[0],Y=V[0],X=V[1],W=V[2],G=V[3],K=$[1],z=Z[0],R=Z[1],F=Z[2],U=Z[3],w=$[2],I=V[4],O=V[5],P=V[6],C=V[7],A=$[3];for(let _=0;_<20;_+=2)G^=T(Q+O|0,7),F^=T(G+Q|0,9),O^=T(F+G|0,13),Q^=T(O+F|0,18),U^=T(K+Y|0,7),P^=T(U+K|0,9),Y^=T(P+U|0,13),K^=T(Y+P|0,18),C^=T(w+z|0,7),X^=T(C+w|0,9),z^=T(X+C|0,13),w^=T(z+X|0,18),W^=T(A+I|0,7),R^=T(W+A|0,9),I^=T(R+W|0,13),A^=T(I+R|0,18),Y^=T(Q+W|0,7),X^=T(Y+Q|0,9),W^=T(X+Y|0,13),Q^=T(W+X|0,18),z^=T(K+G|0,7),R^=T(z+K|0,9),G^=T(R+z|0,13),K^=T(G+R|0,18),I^=T(w+U|0,7),F^=T(I+w|0,9),U^=T(F+I|0,13),w^=T(U+F|0,18),O^=T(A+C|0,7),P^=T(O+A|0,9),C^=T(P+O|0,13),A^=T(C+P|0,18);let H=0;J[H++]=Q,J[H++]=K,J[H++]=w,J[H++]=A,J[H++]=z,J[H++]=R,J[H++]=F,J[H++]=U}var IV=xZ(sJ,{counterRight:!0,extendNonceFn:tJ}),UV=DZ({blockSize:64,nonceLength:24,tagLength:16},($,V)=>{return{encrypt(Z,J){J=NV(Z.length+32,J,!1);let Q=J.subarray(0,32),Y=J.subarray(32);J.set(Z,32),G0(Q),IV($,V,J,J);let X=FV(Y,Q);return J.set(X,16),G0(J.subarray(0,16),X),J.subarray(16)},decrypt(Z,J){c(Z),J=NV(Z.length+32,J,!1);let Q=J.subarray(0,32),Y=J.subarray(32,48),X=J.subarray(48);J.set(Z,32),G0(Q);let W=IV($,V,Q,Q),G=FV(X,W);if(!AZ(Y,G))throw Error("invalid tag");return IV($,V,J.subarray(16),J.subarray(16)),G0(Q,Y,G),X}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function eJ($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function a0($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function A0($,...V){if(!eJ($))throw Error("Uint8Array expected");if(V.length>0&&!V.includes($.length))throw Error("Uint8Array expected of length "+V+", got length="+$.length)}function s0($,V=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(V&&$.finished)throw Error("Hash#digest() has already been called")}function j$($,V){A0($);let Z=V.outputLen;if($.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function fZ($){return new Uint8Array($.buffer,$.byteOffset,$.byteLength)}function y0($){return new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4))}function i0(...$){for(let V=0;V<$.length;V++)$[V].fill(0)}function t0($,V){return $<<32-V|$>>>V}var SZ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function kZ($){return $<<24&4278190080|$<<8&16711680|$>>>8&65280|$>>>24&255}var BZ=SZ?($)=>$:($)=>kZ($);function $Q($){for(let V=0;V<$.length;V++)$[V]=kZ($[V]);return $}var s=SZ?($)=>$:$Q;function VQ($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function u0($){if(typeof $==="string")$=VQ($);return A0($),$}class wV{}function mZ($){let V=(J,Q)=>$(Q).update(u0(J)).digest(),Z=$({});return V.outputLen=Z.outputLen,V.blockLen=Z.blockLen,V.create=(J)=>$(J),V}var gZ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var L$=BigInt(4294967295),vZ=BigInt(32);function MV($,V=!1){if(V)return{h:Number($&L$),l:Number($>>vZ&L$)};return{h:Number($>>vZ&L$)|0,l:Number($&L$)|0}}function F0($,V,Z,J,Q){return $=$+V+Q|0,J=t0(J^$,16),Z=Z+J|0,V=t0(V^Z,12),{a:$,b:V,c:Z,d:J}}function I0($,V,Z,J,Q){return $=$+V+Q|0,J=t0(J^$,8),Z=Z+J|0,V=t0(V^Z,7),{a:$,b:V,c:Z,d:J}}class OV extends wV{constructor($,V){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,a0($),a0(V),this.blockLen=$,this.outputLen=V,this.buffer=new Uint8Array($),this.buffer32=y0(this.buffer)}update($){s0(this),$=u0($),A0($);let{blockLen:V,buffer:Z,buffer32:J}=this,Q=$.length,Y=$.byteOffset,X=$.buffer;for(let W=0;W<Q;){if(this.pos===V)s(J),this.compress(J,0,!1),s(J),this.pos=0;let G=Math.min(V-this.pos,Q-W),K=Y+W;if(G===V&&!(K%4)&&W+G<Q){let z=new Uint32Array(X,K,Math.floor((Q-W)/4));s(z);for(let R=0;W+V<Q;R+=J.length,W+=V)this.length+=V,this.compress(z,R,!1);s(z);continue}Z.set($.subarray(W,W+G),this.pos),this.pos+=G,this.length+=G,W+=G}return this}digestInto($){s0(this),j$($,this);let{pos:V,buffer32:Z}=this;this.finished=!0,i0(this.buffer.subarray(V)),s(Z),this.compress(Z,0,!0),s(Z);let J=y0($);this.get().forEach((Q,Y)=>J[Y]=BZ(Q))}digest(){let{buffer:$,outputLen:V}=this;this.digestInto($);let Z=$.slice(0,V);return this.destroy(),Z}_cloneInto($){let{buffer:V,length:Z,finished:J,destroyed:Q,outputLen:Y,pos:X}=this;return $||($=new this.constructor({dkLen:Y})),$.set(...this.get()),$.buffer.set(V),$.destroyed=Q,$.finished=J,$.length=Z,$.pos=X,$.outputLen=Y,$}clone(){return this._cloneInto()}}function HV($,V,Z,J,Q,Y,X,W,G,K,z,R,F,U,w,I,O,P,C,A){let H=0;for(let _=0;_<J;_++)({a:Q,b:G,c:F,d:O}=F0(Q,G,F,O,Z[V+$[H++]])),{a:Q,b:G,c:F,d:O}=I0(Q,G,F,O,Z[V+$[H++]]),{a:Y,b:K,c:U,d:P}=F0(Y,K,U,P,Z[V+$[H++]]),{a:Y,b:K,c:U,d:P}=I0(Y,K,U,P,Z[V+$[H++]]),{a:X,b:z,c:w,d:C}=F0(X,z,w,C,Z[V+$[H++]]),{a:X,b:z,c:w,d:C}=I0(X,z,w,C,Z[V+$[H++]]),{a:W,b:R,c:I,d:A}=F0(W,R,I,A,Z[V+$[H++]]),{a:W,b:R,c:I,d:A}=I0(W,R,I,A,Z[V+$[H++]]),{a:Q,b:K,c:w,d:A}=F0(Q,K,w,A,Z[V+$[H++]]),{a:Q,b:K,c:w,d:A}=I0(Q,K,w,A,Z[V+$[H++]]),{a:Y,b:z,c:I,d:O}=F0(Y,z,I,O,Z[V+$[H++]]),{a:Y,b:z,c:I,d:O}=I0(Y,z,I,O,Z[V+$[H++]]),{a:X,b:R,c:F,d:P}=F0(X,R,F,P,Z[V+$[H++]]),{a:X,b:R,c:F,d:P}=I0(X,R,F,P,Z[V+$[H++]]),{a:W,b:G,c:U,d:C}=F0(W,G,U,C,Z[V+$[H++]]),{a:W,b:G,c:U,d:C}=I0(W,G,U,C,Z[V+$[H++]]);return{v0:Q,v1:Y,v2:X,v3:W,v4:G,v5:K,v6:z,v7:R,v8:F,v9:U,v10:w,v11:I,v12:O,v13:P,v14:C,v15:A}}var K0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},U0=gZ.slice(),bZ=(()=>{let $=Array.from({length:16},(J,Q)=>Q),V=(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=$;J<7;J++,Q=V(Q))Z.push(...Q);return Uint8Array.from(Z)})();class qV extends OV{constructor($={},V=0){super(64,$.dkLen===void 0?32:$.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}=$,Q=J!==void 0;if(Z!==void 0){if(Q)throw Error('Only "key" or "context" can be specified at same time');let Y=u0(Z).slice();A0(Y,32),this.IV=y0(Y),s(this.IV),this.flags=V|K0.KEYED_HASH}else if(Q){let Y=u0(J),X=new qV({dkLen:32},K0.DERIVE_KEY_CONTEXT).update(Y).digest();this.IV=y0(X),s(this.IV),this.flags=V|K0.DERIVE_KEY_MATERIAL}else this.IV=U0.slice(),this.flags=V;this.state=this.IV.slice(),this.bufferOut=fZ(this.bufferOut32)}get(){return[]}set(){}b2Compress($,V,Z,J=0){let{state:Q,pos:Y}=this,{h:X,l:W}=MV(BigInt($),!0),{v0:G,v1:K,v2:z,v3:R,v4:F,v5:U,v6:w,v7:I,v8:O,v9:P,v10:C,v11:A,v12:H,v13:_,v14:D,v15:x}=HV(bZ,J,Z,7,Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7],U0[0],U0[1],U0[2],U0[3],X,W,Y,V);Q[0]=G^O,Q[1]=K^P,Q[2]=z^C,Q[3]=R^A,Q[4]=F^H,Q[5]=U^_,Q[6]=w^D,Q[7]=I^x}compress($,V=0,Z=!1){let J=this.flags;if(!this.chunkPos)J|=K0.CHUNK_START;if(this.chunkPos===15||Z)J|=K0.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 Y,X=this.chunksDone+1;Z||!(X&1);X>>=1){if(!(Y=this.stack.pop()))break;this.buffer32.set(Y,0),this.buffer32.set(Q,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|K0.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($){$=super._cloneInto($);let{IV:V,flags:Z,state:J,chunkPos:Q,posOut:Y,chunkOut:X,stack:W,chunksDone:G}=this;return $.state.set(J.slice()),$.stack=W.map((K)=>Uint32Array.from(K)),$.IV.set(V),$.flags=Z,$.chunkPos=Q,$.chunksDone=G,$.posOut=Y,$.chunkOut=X,$.enableXOF=this.enableXOF,$.bufferOut32.set(this.bufferOut32),$}destroy(){this.destroyed=!0,i0(this.state,this.buffer32,this.IV,this.bufferOut32),i0(...this.stack)}b2CompressOut(){let{state:$,pos:V,flags:Z,buffer32:J,bufferOut32:Q}=this,{h:Y,l:X}=MV(BigInt(this.chunkOut++));s(J);let{v0:W,v1:G,v2:K,v3:z,v4:R,v5:F,v6:U,v7:w,v8:I,v9:O,v10:P,v11:C,v12:A,v13:H,v14:_,v15:D}=HV(bZ,0,J,7,$[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],U0[0],U0[1],U0[2],U0[3],X,Y,V,Z);Q[0]=W^I,Q[1]=G^O,Q[2]=K^P,Q[3]=z^C,Q[4]=R^A,Q[5]=F^H,Q[6]=U^_,Q[7]=w^D,Q[8]=$[0]^I,Q[9]=$[1]^O,Q[10]=$[2]^P,Q[11]=$[3]^C,Q[12]=$[4]^A,Q[13]=$[5]^H,Q[14]=$[6]^_,Q[15]=$[7]^D,s(J),s(Q),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,i0(this.buffer.subarray(this.pos));let $=this.flags|K0.ROOT;if(this.stack.length)$|=K0.PARENT,s(this.buffer32),this.compress(this.buffer32,0,!0),s(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else $|=(!this.chunkPos?K0.CHUNK_START:0)|K0.CHUNK_END;this.flags=$,this.b2CompressOut()}writeInto($){s0(this,!1),A0($),this.finish();let{blockLen:V,bufferOut:Z}=this;for(let J=0,Q=$.length;J<Q;){if(this.posOut>=V)this.b2CompressOut();let Y=Math.min(V-this.posOut,Q-J);$.set(Z.subarray(this.posOut,this.posOut+Y),J),this.posOut+=Y,J+=Y}return $}xofInto($){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto($)}xof($){return a0($),this.xofInto(new Uint8Array($))}digestInto($){if(j$($,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto($),this.destroy(),$}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var yZ=mZ(($)=>new qV($));var PV=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function iZ($){let V=new Uint8Array(PV.length+32);return V.set(PV),V.set($.subarray(0,32),PV.length),V}function uZ($){return typeof $==="string"?new TextEncoder().encode($):$}function l0($){let V=new ArrayBuffer($.byteLength);return new Uint8Array(V).set($),V}class CV{verifyKeys=new Map;signKeys=new Map;async genRandomBytes($){return D$($)}async gen256BitSecureRandomSeed(){return D$(32)}async encryptXSalsa20Poly1305Combined($,V){let Z=D$(24),Q=UV(V,Z).encrypt($);return new Uint8Array([...Z,...Q])}async decryptXSalsa20Poly1305Combined($,V){let Z=$.slice(0,24),J=$.slice(24);return UV(V,Z).decrypt(J)}async deriveEd25519KeyPair($){let V=$,Z=iZ(V),J=await globalThis.crypto.subtle.importKey("pkcs8",l0(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 Y=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:Q.x},{name:"Ed25519"},!0,["verify"]),X=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",Y)),W=new Uint8Array(64);return W.set(V,0),W.set(X,32),this.signKeys.set(X0(V),J),this.verifyKeys.set(X0(X),Y),{keyType:"ed25519",privateKey:W,publicKey:X}}async importSignKey($){let V=$.subarray(0,32),Z=X0(V),J=this.signKeys.get(Z);if(J)return J;let Q=iZ(V),Y=await globalThis.crypto.subtle.importKey("pkcs8",l0(Q),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Z,Y),Y}async importVerifyKey($){let V=X0($),Z=this.verifyKeys.get(V);if(Z)return Z;let J=await globalThis.crypto.subtle.importKey("raw",l0($),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set(V,J),J}async signEd25519($,V){let Z=uZ($),J=await this.importSignKey(V),Q=await globalThis.crypto.subtle.sign({name:"Ed25519"},J,l0(Z));return new Uint8Array(Q)}async checkSigEd25519($,V,Z){let J=uZ(V);try{let Q=await this.importVerifyKey(Z);return await globalThis.crypto.subtle.verify({name:"Ed25519"},Q,l0($),l0(J))}catch{return!1}}async blake3($){return yZ($)}}var ZQ=new CV,D0=ZQ;class TV{db;constructor($){this.db=$}async enq($){let V=[...$];if(V.length===0)return;let Z=this.db.transaction(Q0,"readwrite"),J=Z.objectStore(Q0);return new Promise((Q,Y)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>Y(Z.error);for(let X of V){let W=`${X.host}:${X.seq}`;J.put(X,W)}})}async deq($,V){let Z=[...V];if(Z.length===0)return;let J=this.db.transaction(Q0,"readwrite"),Q=J.objectStore(Q0);return new Promise((Y,X)=>{J.oncomplete=()=>Y(),J.onerror=()=>X(J.error);for(let W of Z){let G=`${$}:${W}`;Q.delete(G)}})}async list(){let V=this.db.transaction(Q0,"readonly").objectStore(Q0);return new Promise((Z,J)=>{let Q=V.getAll();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async count(){let V=this.db.transaction(Q0,"readonly").objectStore(Q0);return new Promise((Z,J)=>{let Q=V.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let $=this.db.transaction(Q0,"readwrite"),V=$.objectStore(Q0);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),V.clear()})}}function lZ($){return{label:$.label,handle:new URL($.handle),idx:$.idx,lastSeq:$.lastSeq||0,numBags:$.numBags||0,numDupes:$.numDupes||0,clockOffset:$.clockOffset,subscription:$.subscription}}function JQ($,V){let Z={...$};if(V.setLastSeq!==void 0)Z.lastSeq=V.setLastSeq;else if(V.lastSeq!==void 0){let J=Z.lastSeq||0;if(V.lastSeq>J)Z.lastSeq=V.lastSeq}if(V.numBags!==void 0)Z.numBags=V.numBags;else if(V.bagDelta!==void 0&&V.bagDelta!==0)Z.numBags=(Z.numBags||0)+V.bagDelta;if(V.numDupes!==void 0)Z.numDupes=V.numDupes;else if(V.dupeDelta!==void 0&&V.dupeDelta!==0)Z.numDupes=(Z.numDupes||0)+V.dupeDelta;return Z}class AV{db;constructor($){this.db=$}async add($){return this.put({...$,lastSeq:0,numBags:0,numDupes:0})}async put($){let V={...$,handle:$.handle.toString(),lastSeq:$.lastSeq??0,numBags:$.numBags??0,numDupes:$.numDupes??0},Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,Y)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>Y(Z.error),J.put(V)})}async touch($,V){return this.recordStats($,{lastSeq:V})}async recordStats($,V){let Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,Y)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>Y(Z.error);let X=J.get($);X.onsuccess=()=>{let W=X.result;if(!W)return;J.put(JQ(W,V))}})}async get($){let Z=this.db.transaction(t,"readonly").objectStore(t);return new Promise((J,Q)=>{let Y=Z.get($);Y.onsuccess=()=>{let X=Y.result;if(!X)J(void 0);else J(lZ(X))},Y.onerror=()=>Q(Y.error)})}async set($,V){let Z=await this.get($);if(!Z)return 13;try{return await this.put({...Z,...V}),0}catch{return 18}}async del($){let V=this.db.transaction(t,"readwrite"),Z=V.objectStore(t);return new Promise((J,Q)=>{V.oncomplete=()=>J(),V.onerror=()=>Q(V.error),Z.delete($)})}async list(){let V=this.db.transaction(t,"readonly").objectStore(t);return new Promise((Z,J)=>{let Q=V.getAll();Q.onsuccess=()=>{let Y=Q.result;Z(Y.map(lZ))},Q.onerror=()=>J(Q.error)})}async wipe(){let $=this.db.transaction(t,"readwrite"),V=$.objectStore(t);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),V.clear()})}}class DV{crypto;db;constructor($,V){this.crypto=V;this.db=$}async add($){let V=this.db.transaction(u,"readwrite"),Z=V.objectStore(u);return new Promise((J)=>{if($.length===0){J([]);return}let Q=Array($.length).fill(0);V.oncomplete=()=>J(Q),V.onerror=()=>{for(let Y=0;Y<Q.length;Y++)Q[Y]=18;J(Q)};for(let Y=0;Y<$.length;Y++){let{key:X,data:W}=$[Y],G=k(X),K=Z.put(W,G);K.onerror=(z)=>{z.preventDefault(),Q[Y]=18}}})}async del($){let V=[...$];if(V.length===0)return;let Z=this.db.transaction(u,"readwrite"),J=Z.objectStore(u);return new Promise((Q,Y)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>Y(Z.error);for(let X of V){let W=k(X);J.delete(W)}})}async get($){let Z=this.db.transaction(u,"readonly").objectStore(u);return new Promise((J,Q)=>{let Y=k($),X=Z.get(Y);X.onsuccess=async()=>{let W=X.result;if(W)J(await P$($,W,this.crypto));else J(void 0)},X.onerror=()=>Q(X.error)})}async has($){return await this.get($)!==void 0}async list($){let V=$?.apld,Z=$?.body!==!1,Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Y,X)=>{let W=[],G=V===void 0?Q.openCursor():Q.index(e0).openCursor(IDBKeyRange.only(V));G.onsuccess=(K)=>{let z=K.target.result;if(z){let R=V===void 0?z.key:z.primaryKey,F=z.value;W.push({hash:N0(R),data:F}),z.continue()}else Promise.all(W.map(({hash:R,data:F})=>P$(R,F,this.crypto,{body:Z}))).then(Y).catch(X)},G.onerror=()=>X(G.error)})}async count($){let Z=this.db.transaction(u,"readonly").objectStore(u);return new Promise((J,Q)=>{let Y=$===void 0?Z.count():Z.index(e0).count(IDBKeyRange.only($));Y.onsuccess=()=>J(Y.result),Y.onerror=()=>Q(Y.error)})}async listKeys(){let V=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let Q=[],Y=V.openKeyCursor();Y.onsuccess=(X)=>{let W=X.target.result;if(W)Q.push(N0(W.key)),W.continue();else Z(Q)},Y.onerror=()=>J(Y.error)})}async last($){let Z=this.db.transaction(u,"readonly").objectStore(u);return new Promise((J,Q)=>{let Y,X=Z.openCursor();X.onsuccess=async(W)=>{let G=W.target.result;if(G){let{key:K,value:z}=G;if(V0($,z.eid)){if(!Y||(z.ctr??0)>(Y.data.ctr??0)||(z.ctr??0)===(Y.data.ctr??0)&&(z.off??0)>(Y.data.off??0))Y={key:K,data:z}}G.continue()}else if(Y){let K=N0(Y.key);J(await P$(K,Y.data,this.crypto))}else J(void 0)},X.onerror=()=>Q(X.error)})}async markApplied($){let V=[...$];if(V.length===0)return;let Z=this.db.transaction(u,"readwrite"),J=Z.objectStore(u);return new Promise((Q,Y)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>Y(Z.error);for(let X of V){let W=k(X),G=J.get(W);G.onsuccess=()=>{let K=G.result;if(!K)return;ZV(K,q$),J.put(K,W)},G.onerror=(K)=>{K.preventDefault()}}})}async markFailed($){let V=[...$];if(V.length===0)return;let Z=this.db.transaction(u,"readwrite"),J=Z.objectStore(u);return new Promise((Q,Y)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>Y(Z.error);for(let{key:X,err:W}of V){let G=k(X),K=J.get(G);K.onsuccess=()=>{let z=K.result;if(!z)return;ZV(z,v0,W),J.put(z,G)},K.onerror=(z)=>{z.preventDefault()}}})}async wipe(){let $=this.db.transaction(u,"readwrite"),V=$.objectStore(u);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),V.clear()})}}class x${#J;#$;constructor($,V){this.#J=$,this.#$=V}deriveCipher($,V){let Z=$.slice(),J=(X)=>this.#Q(Z,X),Q=(X)=>this.#Y(Z,X);return{encrypt:Object.freeze({encrypt:J}),decrypt:Object.freeze({decrypt:Q}),both:Object.freeze({encrypt:J,decrypt:Q})}[V]}async deriveIdentity($,V=0){let Z=$,J=V,Q=await this.#Z(Z,J);return Object.freeze({publicKey:Q.publicKey,sign:(Y)=>this.#W(Z,J,Y),kdmFor:(Y)=>this.#G(Z,J,Y)})}async#Q($,V){let Z=await this.#V($);return this.#$.encryptXSalsa20Poly1305Combined(V,Z)}async#Y($,V){let Z=await this.#V($);return this.#$.decryptXSalsa20Poly1305Combined(V,Z)}async#V($){return this.#$.blake3(G$(this.#J,$))}async#X($,V){let Z=new TextEncoder().encode($),J=new Uint8Array(8);return new DataView(J.buffer).setBigUint64(0,BigInt(V),!1),await this.#V(G$(Z,J))}async#Z($,V){let Z=await this.#X($,V);return this.#$.deriveEd25519KeyPair(Z)}async#W($,V,Z){let J=await this.#Z($,V);return this.#$.signEd25519(Z,J.privateKey)}async#G($,V,Z){let J=await this.#Z($,V),Q=G$(J.privateKey,Z);return(await this.#$.blake3(Q)).slice(0,O0)}}class _V{enclave;db;constructor($){this.db=$}async save($){let V=X0($),Z=this.db.transaction(w0,"readwrite"),J=Z.objectStore(w0);return new Promise((Q,Y)=>{Z.oncomplete=()=>{this.enclave=new x$($,D0),Q(this.enclave)},Z.onerror=()=>Y(Z.error),J.put(V,"seed")})}async load(){if(this.enclave)return this.enclave;let V=this.db.transaction(w0,"readonly").objectStore(w0);return new Promise((Z,J)=>{let Q=V.get("seed");Q.onsuccess=()=>{let Y=Q.result;if(!Y)Z(void 0);else{let X=W$(Y);this.enclave=new x$(X,D0),Z(this.enclave)}},Q.onerror=()=>J(Q.error)})}async wipe(){this.enclave=void 0;let $=this.db.transaction(w0,"readwrite"),V=$.objectStore(w0);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),V.delete("seed")})}}class jV{db;constructor($){this.db=$}async enq($,V){let Z=[...V];if(Z.length===0)return;let J=this.db.transaction(Y0,"readwrite"),Q=J.objectStore(Y0);return new Promise((Y,X)=>{J.oncomplete=()=>Y(),J.onerror=()=>X(J.error);for(let W of Z){let G=X0(W);Q.put({host:$,hash:G})}})}async deq($,V){let Z=[...V];if(Z.length===0)return;let J=this.db.transaction(Y0,"readwrite"),Q=J.objectStore(Y0);return new Promise((Y,X)=>{J.oncomplete=()=>Y(),J.onerror=()=>X(J.error);for(let W of Z){let G=X0(W);Q.delete([$,G])}})}async list($){let Z=this.db.transaction(Y0,"readonly").objectStore(Y0);return new Promise((J,Q)=>{let Y=Z.getAll();Y.onsuccess=()=>{let W=Y.result.filter((G)=>G.host===$).map((G)=>G.hash);J(W.map((G)=>W$(G)))},Y.onerror=()=>Q(Y.error)})}async count(){let V=this.db.transaction(Y0,"readonly").objectStore(Y0);return new Promise((Z,J)=>{let Q=V.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let $=this.db.transaction(Y0,"readwrite"),V=$.objectStore(Y0);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),V.clear()})}}var w0="seedMeta",t="hosts",Y0="uploadQueue",Q0="downloadQueue",u="messages",e0="apld",hZ=3;class nZ{seed;hosts;uploads;downloads;messages;db;constructor($,V){this.db=$,this.seed=new _V($),this.hosts=new AV($),this.uploads=new jV($),this.downloads=new TV($),this.messages=new DV($,V)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}var pZ="diplomatic-store-db";async function QQ(){return new Promise(($,V)=>{let Z=indexedDB.open(pZ,hZ);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!J.objectStoreNames.contains(w0))J.createObjectStore(w0);if(!J.objectStoreNames.contains(t))J.createObjectStore(t,{keyPath:"label"});if(!J.objectStoreNames.contains(Y0))J.createObjectStore(Y0,{keyPath:["host","hash"]});if(!J.objectStoreNames.contains(Q0))J.createObjectStore(Q0);let Y;if(!J.objectStoreNames.contains(u))Y=J.createObjectStore(u);else{if(!Q)throw Error("missing upgrade transaction for messages store");Y=Q.objectStore(u)}if(!Y.indexNames.contains(e0))Y.createIndex(e0,"apld",{unique:!1})},Z.onblocked=()=>{console.warn(`[DIPLOMATIC] protocol store IDB upgrade blocked (${pZ} → v${hZ}); waiting for other connections to close`)},Z.onsuccess=()=>{let J=Z.result;J.onversionchange=()=>{J.close()},$(J)},Z.onerror=()=>V(Z.error??Error("protocol store IndexedDB open failed"))})}async function cZ($){let V=await QQ();if(typeof navigator<"u"&&navigator.storage?.persist)try{await Promise.race([navigator.storage.persist(),new Promise((Z)=>{setTimeout(()=>Z(!1),2000)})])}catch{}return new nZ(V,$)}class LV{client;entDB;post;whenReady;resolveReady;rejectReady;constructor($){this.post=$,this.whenReady=new Promise((V,Z)=>{this.resolveReady=V,this.rejectReady=Z})}async init(){try{let $=await cZ(D0),V=await WZ({cache:!1}),Z=new U$(V.apply,()=>V.clear(),(Y)=>{if(Y.length<1)return;this.post({kind:"dirty",eids:Y.map((X)=>X.slice())})}),J=Z.clear;Z.clear=async()=>{let Y=await J();if(Y===0)this.post({kind:"wiped"});return Y};let Q=new WV(new v$,Z,$,tV,D0);this.client=Q,this.entDB=V,Q.clientState.listen(()=>{this.emitClientState()}),Q.xferState.listen(()=>{this.emitXferState()}),await this.emitClientState(),await this.emitXferState(),this.post({kind:"ready"}),this.markReady()}catch($){let V=$ instanceof Error?$:Error(String($));throw this.post({kind:"initError",message:V.message}),this.failReady(V),V}}markReady(){let $=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,$)$()}failReady($){let V=this.rejectReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V($)}requireClient(){if(!this.client)throw Error("WorkerRuntime not initialized");return this.client}async emitClientState(){let $=this.client;if(!$)return;let V=await $.clientState.get();this.post({kind:"clientState",state:V})}async emitXferState(){let $=this.client;if(!$)return;let V=await $.xferState.get();this.post({kind:"xferState",state:V})}hostFromSerialized($){return{handle:new URL($.handle),label:$.label,idx:$.idx}}async handle($){await this.whenReady;let V=this.requireClient();switch($.op){case"ping":return"pong";case"setSeed":{await V.setSeed(YQ($.seed));return}case"link":{await V.link(this.hostFromSerialized($.host),$.connect??!0);return}case"unlink":{await V.unlink($.label);return}case"connect":{await V.connect($.listen??!0,$.sync??!0);return}case"disconnect":{await V.disconnect();return}case"sync":return await V.sync();case"rebuild":return await V.rebuild({checkHost:$.checkHost??!0});case"reconcile":{let[Z,J]=await V.reconcile($.hostLabel,{pull:$.pull,push:$.push,sync:$.sync});if(J!==0)throw new W0(J);if(!Z)throw new W0(12);return Z}case"msgcheck":return await V.msgcheck();case"entcheck":{let Z=this.entDB;if(!Z)throw new W0(12);let[J,Q]=await Z.checksum(D0);if(Q!==0)throw new W0(Q);if(!J)throw new W0(12);return J}case"wipe":{await V.wipe();return}case"import":{let Z=$.bytes.slice(),J=new Blob([Z]),Q=new File([J],"import.dip");return await V.import(Q)}case"export":{let[Z,J]=await V.exportBytes();if(J!==0)throw new W0(J);if(!Z)throw new W0(12);return Z}case"getClientState":return await V.clientState.get();case"getXferState":return await V.xferState.get();default:{let Z=$;throw Error("unknown worker command")}}}}class W0 extends Error{status;constructor($){super(`WorkerStatusError: ${L[$]}`);this.status=$;this.name="WorkerStatusError"}}function xV($,V){return{kind:"reply",id:$,ok:!0,result:V}}function EV($,V){return{kind:"reply",id:$,ok:!1,status:V}}function YQ($){if($.length!==32)throw new W0(10);return $}var _0=globalThis,dZ=new LV(($,V)=>{if(V&&V.length>0)_0.postMessage($,V);else _0.postMessage($)});_0.onmessage=($)=>{let V=$.data;if(!BV(V))return;XQ(V)};async function XQ($){try{let V=await dZ.handle($);if(($.op==="export"||$.op==="msgcheck"||$.op==="entcheck"||$.op==="reconcile")&&V instanceof Uint8Array){let Z=V.slice();_0.postMessage(xV($.id,Z),[Z.buffer]);return}_0.postMessage(xV($.id,V))}catch(V){if(V instanceof W0){_0.postMessage(EV($.id,V.status));return}console.error("worker command failed",V),_0.postMessage(EV($.id,12))}}dZ.init().catch(($)=>{console.error("worker init failed",$)});
1
+ var M0=64;var SV=32,O0=8;var $$=32;var kV=30000,BV=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 mV($){if(!$||typeof $!=="object")return!1;if(!("op"in $)||!("id"in $))return!1;return typeof $.op==="string"&&typeof $.id==="number"}function gV($){let V=$.length,Z=0,J=0;while(J<V){let Q=$.charCodeAt(J++);if((Q&4294967168)===0){Z++;continue}else if((Q&4294965248)===0)Z+=2;else{if(Q>=55296&&Q<=56319){if(J<V){let Y=$.charCodeAt(J);if((Y&64512)===56320)++J,Q=((Q&1023)<<10)+(Y&1023)+65536}}if((Q&4294901760)===0)Z+=3;else Z+=4}}return Z}function rZ($,V,Z){let J=$.length,Q=Z,Y=0;while(Y<J){let X=$.charCodeAt(Y++);if((X&4294967168)===0){V[Q++]=X;continue}else if((X&4294965248)===0)V[Q++]=X>>6&31|192;else{if(X>=55296&&X<=56319){if(Y<J){let W=$.charCodeAt(Y);if((W&64512)===56320)++Y,X=((X&1023)<<10)+(W&1023)+65536}}if((X&4294901760)===0)V[Q++]=X>>12&15|224,V[Q++]=X>>6&63|128;else V[Q++]=X>>18&7|240,V[Q++]=X>>12&63|128,V[Q++]=X>>6&63|128}V[Q++]=X&63|128}}var oZ=new TextEncoder,aZ=50;function sZ($,V,Z){oZ.encodeInto($,V.subarray(Z))}function vV($,V,Z){if($.length>aZ)sZ($,V,Z);else rZ($,V,Z)}var tZ=4096;function f$($,V,Z){let J=V,Q=J+Z,Y=[],X="";while(J<Q){let W=$[J++];if((W&128)===0)Y.push(W);else if((W&224)===192){let K=$[J++]&63;Y.push((W&31)<<6|K)}else if((W&240)===224){let K=$[J++]&63,G=$[J++]&63;Y.push((W&31)<<12|K<<6|G)}else if((W&248)===240){let K=$[J++]&63,G=$[J++]&63,z=$[J++]&63,R=(W&7)<<18|K<<12|G<<6|z;if(R>65535)R-=65536,Y.push(R>>>10&1023|55296),R=56320|R&1023;Y.push(R)}else Y.push(W);if(Y.length>=tZ)X+=String.fromCharCode(...Y),Y.length=0}if(Y.length>0)X+=String.fromCharCode(...Y);return X}var eZ=new TextDecoder,$J=200;function VJ($,V,Z){let J=$.subarray(V,V+Z);return eZ.decode(J)}function bV($,V,Z){if(Z>$J)return VJ($,V,Z);else return f$($,V,Z)}class S0{type;data;constructor($,V){this.type=$,this.data=V}}class a extends Error{constructor($){super($);let V=Object.create(a.prototype);Object.setPrototypeOf(this,V),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:a.name})}}var k0=4294967295;function iV($,V,Z){let J=Z/4294967296,Q=Z;$.setUint32(V,J),$.setUint32(V+4,Q)}function V$($,V,Z){let J=Math.floor(Z/4294967296),Q=Z;$.setUint32(V,J),$.setUint32(V+4,Q)}function Z$($,V){let Z=$.getInt32(V),J=$.getUint32(V+4);return Z*4294967296+J}function yV($,V){let Z=$.getUint32(V),J=$.getUint32(V+4);return Z*4294967296+J}var ZJ=-1,JJ=4294967295,QJ=17179869183;function YJ({sec:$,nsec:V}){if($>=0&&V>=0&&$<=QJ)if(V===0&&$<=JJ){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,$),Z}else{let Z=$/4294967296,J=$&4294967295,Q=new Uint8Array(8),Y=new DataView(Q.buffer);return Y.setUint32(0,V<<2|Z&3),Y.setUint32(4,J),Q}else{let Z=new Uint8Array(12),J=new DataView(Z.buffer);return J.setUint32(0,V),V$(J,4,$),Z}}function XJ($){let V=$.getTime(),Z=Math.floor(V/1000),J=(V-Z*1000)*1e6,Q=Math.floor(J/1e9);return{sec:Z+Q,nsec:J-Q*1e9}}function WJ($){if($ instanceof Date){let V=XJ($);return YJ(V)}else return null}function KJ($){let V=new DataView($.buffer,$.byteOffset,$.byteLength);switch($.byteLength){case 4:{let Z=V.getUint32(0),J=0;return{sec:Z,nsec:0}}case 8:{let Z=V.getUint32(0),J=V.getUint32(4),Q=(Z&3)*4294967296+J,Y=Z>>>2;return{sec:Q,nsec:Y}}case 12:{let Z=Z$(V,4),J=V.getUint32(0);return{sec:Z,nsec:J}}default:throw new a(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${$.length}`)}}function GJ($){let V=KJ($);return new Date(V.sec*1000+V.nsec/1e6)}var uV={type:ZJ,encode:WJ,decode:GJ};class B0{static defaultCodec=new B0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(uV)}register({type:$,encode:V,decode:Z}){if($>=0)this.encoders[$]=V,this.decoders[$]=Z;else{let J=-1-$;this.builtInEncoders[J]=V,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 Y=-1-Z;return new S0(Y,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 S0(Z,Q)}}if($ instanceof S0)return $;return null}decode($,V,Z){let J=V<0?this.builtInDecoders[-1-V]:this.decoders[V];if(J)return J($,V,Z);else return new S0(V,$)}}function zJ($){return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer}function h0($){if($ instanceof Uint8Array)return $;else if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);else if(zJ($))return new Uint8Array($);else return Uint8Array.from($)}var NJ=100,RJ=2048;class J${extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??B0.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.maxDepth=$?.maxDepth??NJ,this.initialBufferSize=$?.initialBufferSize??RJ,this.sortKeys=$?.sortKeys??!1,this.forceFloat32=$?.forceFloat32??!1,this.ignoreUndefined=$?.ignoreUndefined??!1,this.forceIntegerToFloat=$?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new J$({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($){if(this.entered)return this.clone().encodeSharedRef($);try{return this.entered=!0,this.reinitializeState(),this.doEncode($,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode($){if(this.entered)return this.clone().encode($);try{return this.entered=!0,this.reinitializeState(),this.doEncode($,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode($,V){if(V>this.maxDepth)throw Error(`Too deep objects in depth ${V}`);if($==null)this.encodeNil();else if(typeof $==="boolean")this.encodeBoolean($);else if(typeof $==="number")if(!this.forceIntegerToFloat)this.encodeNumber($);else this.encodeNumberAsFloat($);else if(typeof $==="string")this.encodeString($);else if(this.useBigInt64&&typeof $==="bigint")this.encodeBigInt64($);else this.encodeObject($,V)}ensureBufferSizeToWrite($){let V=this.pos+$;if(this.view.byteLength<V)this.resizeBuffer(V*2)}resizeBuffer($){let V=new ArrayBuffer($),Z=new Uint8Array(V),J=new DataView(V);Z.set(this.bytes),this.view=J,this.bytes=Z}encodeNil(){this.writeU8(192)}encodeBoolean($){if($===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber($){if(!this.forceIntegerToFloat&&Number.isSafeInteger($))if($>=0)if($<128)this.writeU8($);else if($<256)this.writeU8(204),this.writeU8($);else if($<65536)this.writeU8(205),this.writeU16($);else if($<4294967296)this.writeU8(206),this.writeU32($);else if(!this.useBigInt64)this.writeU8(207),this.writeU64($);else this.encodeNumberAsFloat($);else if($>=-32)this.writeU8(224|$+32);else if($>=-128)this.writeU8(208),this.writeI8($);else if($>=-32768)this.writeU8(209),this.writeI16($);else if($>=-2147483648)this.writeU8(210),this.writeI32($);else if(!this.useBigInt64)this.writeU8(211),this.writeI64($);else this.encodeNumberAsFloat($);else this.encodeNumberAsFloat($)}encodeNumberAsFloat($){if(this.forceFloat32)this.writeU8(202),this.writeF32($);else this.writeU8(203),this.writeF64($)}encodeBigInt64($){if($>=BigInt(0))this.writeU8(207),this.writeBigUint64($);else this.writeU8(211),this.writeBigInt64($)}writeStringHeader($){if($<32)this.writeU8(160+$);else if($<256)this.writeU8(217),this.writeU8($);else if($<65536)this.writeU8(218),this.writeU16($);else if($<4294967296)this.writeU8(219),this.writeU32($);else throw Error(`Too long string: ${$} bytes in UTF-8`)}encodeString($){let Z=gV($);this.ensureBufferSizeToWrite(5+Z),this.writeStringHeader(Z),vV($,this.bytes,this.pos),this.pos+=Z}encodeObject($,V){let Z=this.extensionCodec.tryToEncode($,this.context);if(Z!=null)this.encodeExtension(Z);else if(Array.isArray($))this.encodeArray($,V);else if(ArrayBuffer.isView($))this.encodeBinary($);else if(typeof $==="object")this.encodeMap($,V);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply($)}`)}encodeBinary($){let V=$.byteLength;if(V<256)this.writeU8(196),this.writeU8(V);else if(V<65536)this.writeU8(197),this.writeU16(V);else if(V<4294967296)this.writeU8(198),this.writeU32(V);else throw Error(`Too large binary: ${V}`);let Z=h0($);this.writeU8a(Z)}encodeArray($,V){let Z=$.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 $)this.doEncode(J,V+1)}countWithoutUndefined($,V){let Z=0;for(let J of V)if($[J]!==void 0)Z++;return Z}encodeMap($,V){let Z=Object.keys($);if(this.sortKeys)Z.sort();let J=this.ignoreUndefined?this.countWithoutUndefined($,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 Y=$[Q];if(!(this.ignoreUndefined&&Y===void 0))this.encodeString(Q),this.doEncode(Y,V+1)}}encodeExtension($){if(typeof $.data==="function"){let Z=$.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($.type),this.writeU8a(Z);return}let V=$.data.length;if(V===1)this.writeU8(212);else if(V===2)this.writeU8(213);else if(V===4)this.writeU8(214);else if(V===8)this.writeU8(215);else if(V===16)this.writeU8(216);else if(V<256)this.writeU8(199),this.writeU8(V);else if(V<65536)this.writeU8(200),this.writeU16(V);else if(V<4294967296)this.writeU8(201),this.writeU32(V);else throw Error(`Too large extension object: ${V}`);this.writeI8($.type),this.writeU8a($.data)}writeU8($){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,$),this.pos++}writeU8a($){let V=$.length;this.ensureBufferSizeToWrite(V),this.bytes.set($,this.pos),this.pos+=V}writeI8($){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,$),this.pos++}writeU16($){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,$),this.pos+=2}writeI16($){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,$),this.pos+=2}writeU32($){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,$),this.pos+=4}writeI32($){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,$),this.pos+=4}writeF32($){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,$),this.pos+=4}writeF64($){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,$),this.pos+=8}writeU64($){this.ensureBufferSizeToWrite(8),iV(this.view,this.pos,$),this.pos+=8}writeI64($){this.ensureBufferSizeToWrite(8),V$(this.view,this.pos,$),this.pos+=8}writeBigUint64($){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,$),this.pos+=8}writeBigInt64($){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,$),this.pos+=8}}function C0($,V){return new J$(V).encodeSharedRef($)}function Q$($){return`${$<0?"-":""}0x${Math.abs($).toString(16).padStart(2,"0")}`}var IJ=16,FJ=16;class S${hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor($=IJ,V=FJ){this.maxKeyLength=$,this.maxLengthPerKey=V,this.caches=[];for(let Z=0;Z<this.maxKeyLength;Z++)this.caches.push([])}canBeCached($){return $>0&&$<=this.maxKeyLength}find($,V,Z){let J=this.caches[Z-1];$:for(let Q of J){let Y=Q.bytes;for(let X=0;X<Z;X++)if(Y[X]!==$[V+X])continue $;return Q.str}return null}store($,V){let Z=this.caches[$.length-1],J={bytes:$,str:V};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=f$($,V,Z),Y=Uint8Array.prototype.slice.call($,V,V+Z);return this.store(Y,Q),Q}}var k$="array",n0="map_key",hV="map_value",UJ=($)=>{if(typeof $==="string"||typeof $==="number")return $;throw new a("The type of key must be string or number but "+typeof $)};class pV{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState($){let V=this.getUninitializedStateFromPool();V.type=k$,V.position=0,V.size=$,V.array=Array($)}pushMapState($){let V=this.getUninitializedStateFromPool();V.type=n0,V.readCount=0,V.size=$,V.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let $={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push($)}return this.stack[this.stackHeadPosition]}release($){if(this.stack[this.stackHeadPosition]!==$)throw Error("Invalid stack state. Released state is not on top of the stack.");if($.type===k$){let Z=$;Z.size=0,Z.array=void 0,Z.position=0,Z.type=void 0}if($.type===n0||$.type===hV){let Z=$;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 p0=-1,B$=new DataView(new ArrayBuffer(0)),wJ=new Uint8Array(B$.buffer);try{B$.getInt8(0)}catch($){if(!($ 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 lV=RangeError("Insufficient data"),MJ=new S$;class Y${extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=B$;bytes=wJ;headByte=p0;stack=new pV;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??B0.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.rawStrings=$?.rawStrings??!1,this.maxStrLength=$?.maxStrLength??k0,this.maxBinLength=$?.maxBinLength??k0,this.maxArrayLength=$?.maxArrayLength??k0,this.maxMapLength=$?.maxMapLength??k0,this.maxExtLength=$?.maxExtLength??k0,this.keyDecoder=$?.keyDecoder!==void 0?$.keyDecoder:MJ,this.mapKeyConverter=$?.mapKeyConverter??UJ}clone(){return new Y$({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=p0,this.stack.reset()}setBuffer($){let V=h0($);this.bytes=V,this.view=new DataView(V.buffer,V.byteOffset,V.byteLength),this.pos=0}appendBuffer($){if(this.headByte===p0&&!this.hasRemaining(1))this.setBuffer($);else{let V=this.bytes.subarray(this.pos),Z=h0($),J=new Uint8Array(V.length+Z.length);J.set(V),J.set(Z,V.length),this.setBuffer(J)}}hasRemaining($){return this.view.byteLength-this.pos>=$}createExtraByteError($){let{view:V,pos:Z}=this;return RangeError(`Extra ${V.byteLength-Z} of ${V.byteLength} byte(s) found at buffer[${$}]`)}decode($){if(this.entered)return this.clone().decode($);try{this.entered=!0,this.reinitializeState(),this.setBuffer($);let V=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return V}finally{this.entered=!1}}*decodeMulti($){if(this.entered){yield*this.clone().decodeMulti($);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer($);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync($){if(this.entered)return this.clone().decodeAsync($);try{this.entered=!0;let V=!1,Z;for await(let X of $){if(V)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(X);try{Z=this.doDecodeSync(),V=!0}catch(W){if(!(W instanceof RangeError))throw W}this.totalPos+=this.pos}if(V){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Z}let{headByte:J,pos:Q,totalPos:Y}=this;throw RangeError(`Insufficient data in parsing ${Q$(J)} at ${Y} (${Q} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream($){return this.decodeMultiAsync($,!0)}decodeStream($){return this.decodeMultiAsync($,!1)}async*decodeMultiAsync($,V){if(this.entered){yield*this.clone().decodeMultiAsync($,V);return}try{this.entered=!0;let Z=V,J=-1;for await(let Q of $){if(V&&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(Y){if(!(Y instanceof RangeError))throw Y}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){$:while(!0){let $=this.readHeadByte(),V;if($>=224)V=$-256;else if($<192)if($<128)V=$;else if($<144){let J=$-128;if(J!==0){this.pushMapState(J),this.complete();continue $}else V={}}else if($<160){let J=$-144;if(J!==0){this.pushArrayState(J),this.complete();continue $}else V=[]}else{let J=$-160;V=this.decodeString(J,0)}else if($===192)V=null;else if($===194)V=!1;else if($===195)V=!0;else if($===202)V=this.readF32();else if($===203)V=this.readF64();else if($===204)V=this.readU8();else if($===205)V=this.readU16();else if($===206)V=this.readU32();else if($===207)if(this.useBigInt64)V=this.readU64AsBigInt();else V=this.readU64();else if($===208)V=this.readI8();else if($===209)V=this.readI16();else if($===210)V=this.readI32();else if($===211)if(this.useBigInt64)V=this.readI64AsBigInt();else V=this.readI64();else if($===217){let J=this.lookU8();V=this.decodeString(J,1)}else if($===218){let J=this.lookU16();V=this.decodeString(J,2)}else if($===219){let J=this.lookU32();V=this.decodeString(J,4)}else if($===220){let J=this.readU16();if(J!==0){this.pushArrayState(J),this.complete();continue $}else V=[]}else if($===221){let J=this.readU32();if(J!==0){this.pushArrayState(J),this.complete();continue $}else V=[]}else if($===222){let J=this.readU16();if(J!==0){this.pushMapState(J),this.complete();continue $}else V={}}else if($===223){let J=this.readU32();if(J!==0){this.pushMapState(J),this.complete();continue $}else V={}}else if($===196){let J=this.lookU8();V=this.decodeBinary(J,1)}else if($===197){let J=this.lookU16();V=this.decodeBinary(J,2)}else if($===198){let J=this.lookU32();V=this.decodeBinary(J,4)}else if($===212)V=this.decodeExtension(1,0);else if($===213)V=this.decodeExtension(2,0);else if($===214)V=this.decodeExtension(4,0);else if($===215)V=this.decodeExtension(8,0);else if($===216)V=this.decodeExtension(16,0);else if($===199){let J=this.lookU8();V=this.decodeExtension(J,1)}else if($===200){let J=this.lookU16();V=this.decodeExtension(J,2)}else if($===201){let J=this.lookU32();V=this.decodeExtension(J,4)}else throw new a(`Unrecognized type byte: ${Q$($)}`);this.complete();let Z=this.stack;while(Z.length>0){let J=Z.top();if(J.type===k$)if(J.array[J.position]=V,J.position++,J.position===J.size)V=J.array,Z.release(J);else continue $;else if(J.type===n0){if(V==="__proto__")throw new a("The key __proto__ is not allowed");J.key=this.mapKeyConverter(V),J.type=hV;continue $}else if(J.map[J.key]=V,J.readCount++,J.readCount===J.size)V=J.map,Z.release(J);else{J.key=null,J.type=n0;continue $}}return V}}readHeadByte(){if(this.headByte===p0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=p0}readArraySize(){let $=this.readHeadByte();switch($){case 220:return this.readU16();case 221:return this.readU32();default:if($<160)return $-144;else throw new a(`Unrecognized array type byte: ${Q$($)}`)}}pushMapState($){if($>this.maxMapLength)throw new a(`Max length exceeded: map length (${$}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState($)}pushArrayState($){if($>this.maxArrayLength)throw new a(`Max length exceeded: array length (${$}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState($)}decodeString($,V){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String($,V);return this.decodeBinary($,V)}decodeUtf8String($,V){if($>this.maxStrLength)throw new a(`Max length exceeded: UTF-8 byte length (${$}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+V+$)throw lV;let Z=this.pos+V,J;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached($))J=this.keyDecoder.decode(this.bytes,Z,$);else J=bV(this.bytes,Z,$);return this.pos+=V+$,J}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===n0;return!1}decodeBinary($,V){if($>this.maxBinLength)throw new a(`Max length exceeded: bin length (${$}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining($+V))throw lV;let Z=this.pos+V,J=this.bytes.subarray(Z,Z+$);return this.pos+=V+$,J}decodeExtension($,V){if($>this.maxExtLength)throw new a(`Max length exceeded: ext length (${$}) > maxExtLength (${this.maxExtLength})`);let Z=this.view.getInt8(this.pos+V),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 $=this.view.getUint8(this.pos);return this.pos++,$}readI8(){let $=this.view.getInt8(this.pos);return this.pos++,$}readU16(){let $=this.view.getUint16(this.pos);return this.pos+=2,$}readI16(){let $=this.view.getInt16(this.pos);return this.pos+=2,$}readU32(){let $=this.view.getUint32(this.pos);return this.pos+=4,$}readI32(){let $=this.view.getInt32(this.pos);return this.pos+=4,$}readU64(){let $=yV(this.view,this.pos);return this.pos+=8,$}readI64(){let $=Z$(this.view,this.pos);return this.pos+=8,$}readU64AsBigInt(){let $=this.view.getBigUint64(this.pos);return this.pos+=8,$}readI64AsBigInt(){let $=this.view.getBigInt64(this.pos);return this.pos+=8,$}readF32(){let $=this.view.getFloat32(this.pos);return this.pos+=4,$}readF64(){let $=this.view.getFloat64(this.pos);return this.pos+=8,$}}function m$($,V){return new Y$(V).decode($)}class c0{listeners=new Map;addEventListener($,V){let Z=this.listeners.get($);if(!Z)Z=new Set,this.listeners.set($,Z);return Z.add(V),()=>{this.removeEventListener($,V)}}removeEventListener($,V){let Z=this.listeners.get($);if(Z){if(Z.delete(V),Z.size===0)this.listeners.delete($)}}emit($,V){let Z=this.listeners.get($);if(Z){let J=Array.from(Z);for(let Q of J)Q(V)}}emitAll($){let V=Array.from(this.listeners.keys());for(let Z of V)this.emit(Z,$)}}class T0{getter;static eventName="update";emitter;constructor($){this.getter=$;this.emitter=new c0}get=()=>this.getter();async emit(){let $=await this.getter();queueMicrotask(()=>this.emitter.emit(T0.eventName,$))}listen($){return this.emitter.addEventListener(T0.eventName,$),()=>{this.emitter.removeEventListener(T0.eventName,$)}}}function M($){return[$,0]}function N($){return[void 0,$]}function OJ($){if($<0)console.info("N",$),console.trace();if(typeof $!=="bigint")$=BigInt($);if($<0n)return N(10);let V=[];while($>0n){let Z=Number($&0x7fn);if($>>=7n,$>0n)V.push(Z|128);else V.push(Z)}if(V.length===0)return M(new Uint8Array([0]));if(V.length>8)return N(26);return M(new Uint8Array(V))}function HJ($,V=0){let Z=0n,J=0,Q=V;while(!0){if(Q>=$.length)return N(14);let Y=$[Q++];if(Y===void 0)return N(14);if(Z|=BigInt(Y&127)<<BigInt(J),(Y&128)===0){if(Q-V>8)return N(26);return M({value:Z>0x1fffffffffffffn?Z:Number(Z),bytesRead:Q-V})}if(J+=7,J>=56)return N(26)}}class v{data;pos=0;constructor($){this.data=$}static async fromResponse($){let V=await $.arrayBuffer(),Z=new Uint8Array(V);return new v(Z)}readBigInt(){if(this.pos+8>this.data.length)return N(7);let $=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,M($)}readDate(){let[$,V]=this.readVarInt();if(V!==0)return N(V);return M(new Date($))}readVarInt(){let[$,V]=HJ(this.data,this.pos);if(V!==0)return N(V);this.pos+=$.bytesRead;let Z=$.value;return M(typeof Z==="bigint"?Number(Z):Z)}readVarString(){let[$,V]=this.readVarInt();if(V!==0)return N(V);let[Z,J]=this.readBytes($);if(J!==0)return N(J);let Q=new TextDecoder().decode(Z);return M(Q)}readBytes($){if($<0)return N(10);if(this.pos+$>this.data.length)return N(23);let V=this.data.slice(this.pos,this.pos+$);return this.pos+=$,M(V)}readVarBytes(){let[$,V]=this.readVarInt();if(V!==0)return N(V);return this.readBytes($)}readStruct($){return $.decode(this)}readStructs($){let V=[];while(!this.done()){let[Z,J]=this.readStruct($);if(J!==0)return N(J);V.push(Z)}return M(V)}readBytesSeq($){let V=[];while(!this.done()){let[Z,J]=this.readBytes($);if(J!==0)return N(J);V.push(Z)}return M(V)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class b{parts=[];writeBigInt($){let V=new Uint8Array(8);new DataView(V.buffer).setBigUint64(0,$,!1),this.parts.push(V)}writeDate($){let V=$.getTime();return this.writeVarInt(V)}writeVarInt($){let[V,Z]=OJ($);if(Z!==0)return Z;return this.parts.push(V),0}writeVarString($){let V=new TextEncoder().encode($),Z=this.writeVarInt(V.length);if(Z!==0)return Z;return this.writeBytes(V),0}prependBytes($){this.parts.unshift($)}writeBytes($){this.parts.push($)}writeVarBytes($){let V=this.writeVarInt($.length);if(V!==0)return V;return this.writeBytes($),0}writeStruct($,V){return $.encode(this,V)}writeStructs($,V){for(let Z of V){let J=this.writeStruct($,Z);if(J!==0)return J}return 0}writeBytesSeq($){for(let V of $)this.writeBytes(V)}result(){let $=this.parts.reduce((J,Q)=>J+Q.length,0),V=new Uint8Array($),Z=0;for(let J of this.parts)V.set(J,Z),Z+=J.length;return V}*scan(){for(let $ of this.parts)yield $}}async function g$($,V){let Z=new b,J=Z.writeDate(V);if(J!==0)return N(J);let Q=Z.result(),Y=await $.sign(Q);return M({pubKey:$.publicKey,sig:Y,timestamp:V})}async function H0($,V,Z){let J=Z.now().getTime(),Q=$.timestamp.getTime();if(Math.abs(J-Q)>kV)return 4;let X=new b;X.writeDate($.timestamp);let W=X.result();if(!await V.checkSigEd25519($.sig,W,$.pubKey))return 3;return 0}var $0={encode($,V){let Z=$.writeVarBytes(V.id);if(Z!==0)return Z;let J=$.writeDate(V.ts);if(J!==0)return J;return 0},decode($){let[V,Z]=$.readVarBytes();if(Z!==0)return N(Z);let[J,Q]=$.readDate();if(Q!==0)return N(Q);return M({id:V,ts:J})}};function X$($){let V=new b,Z=V.writeStruct($0,$);if(Z!==0)return N(Z);let J=V.result();return M(J)}var J0={encode($,V){let Z=$.writeVarBytes(V.eid);if(Z!==0)return Z;let J=$.writeVarInt(V.off);if(J!==0)return J;let Q=$.writeVarInt(V.ctr);if(Q!==0)return Q;let Y=$.writeVarInt(V.len);if(Y!==0)return Y;if(V.hsh)$.writeBytes(V.hsh);return 0},decode($){let[V,Z]=$.readVarBytes();if(Z!==0)return N(Z);let J=new v(V),[,Q]=$0.decode(J);if(Q!==0)return N(Q);let[Y,X]=$.readVarInt();if(X!==0)return N(X);let[W,K]=$.readVarInt();if(K!==0)return N(K);let[G,z]=$.readVarInt();if(z!==0)return N(z);let R;if(G>0){let[I,U]=$.readBytes($$);if(U!==0)return N(U);R=I}return M({eid:V,off:Y,ctr:W,len:G,hsh:R})}};function X0($){return Array.from($).map((Z)=>Z.toString(16).padStart(2,"0")).join("")}function W$($){if($.length%2!==0)throw Error("Invalid hex string");let V=new Uint8Array($.length/2);for(let Z=0;Z<$.length;Z+=2)V[Z/2]=Number.parseInt($.substr(Z,2),16);return V}function V0($,V){if($===V)return!0;if($.byteLength!==V.byteLength)return!1;return $.every((Z,J)=>Z===V[J])}var E;if(typeof Uint8Array.prototype.toBase64==="function")E=($)=>$.toBase64();else E=($)=>btoa(String.fromCharCode(...$));var N0;if(typeof Uint8Array.fromBase64==="function")N0=($)=>Uint8Array.fromBase64($);else N0=($)=>Uint8Array.from(atob($),(V)=>V.charCodeAt(0));function K$($,V){let Z=new Uint8Array($.length+V.length);return Z.set($,0),Z.set(V,$.length),Z}function nV($,V,Z){return Z.checkSigEd25519($.sig,$.headCph,V)}async function cV($,V,Z,J){let Q;if($.bod&&$.len>0)Q=await Z.blake3($.bod);let Y=new b,X=J0.encode(Y,{...$,hsh:Q});if(X!==0)return N(X);let W=Y.result(),K=await V.kdmFor(W),G=J.deriveCipher(K,"encrypt"),z=await G.encrypt(W),R=$.bod?await G.encrypt($.bod):new Uint8Array(0),I=await V.sign(z);return M({sig:I,kdm:K,headCph:z,bodyCph:R})}async function v$($,V,Z,J,Q){let Y=new v($),[X,W]=J0.decode(Y);if(W!==0)return N(14);let K;try{K=V&&V.length>0?await Z.decrypt(V):void 0}catch{return N(20)}let G=X.hsh&&K===void 0,z=X.hsh===void 0&&K!==void 0;if(G||z)return N(19);if(X.hsh&&K){let I=await J.blake3(K);if(!V0(I,X.hsh))return N(19)}let R=Q??await J.blake3($);return M({msgHead:X,bod:K,headHash:R})}class b${now(){return new Date}}function dV($,V,Z,J){let Q=V.getTime()-$.getTime(),Y=Z.getTime()-J.getTime();return(Q+Y)/2}var d0={encode($,V){if($.writeVarInt(V.quota),V.quota>0){if(V.usage===void 0)return 9;$.writeVarInt(V.usage)}return 0},decode($){let[V,Z]=$.readVarInt();if(Z!==0)return N(Z);let J;if(V>0){let[Q,Y]=$.readVarInt();if(Y!==0)return N(Y);J=Q}return M({quota:V,usage:J})}};var i$={encode($,V){$.writeBytes(new Uint8Array([V.status]));let Z=$.writeDate(V.timeRcvd);if(Z!==0)return Z;let J=$.writeDate(V.timeSent);if(J!==0)return J;let Q=$.writeVarInt(V.subscription.term);if(Q!==0)return Q;let Y=$.writeVarInt(V.subscription.elapsed);if(Y!==0)return Y;let X=$.writeStruct(d0,V.subscription.stat);if(X!==0)return X;let W=$.writeStruct(d0,V.subscription.dyn);if(W!==0)return W;return 0},decode($){let[V,Z]=$.readBytes(1);if(Z!==0)return N(Z);let J=V[0],[Q,Y]=$.readDate();if(Y!==0)return N(Y);let[X,W]=$.readDate();if(W!==0)return N(W);let[K,G]=$.readVarInt();if(G!==0)return N(G);let[z,R]=$.readVarInt();if(R!==0)return N(R);let[I,U]=$.readStruct(d0);if(U!==0)return N(U);let[w,F]=$.readStruct(d0);if(F!==0)return N(F);return M({status:J,timeRcvd:Q,timeSent:X,subscription:{term:K,elapsed:z,stat:I,dyn:w}})}};var y$={encode($,V){let Z=$.writeVarBytes(V.headCph);if(Z!==0)return Z;let J=$.writeVarInt(V.seq);if(J!==0)return J;return 0},decode($){let[V,Z]=$.readVarBytes();if(Z!==0)return N(Z);let[J,Q]=$.readVarInt();if(Q!==0)return N(Q);return M({headCph:V,seq:J})}};var Z0={encode($,V){$.writeBytes(V.pubKey),$.writeBytes(V.sig);let Z=$.writeDate(V.timestamp);if(Z!==0)return Z;return 0},decode($){let[V,Z]=$.readBytes(SV);if(Z!==0)return N(Z);let[J,Q]=$.readBytes(M0);if(Q!==0)return N(Q);let[Y,X]=$.readDate();if(X!==0)return N(X);return M({pubKey:V,sig:J,timestamp:Y})}};var rV={async encodeReq($,V,Z,J,Q){let Y=Q.writeStruct(Z0,Z);if(Y!==0)return Y;for(let X of J)Q.writeVarInt(X);return 0},async handleReq($,V,Z){let{clock:J,crypto:Q,storage:Y}=$,[X,W]=V.readStruct(Z0);if(W!==0)return W;let K=await H0(X,Q,J);if(K!==0)return K;let{pubKey:G}=X,[z,R]=await Y.hasUser(G);if(R!==0)return R;if(!z)return 5;let[I,U]=V.readVarInt();if(U!==0)return U;if(!V.done())return 8;let[w,F]=await Y.listHeads(G,I);if(F!==0)return F;return Z.writeStructs(y$,w)},decodeResp($){return $.readStructs(y$)}};var u$={encode($,V){$.writeVarInt(V.seq);let Z=$.writeVarBytes(V.bodyCph);if(Z!==0)return Z;return 0},decode($){let[V,Z]=$.readVarInt();if(Z!==0)return N(Z);let[J,Q]=$.readVarBytes();if(Q!==0)return N(Q);return M({seq:V,bodyCph:J})}};var oV={async encodeReq($,V,Z,J,Q){let Y=Q.writeStruct(Z0,Z);if(Y!==0)return Y;for(let X of J){let W=Q.writeVarInt(X);if(W!==0)return W}return 0},async handleReq($,V,Z){let{clock:J,crypto:Q,storage:Y}=$,[X,W]=V.readStruct(Z0);if(W!==0)return W;let K=await H0(X,Q,J);if(K!==0)return K;let{pubKey:G}=X,[z,R]=await Y.hasUser(G);if(R!==0)return R;if(!z)return 5;let I=[];while(!V.done()){let[F,O]=V.readVarInt();if(O!==0)return O;I.push(F)}console.info(`PULL: ${I.length} bags`);let[U,w]=await Y.getBodies(G,I);if(w!==0)return w;if(!U)return 17;for(let{seq:F,bodyCph:O}of U){let P={seq:F,bodyCph:O},q=Z.writeStruct(u$,P);if(q!==0)return q}return 0},decodeResp($){return $.readStructs(u$)}};var l$={encode($,V){$.writeBytes(V.sig),$.writeBytes(V.kdm);let Z=$.writeVarBytes(V.headCph);if(Z!==0)return Z;let J=$.writeVarBytes(V.bodyCph);if(J!==0)return J;return 0},decode($){let[V,Z]=$.readBytes(M0);if(Z!==0)return N(Z);let[J,Q]=$.readBytes(O0);if(Q!==0)return N(Q);let[Y,X]=$.readVarBytes();if(X!==0)return N(X);let[W,K]=$.readVarBytes();if(K!==0)return N(K);return M({sig:V,kdm:J,headCph:Y,bodyCph:W})}};var G$={encode($,V){let Z=$.writeVarInt(V.seq);if(Z!==0)return Z;let J=$.writeVarBytes(V.headCph);if(J!==0)return J;let Q=V.bodyCph?V.bodyCph.length:0,Y=$.writeVarInt(Q);if(Y!==0)return Y;if(Q>0){if(!V.bodyCph)return 10;$.writeBytes(V.bodyCph)}return 0},decode($){let[V,Z]=$.readVarInt();if(Z!==0)return N(Z);let[J,Q]=$.readVarBytes();if(Q!==0)return N(Q);let[Y,X]=$.readVarInt();if(X!==0)return N(X);let W;if(Y>0){let[K,G]=$.readBytes(Y);if(G!==0)return N(G);W=K}return M({seq:V,headCph:J,bodyCph:W})}};var z$={encode($,V){$.writeBytes(V.sig),$.writeBytes(V.kdm);let Z=$.writeVarBytes(V.headCph);if(Z!==0)return Z;return 0},decode($){let[V,Z]=$.readBytes(M0);if(Z!==0)return N(Z);let[J,Q]=$.readBytes(O0);if(Q!==0)return N(Q);let[Y,X]=$.readVarBytes();if(X!==0)return N(X);return M({sig:V,kdm:J,headCph:Y})}};var N$={encode($,V){if($.writeVarInt(V.idx),$.writeBytes(new Uint8Array([V.status])),V.status===0)$.writeVarInt(V.seq);return 0},decode($){let[V,Z]=$.readVarInt();if(Z!==0)return N(Z);let[J,Q]=$.readBytes(1);if(Q!==0)return N(Q);let Y=J[0];if(Y!==0)return M({idx:V,status:Y});let[X,W]=$.readVarInt();if(W!==0)return N(W);return M({idx:V,status:Y,seq:X})}};var aV={async encodeReq($,V,Z,J,Q){let Y=Q.writeStruct(Z0,Z);if(Y!==0)return Y;let X=Q.writeStructs(l$,J);if(X!==0)return X;return 0},async handleReq($,V,Z){let{clock:J,crypto:Q,storage:Y,notifier:X}=$,[W,K]=V.readStruct(Z0);if(K!==0)return K;let G=await H0(W,Q,J);if(G!==0)return G;let{pubKey:z}=W,[R,I]=await Y.hasUser(z);if(I!==0)return I;if(!R)return 5;let[U,w]=V.readStructs(l$);if(w!==0)return w;console.info(`PUSH: ${U.length} bags`);let F=[],O=[];for(let H=0;H<U.length;H++){let D=U[H];if(!await nV(D,z,Q)){let B={idx:H,status:3},k=Z.writeStruct(N$,B);if(k!==0)return k;continue}F.push(H),O.push(D)}let[P,q]=await Y.setBags(z,O);if(q!==0)return q;if(!P||P.length!==O.length)return 17;let T=[];for(let H=0;H<O.length;H++){let D=O[H],x=F[H],B=P[H],k=new b,f=k.writeStruct(z$,D);if(f!==0)return f;let g=k.result(),C={seq:B,headCph:g};if(U.length===1&&D.bodyCph.length<=BV)C.bodyCph=D.bodyCph;T.push(C);let y={idx:x,status:0,seq:B},l=Z.writeStruct(N$,y);if(l!==0)return l}if(T.length>0){let H=new b,D=H.writeStructs(G$,T);if(D!==0)return D;let x=H.result();await Promise.resolve(X.push(z,x))}return 0},decodeResp($){return $.readStructs(N$)}};var sV={async encodeReq($,V,Z,J,Q){return Q.writeStruct(Z0,Z)},async handleReq($,V,Z){let{clock:J,crypto:Q,storage:Y}=$,[X,W]=V.readStruct(Z0);if(W!==0)return W;let K=await H0(X,Q,J);if(K!==0)return K;let{pubKey:G}=X;if(!V.done())return 8;let[z,R]=await Y.addUser(G);if(R!==0)return R;return 0},decodeResp($){return M(void 0)}};class h${url;websocket;constructor($){this.url=$}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 Y=new b;Y.writeStruct(Z0,$);let X=Y.result(),W=X0(X);return Q.searchParams.set("t",W),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=(K)=>{let G=new Uint8Array(K.data);V(G)},this.websocket.onerror=(K)=>{console.log(`ERROR: ${JSON.stringify(K)}`),this.websocket=void 0,Z()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var d={user:{path:"/user",endpoint:sV,name:0},push:{path:"/push",endpoint:aV,name:2},peek:{path:"/peek",endpoint:rV,name:1},pull:{path:"/pull",endpoint:oV,name:3}},qJ={0:d.user,2:d.push,1:d.peek,3:d.pull},RW={[d.user.path]:d.user,[d.push.path]:d.push,[d.peek.path]:d.peek,[d.pull.path]:d.pull};class tV{url;listener;constructor($){this.url=$;this.listener=new h$($)}async call($,V){let{path:Z}=qJ[$],J=new URL(Z,this.url);try{return await PJ(J,V)}catch{return N(25)}}}var eV=($)=>{return new tV($.handle)};async function PJ($,V){let Z=await fetch($,{method:"POST",body:V.result().slice()});if(!Z.ok)return N(24);let J=await v.fromResponse(Z);return M(J)}class R${enclave;crypto;host;clock;transport;updateHostMeta;constructor($,V,Z,J,Q,Y){this.enclave=$;this.crypto=V;this.host=Z;this.clock=J;this.transport=Q;this.updateHostMeta=Y}async call($,V){let{clock:Z,transport:J}=this,{endpoint:Q,name:Y}=$,X=await this.identity(),W=Z.now(),[K,G]=await g$(X,W);if(G!==0)return N(G);let z=new b,R=await Q.encodeReq(this,X,K,V,z);if(R!==0)return N(R);let I=Z.now(),[U,w]=await J.call(Y,z),F=Z.now();if(w!==0)return N(w);let[O,P]=U.readStruct(i$);if(P!==0)return N(P);if(O.status!==0)return N(O.status);let T={clockOffset:dV(I,O.timeRcvd,O.timeSent,F),subscription:O.subscription},H=await this.updateHostMeta(T);if(H!==0)return N(H);return Q.decodeResp(U)}identity=()=>{let{host:$,enclave:V}=this;return V.deriveIdentity($.label,$.idx??0)};seal=async($)=>{let{crypto:V,enclave:Z}=this,J=await this.identity();return cV($,J,V,Z)};register=()=>this.call(d.user,[]);peek=($)=>this.call(d.peek,[$]);push=($)=>this.call(d.push,$);pull=($)=>this.call(d.pull,$);listen=async($,V,Z)=>{let{clock:J,transport:Q}=this,{listener:Y}=Q,X=await this.identity(),W=J.now(),[K,G]=await g$(X,W);if(G!==0)return G;return await Y.connect(K,$,V,Z)};isConnected(){let $=this.transport?.listener;if($&&typeof $.connected==="function")return $.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var p$={encode($,V){let Z=$.writeVarString(V.lbl);if(Z!==0)return Z;let J=$.writeVarInt(V.idx);if(J!==0)return J;let Q=$.writeVarInt(V.num);if(Q!==0)return Q;return $.writeBytes(V.hsh),$.writeBytes(V.sig),0},decode($){let[V,Z]=$.readVarString();if(Z!==0)return N(Z);let[J,Q]=$.readVarInt();if(Q!==0)return N(Q);let[Y,X]=$.readVarInt();if(X!==0)return N(X);let[W,K]=$.readBytes($$);if(K!==0)return N(K);let[G,z]=$.readBytes(M0);if(z!==0)return N(z);return M({lbl:V,idx:J,num:Y,hsh:W,sig:G})}};var n$={encode($,V){let Z=$.writeStruct(p$,V.head);if(Z!==0)return Z;let J=$.writeVarBytes(V.indexEnc);if(J!==0)return J;let Q=$.writeVarBytes(V.bodyEnc);if(Q!==0)return Q;return 0},decode($){let[V,Z]=$.readStruct(p$);if(Z!==0)return N(Z);let[J,Q]=$.readVarBytes();if(Q!==0)return N(Q);let[Y,X]=$.readVarBytes();if(X!==0)return N(X);return M({head:V,indexEnc:J,bodyEnc:Y})}};var c$={encode($,V){$.writeBytes(V.kdm);let Z=$.writeVarBytes(V.headCph);if(Z!==0)return Z;let J=$.writeVarInt(V.lenBody);if(J!==0)return J;if(V.lenBody>0&&V.offBody!==void 0){let Q=$.writeVarInt(V.offBody);if(Q!==0)return Q}return 0},decode($){let[V,Z]=$.readBytes(O0);if(Z!==0)return N(Z);let[J,Q]=$.readVarBytes();if(Q!==0)return N(Q);let[Y,X]=$.readVarInt();if(X!==0)return N(X);let W;if(Y>0){let[K,G]=$.readVarInt();if(G!==0)return N(G);W=K}return M({kdm:V,headCph:J,lenBody:Y,offBody:W})}};async function $Z($,V,Z,J,Q){let Y=await Q.deriveIdentity($,V),X=new b,W=new b,K=0,G=0;for(let P of Z){let q=new b,T=q.writeStruct(J0,P.head);if(T!==0)return N(T);let H=q.result(),D=await Y.kdmFor(H),x=Q.deriveCipher(D,"encrypt"),B=await x.encrypt(H),k=P.body?await x.encrypt(P.body):new Uint8Array(0),f=P.head.len>0&&P.head.hsh!==void 0?k.length:0,g={kdm:D,headCph:B,lenBody:f,offBody:f>0?G:void 0},C=X.writeStruct(c$,g);if(C!==0)return N(C);if(P.body)W.writeBytes(k),G+=k.length;K++}let z=W.result(),R=X.result(),I=await J.blake3(R),U=await Y.sign(I),w={lbl:$,idx:V,num:K,hsh:I,sig:U},F=new b;F.writeStruct(n$,{head:w,indexEnc:R,bodyEnc:z});let O=F.result();return M(O)}async function VZ($,V,Z){let[J,Q]=n$.decode(new v($));if(Q!==0)return N(Q);let{head:Y,indexEnc:X,bodyEnc:W}=J,K=await Z.deriveIdentity(Y.lbl,Y.idx);if(!await V.checkSigEd25519(Y.sig,Y.hsh,K.publicKey))return N(3);let z=await V.blake3(X);if(!V0(z,Y.hsh))return N(19);let R=new v(X),I=[];for(let w=0;w<Y.num;w++){let[F,O]=R.readStruct(c$);if(O!==0)return N(O);I.push(F)}if(I.length!==Y.num)return N(14);let U=[];for(let w of I){let F=Z.deriveCipher(w.kdm,"decrypt"),O;try{O=await F.decrypt(w.headCph)}catch{return N(20)}let[P,q]=J0.decode(new v(O));if(q!==0)return N(q);let T;if(w.lenBody>0&&w.offBody!==void 0){if(P.hsh===void 0)return N(14);let H=W.slice(w.offBody,w.offBody+w.lenBody);try{T=await F.decrypt(H)}catch{return N(20)}let D=await V.blake3(T);if(!V0(D,P.hsh))return N(19)}U.push({head:P,body:T})}return M(U)}async function ZZ({now:$,bod:V,crypto:Z}){let J=await Z.genRandomBytes(8),Q=new b,Y=Q.writeStruct($0,{id:J,ts:$});if(Y!==0)return N(Y);let X=Q.result();return I$({now:$,eid:X,ctr:0,bod:V,crypto:Z})}async function I$({now:$,eid:V,ctr:Z,bod:J,crypto:Q}){let Y=new v(V),[X,W]=$0.decode(Y);if(W!==0)return N(W);let K=$.getTime()-X.ts.getTime(),G,z=J?.length??0;if(J&&z>0)G=await Q.blake3(J);return M({eid:V,off:K,ctr:Z,len:z,hsh:G})}function CJ($,V){let Z=$.length<V.length?$.length:V.length;for(let J=0;J<Z;J++)if($[J]!==V[J])return $[J]-V[J];return $.length-V.length}async function r0($,V){let Z=Array.from($);Z.sort(CJ);let J=0;for(let X of Z)J+=X.length;let Q=new Uint8Array(J),Y=0;for(let X of Z)Q.set(X,Y),Y+=X.length;return V.blake3(Q)}function TJ($){let V=new b,Z=V.writeVarBytes($.eid);if(Z!==0)return N(Z);let J=V.writeDate($.updatedAt);if(J!==0)return N(J);let Q=V.writeVarInt($.ctr);if(Q!==0)return N(Q);return M(V.result())}async function F$($,V){let Z=[];for(let J of $){let[Q,Y]=TJ(J);if(Y!==0||!Q)return N(Y);Z.push(Q)}return M(await r0(Z,V))}var J8=Symbol("EntityID");function JZ($){return"type"in $}var Q8=Symbol("MasterSeed"),Y8=Symbol("DerivationSeed"),X8=Symbol("PublicKey"),W8=Symbol("PrivateKey"),K8=Symbol("HostSpecificKeyPair"),G8=Symbol("Hash");function AJ($){if(!$)return!1;if(typeof $!=="object")return!1;if("body"in $===!1)return!1;if("type"in $===!1)return!1;return!0}function DJ($){if(!$.bod||$.bod.length===0){let J={off:$.off,ctr:$.ctr,eid:$.eid};return M(J)}let V=m$($.bod);if(AJ(V)===!1)return console.warn("msg body invalid",V),N(14);let Z={off:$.off,ctr:$.ctr,eid:$.eid,gid:V.gid,pid:V.pid,tags:V.tags,type:V.type,body:V.body};return M(Z)}class U${applier;emitter=new c0;clearer;onDirtyEids;cacheDriven;peerIngest;constructor($,V,Z,J){this.applier=$;this.clearer=V,this.onDirtyEids=Z,this.cacheDriven=J?.cacheDriven??!1,this.peerIngest=J?.peerIngest}apply=async($)=>{let V=[],Z=[];for(let W of $){let[K,G]=DJ(W);if(Z.push(G),G!==0)continue;V.push(K)}let{stats:J,types:Q,eids:Y}=await this.applier(V),X=[];for(let W=0;W<$.length;W++){let K=Z[W],G=J[W];if(K!==0){X.push(K);continue}if(G!==0){X.push(G);continue}X.push(0)}if(!this.cacheDriven)for(let W of Q)this.emitter.emit(W,null);if(Y.length>0)this.onDirtyEids?.(Y);return X};clear=async()=>{let $=await this.clearer();if($!==0)return $;return this.emitter.emitAll(null),$};notify=($)=>{for(let V of $)this.emitter.emit(V,null)};refresh=async($)=>{if(this.peerIngest){await this.peerIngest($);return}};on=($,V)=>{this.emitter.addEventListener($,V)};off=($,V)=>{this.emitter.removeEventListener($,V)}}var p="entities",w$="entity_type_created_at",d$="entity_type_updated_at",r$="entity_type_group_id",o$="entity_type_parent_id",a$="entity_tags",QZ="db",YZ=12;function _J($){let V={bod:$.body,crd:$.createdAt,...$.ctr!==0?{ctr:$.ctr}:{},eid:E($.eid),gid:$.gid,pid:$.pid?E($.pid):void 0,tags:$.tags,typ:$.type,upd:$.updatedAt};if(V.gid===void 0)delete V.gid;if(V.pid===void 0)delete V.pid;if(V.tags===void 0)delete V.tags;if(V.ctr===void 0)delete V.ctr;return V}function q0($){return{body:$.bod,createdAt:$.crd,updatedAt:$.upd,ctr:$.ctr??0,type:$.typ,eid:N0($.eid),gid:$.gid,pid:$.pid?N0($.pid):void 0,...$.tags!==void 0?{tags:$.tags}:{}}}class XZ{db;opening;async init(){await this.ensureDb()}async ensureDb(){if(this.db)return this.db;if(this.opening)return this.opening;return this.opening=LJ().then(($)=>{return $.onversionchange=()=>{if($.close(),this.db===$)this.db=void 0},this.db=$,this.opening=void 0,$},($)=>{throw this.opening=void 0,$}),this.opening}apply=async($)=>{let V=new Set,Z=[],J;try{J=await this.ensureDb()}catch{return{stats:$.map(()=>16),types:V,eids:Z}}let Q=J.transaction(p,"readwrite"),Y=Q.objectStore(p);return new Promise((X)=>{let W=Array($.length).fill(0);if($.length<1){X({stats:[],types:V,eids:Z});return}Q.oncomplete=()=>{X({stats:W,types:V,eids:Z})},Q.onerror=()=>{for(let G=0;G<W.length;G++)if(W[G]===void 0)W[G]=18;X({stats:W,types:V,eids:Z})};let K=new Map;for(let G=0;G<$.length;G++){let z=$[G],R=E(z.eid),I={op:z,index:G},U=K.get(R);if(U)U.push(I);else K.set(R,[I])}for(let[G,z]of K){if(z.length<1)continue;let R=Y.get(G);R.onsuccess=()=>{let I=R.result,U=I?q0(I):void 0,w=!1;for(let{op:F,index:O}of z){let[P,q]=m0(U,F);if(q!==0){W[O]=q;continue}if(w=!0,P)V.add(P.type);else if(U)V.add(U.type);U=P}if(w)Z.push(z[0].op.eid);if(U){let F=_J(U),O=Y.put(F);O.onerror=(P)=>{P.preventDefault();for(let{index:q}of z)W[q]=18}}else{let F=Y.delete(G);F.onerror=()=>{for(let{index:O}of z)W[O]=18}}},R.onerror=()=>{for(let{index:I}of z)W[I]=18}}})};async clear(){let $;try{$=await this.ensureDb()}catch{return 16}let V=$.transaction(p,"readwrite"),Z=V.objectStore(p);return new Promise((J)=>{V.oncomplete=()=>J(0),V.onerror=()=>J(18),Z.clear()})}async getEnt($){let V;try{V=await this.ensureDb()}catch{return N(16)}let Z=E($),Q=V.transaction(p,"readonly").objectStore(p);return new Promise((Y)=>{let X=Q.get(Z);X.onsuccess=()=>{let W=X.result;if(!W)Y(M(void 0));else{let K=q0(W);Y(M(K))}},X.onerror=()=>Y(N(18))})}async getAllOfTypeUpdatedBetween($,V,Z){let J;try{J=await this.ensureDb()}catch{return N(16)}let Y=J.transaction(p,"readonly").objectStore(p).index(d$);return new Promise((X)=>{let W=Y.getAll(IDBKeyRange.bound([$,V],[$,Z]));W.onsuccess=()=>{let K=W.result;X(M(K.map(q0)))},W.onerror=()=>X(N(18))})}async getGroupMembers($,V){let Z;try{Z=await this.ensureDb()}catch{return N(16)}let Q=Z.transaction(p,"readonly").objectStore(p).index(r$);return new Promise((Y)=>{let X=Q.getAll(IDBKeyRange.only([$,V]));X.onsuccess=()=>{let W=X.result;Y(M(W.map(q0)))},X.onerror=()=>Y(N(18))})}async getAllOfType($){let V;try{V=await this.ensureDb()}catch{return N(16)}let J=V.transaction(p,"readonly").objectStore(p).index(w$);return new Promise((Q)=>{let Y=J.getAll(IDBKeyRange.bound([$],[$,[]]));Y.onsuccess=()=>{let X=Y.result;Q(M(X.map(q0)))},Y.onerror=()=>Q(N(18))})}async getByTag($,V){let Z;try{Z=await this.ensureDb()}catch{return N(16)}let Q=Z.transaction(p,"readonly").objectStore(p).index(a$);return new Promise((Y)=>{let X=Q.getAll(IDBKeyRange.only(V));X.onsuccess=()=>{let K=X.result.filter((G)=>G.typ===$).map(q0);Y(M(K))},X.onerror=()=>Y(N(18))})}async getAllEntities($){if("pid"in $){let V;try{V=await this.ensureDb()}catch{return N(16)}let Z=E($.pid),Q=V.transaction(p,"readonly").objectStore(p).index(o$);return new Promise((Y)=>{let X=Q.getAll(IDBKeyRange.only([$.type,Z]));X.onsuccess=()=>{let K=X.result.map(q0);Y(M(K))},X.onerror=()=>Y(N(18))})}else if("gid"in $)return await this.getGroupMembers($.type,$.gid);else if("tag"in $)return await this.getByTag($.type,$.tag);else if("updatedBetween"in $)return await this.getAllOfTypeUpdatedBetween($.type,$.updatedBetween.start,$.updatedBetween.end);return await this.getAllOfType($.type)}async getEntities($){let[V,Z]=await this.getAllEntities($);if(Z!==0)return N(Z);return M(V)}async countEntities({type:$}){let V;try{V=await this.ensureDb()}catch{return N(16)}let J=V.transaction(p,"readonly").objectStore(p).index(w$);return new Promise((Q)=>{let Y=IDBKeyRange.bound([$],[$,[]]),X=J.count(Y);X.onsuccess=()=>Q(M(X.result)),X.onerror=()=>Q(N(18))})}async checksum($){let V;try{V=await this.ensureDb()}catch{return N(16)}let J=V.transaction(p,"readonly").objectStore(p),Q=[];return new Promise((Y)=>{let X=J.openCursor();X.onsuccess=()=>{let W=X.result;if(W){let K=W.value;Q.push(M$(q0(K))),W.continue()}else F$(Q,$).then(Y)},X.onerror=()=>Y(N(18))})}}function jJ($,V){if(!$.objectStoreNames.contains(p))$.createObjectStore(p,{keyPath:"eid",autoIncrement:!1});let Z=V.objectStore(p);if(!Z.indexNames.contains(w$))Z.createIndex(w$,["typ","crd"],{unique:!1});if(!Z.indexNames.contains(d$))Z.createIndex(d$,["typ","upd"],{unique:!1});if(!Z.indexNames.contains(r$))Z.createIndex(r$,["typ","gid"],{unique:!1});if(!Z.indexNames.contains(o$))Z.createIndex(o$,["typ","pid"],{unique:!1});if(!Z.indexNames.contains(a$))Z.createIndex(a$,"tags",{unique:!1,multiEntry:!0})}function LJ(){return new Promise(($,V)=>{let Z=indexedDB.open(QZ,YZ);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!Q){V(Error("Transaction is null during EntDB upgrade"));return}try{jJ(J,Q)}catch(Y){V(Y instanceof Error?Y:Error(String(Y)))}},Z.onblocked=()=>{console.warn(`[DIPLOMATIC] EntDB IDB upgrade blocked (${QZ} → v${YZ}); waiting for other connections to close`)},Z.onsuccess=()=>$(Z.result),Z.onerror=()=>V(Z.error??Error("EntDB IndexedDB open failed"))})}async function WZ(){let $=new XZ;return await $.init(),$}class s${ents=new Map;useIndex;byType=new Map;byTypePid=new Map;byTypeGid=new Map;byTypeTag=new Map;constructor($=[],V){this.useIndex=V?.indexes!==!1;for(let Z of $)this.put(Z)}put($){let V=E($.eid),Z=this.ents.get(V);if(Z)this.unindex(V,Z);this.ents.set(V,$),this.index(V,$)}del($){let V=this.ents.get($);if(!V)return;this.unindex($,V),this.ents.delete($)}index($,V){if(!this.useIndex)return;let Z=this.byType.get(V.type);if(!Z)Z=new Map,this.byType.set(V.type,Z);if(Z.set($,V),V.pid){let J=E(V.pid),Q=this.byTypePid.get(V.type);if(!Q)Q=new Map,this.byTypePid.set(V.type,Q);let Y=Q.get(J);if(!Y)Y=new Map,Q.set(J,Y);Y.set($,V)}if(typeof V.gid==="string"){let J=this.byTypeGid.get(V.type);if(!J)J=new Map,this.byTypeGid.set(V.type,J);let Q=J.get(V.gid);if(!Q)Q=new Map,J.set(V.gid,Q);Q.set($,V)}if(V.tags){let J=this.byTypeTag.get(V.type);if(!J)J=new Map,this.byTypeTag.set(V.type,J);for(let Q of V.tags){let Y=J.get(Q);if(!Y)Y=new Map,J.set(Q,Y);Y.set($,V)}}}unindex($,V){if(!this.useIndex)return;let Z=this.byType.get(V.type);if(Z){if(Z.delete($),Z.size===0)this.byType.delete(V.type)}if(V.pid){let J=E(V.pid),Q=this.byTypePid.get(V.type),Y=Q?.get(J);if(Y){if(Y.delete($),Y.size===0)Q?.delete(J)}if(Q&&Q.size===0)this.byTypePid.delete(V.type)}if(typeof V.gid==="string"){let J=this.byTypeGid.get(V.type),Q=J?.get(V.gid);if(Q){if(Q.delete($),Q.size===0)J?.delete(V.gid)}if(J&&J.size===0)this.byTypeGid.delete(V.type)}if(V.tags){let J=this.byTypeTag.get(V.type);if(J){for(let Q of V.tags){let Y=J.get(Q);if(Y){if(Y.delete($),Y.size===0)J.delete(Q)}}if(J.size===0)this.byTypeTag.delete(V.type)}}}clearIndexes(){this.byType.clear(),this.byTypePid.clear(),this.byTypeGid.clear(),this.byTypeTag.clear()}bucketList($){if(!$||$.size===0)return[];let V=[];for(let Z of $.values())V.push(Z);return V}async apply($){let V=new Set,Z=[],J=[];for(let Q of $){let Y=E(Q.eid),X=this.ents.get(Y),[W,K]=m0(X,Q);if(K!==0){J.push(K);continue}if(W)V.add(W.type);else if(X)V.add(X.type);if(W)this.put(W);else this.del(Y);Z.push(Q.eid),J.push(0)}return{stats:J,types:V,eids:Z}}async clear(){return this.ents.clear(),this.clearIndexes(),0}async getEnt($){let V=E($),Z=this.ents.get(V);return M(Z)}async getAllEntities({type:$,gid:V,pid:Z,tag:J,updatedBetween:Q}){if(this.useIndex){if(Z!==void 0){let X=E(Z);return M(this.bucketList(this.byTypePid.get($)?.get(X)))}if(V!==void 0)return M(this.bucketList(this.byTypeGid.get($)?.get(V)));if(J!==void 0)return M(this.bucketList(this.byTypeTag.get($)?.get(J)));if(Q!==void 0){let X=[],W=this.byType.get($);if(W){for(let K of W.values())if(K.updatedAt>=Q.start&&K.updatedAt<=Q.end)X.push(K)}return M(X)}return M(this.bucketList(this.byType.get($)))}let Y=[];if(Z!==void 0){for(let X of this.ents.values())if(X.type===$&&X.pid&&V0(X.pid,Z))Y.push(X)}else if(V!==void 0){for(let X of this.ents.values())if(X.type===$&&(typeof X.gid==="string"&&X.gid===V))Y.push(X)}else if(J!==void 0){for(let X of this.ents.values())if(X.type===$&&X.tags&&X.tags.includes(J))Y.push(X)}else if(Q!==void 0){for(let X of this.ents.values())if(X.type===$&&X.updatedAt>=Q.start&&X.updatedAt<=Q.end)Y.push(X)}else for(let X of this.ents.values())if(X.type===$)Y.push(X);return M(Y)}async getEntities($){let[V,Z]=await this.getAllEntities($);if(Z!==0)return N(Z);return M(V)}async countEntities({type:$}){if(this.useIndex)return M(this.byType.get($)?.size??0);let V=0;for(let Z of this.ents.values())if(Z.type===$)V+=1;return M(V)}async checksum($){let V=[];for(let Z of this.ents.values())V.push(M$(Z));return F$(V,$)}}async function KZ($){let V=await WZ();if($?.cache===!1)return V;return new t$(V,void 0,{indexes:$?.indexes})}class t${mem;durable;warmed=new Set;listeners=new Set;chain=Promise.resolve();constructor($,V,Z){if(this.durable=$,this.mem=new s$(V??[],{indexes:Z?.indexes}),V)for(let J of V)this.warmed.add(J.type)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}emit($){if($.size<1)return;for(let V of this.listeners)V($)}run($){let V=this.chain.then($,$);return this.chain=V.then(()=>{return},()=>{return}),V}apply($){return this.run(async()=>{let V=BJ(this.mem,$);this.emit(V.types);let Z=await this.durable.apply($),{changed:J,status:Q}=await this.pullEids($.map((Y)=>Y.eid));if(this.emit(J),Q!==0)return{stats:$.map(()=>Q),types:Z.types,eids:Z.eids};return Z})}clear(){return this.run(async()=>{let $=await this.durable.clear();if($!==0)return $;let V=this.mem.ents.size>0;return await this.mem.clear(),this.warmed.clear(),0})}ingestFromDurable($){return this.run(async()=>{let{changed:V,status:Z}=await this.pullEids($);return this.emit(V),Z})}async pullEids($){let V=new Set,Z=new Set;for(let J of $){let Q=E(J);if(Z.has(Q))continue;Z.add(Q);let Y=this.mem.ents.get(Q),[X,W]=await this.durable.getEnt(J);if(W!==0)return{changed:V,status:W};if(X){if(this.mem.put(X),!Y||!xJ(Y,X)){if(V.add(X.type),Y&&Y.type!==X.type)V.add(Y.type)}}else if(Y)this.mem.del(Q),V.add(Y.type)}return{changed:V,status:0}}async warmType($){if(this.warmed.has($))return 0;let[V,Z]=await this.durable.getEntities({type:$});if(Z!==0)return Z;if(V)for(let J of V){let Q=E(J.eid),Y=this.mem.ents.get(Q);if(!Y||kJ(J,Y))this.mem.put(J)}return this.warmed.add($),0}async getEnt($){let V=E($);if(this.mem.ents.has(V))return this.mem.getEnt($);return this.run(async()=>{if(this.mem.ents.has(V))return this.mem.getEnt($);let[Z,J]=await this.durable.getEnt($);if(J!==0)return N(J);if(Z)this.mem.put(Z);return M(Z)})}async getEntities($){if(!this.warmed.has($.type)){let V=await this.run(()=>this.warmType($.type));if(V!==0)return N(V)}return this.mem.getEntities($)}async countEntities({type:$}){if(!this.warmed.has($)){let V=await this.run(()=>this.warmType($));if(V!==0)return N(V)}return this.mem.countEntities({type:$})}async checksum($){return this.durable.checksum($)}}function xJ($,V){if($.ctr!==V.ctr)return!1;if($.updatedAt.getTime()!==V.updatedAt.getTime())return!1;if($.createdAt.getTime()!==V.createdAt.getTime())return!1;if($.type!==V.type)return!1;if($.gid!==V.gid)return!1;if(!V0($.eid,V.eid))return!1;if(!fJ($.pid,V.pid))return!1;if(!EJ($.tags,V.tags))return!1;return SJ($.body,V.body)}function EJ($,V){if($===V)return!0;if($===void 0||V===void 0)return!1;if($.length!==V.length)return!1;for(let Z=0;Z<$.length;Z++)if($[Z]!==V[Z])return!1;return!0}function fJ($,V){if($===void 0&&V===void 0)return!0;if($===void 0||V===void 0)return!1;return V0($,V)}function SJ($,V){if(Object.is($,V))return!0;if($ instanceof Uint8Array&&V instanceof Uint8Array)return V0($,V);if($ instanceof Date&&V instanceof Date)return $.getTime()===V.getTime();try{return V0(C0($),C0(V))}catch{return!1}}function kJ($,V){let Z=$.updatedAt.getTime(),J=V.updatedAt.getTime();if(Z!==J)return Z>J;return $.ctr>V.ctr}function BJ($,V){let Z=new Set,J=[];for(let Q of V){let Y=E(Q.eid),X=$.ents.get(Y),[W,K]=m0(X,Q);if(K!==0){J.push(K);continue}if(W)Z.add(W.type);else if(X)Z.add(X.type);if(W)$.put(W);else $.del(Y);J.push(0)}return{stats:J,types:Z}}function mJ($){if(!Array.isArray($)||$.length===0)return;let V=new Set,Z=[];for(let J of $){if(typeof J!=="string"||J.length===0)continue;if(V.has(J))continue;V.add(J),Z.push(J)}return Z.length>0?Z:void 0}function M$($){return{eid:$.eid,ctr:$.ctr,updatedAt:$.updatedAt}}function GZ($){let V=new v($.eid),[Z,J]=V.readStruct($0);if(J!==0)return N(J);return M({eid:$.eid,ctr:$.ctr,updatedAt:new Date(Z.ts.getTime()+$.off)})}function m0($,V){let Z=new v(V.eid),[J,Q]=Z.readStruct($0);if(Q!==0)return N(Q);let Y=new Date(J.ts.getTime()+V.off);if($!==void 0&&Y<=$.updatedAt)return N(15);if(JZ(V)){let X=mJ(V.tags);return M({eid:V.eid,gid:V.gid,pid:V.pid,...X!==void 0?{tags:X}:{},type:V.type,createdAt:J.ts,updatedAt:Y,ctr:V.ctr,body:V.body})}else return M(void 0)}class O${inflight=null;again=!1;run($){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain($),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain($){try{this.again=!1;let V=await $();while(this.again)this.again=!1,V=await $();return V}finally{this.inflight=null}}}var zZ=100;class e${timer=null;delayMs;work;tail=new O$;constructor($,V){this.delayMs=$<0?0:$,this.work=V}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)}}function NZ($){let V=new v($.eid),[Z,J]=$0.decode(V);if(J!==0)return;return Z.ts.getTime()+$.off}function gJ($,V){let Z=NZ($),J=NZ(V);if(Z===void 0&&J===void 0)return 0;if(Z===void 0)return 1;if(J===void 0)return-1;if(J!==Z)return J-Z;return V.ctr-$.ctr}function g0($,V){return $.slice().sort((Z,J)=>gJ(V(Z),V(J)))}var $V={phase:"idle"},o0=50;function VV($,V,Z){if($<=0||V<=0)return!1;if($===1||$===V)return!0;return $%Z===0}function RZ($,V){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob($,V);return}let Z=URL.createObjectURL($),J=document.createElement("a");J.href=Z,J.download=V,document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL(Z)}function IZ($,V,Z){let J=[],Q=[],Y=0;for(let X of $){let W=V(X);if(Q.length>0&&Y+W>Z)J.push(Q),Q=[],Y=0;if(Q.push(X),Y+=W,Y>=Z)J.push(Q),Q=[],Y=0}if(Q.length>0)J.push(Q);return J}async function ZV($,V,Z){let J=$.length;if(J<1)return[];let Q=Array(J),Y=0,X=Math.min(Math.max(1,V),J),W=async()=>{while(!0){let G=Y;if(Y+=1,G>=J)return;Q[G]=await Z($[G],G)}},K=[];for(let G=0;G<X;G++)K.push(W());return await Promise.all(K),Q}async function H$($,V,Z,J){let Q=new v($.headCph),[Y,X]=Q.readStruct(z$);if(X!==0)return N(X);let{sig:W,kdm:K,headCph:G}=Y;if(!await J.checkSigEd25519(W,G,V))return N(3);let R=Z.deriveCipher(K,"decrypt"),I;try{I=await R.decrypt(G)}catch{return N(20)}return M({kdm:K,headEnc:I})}var b0="f",q$="t",v0="e";function vJ($){if($===!0||$===q$)return q$;if($===v0)return v0;return b0}function FZ($){return $!==0&&$!==15&&$!==18&&$!==17}function JV($,V,Z){if($.apld=V,V===v0&&Z!==void 0)$.err=Z;else delete $.err}async function P$($,V,Z,J){let Q=J?.body!==!1,Y=vJ(V.apld),X=V.body,W=X?.length??0,K;if(Q&&X&&W>0)K=await Z.blake3(X);let G={eid:V.eid,off:V.off??0,ctr:V.ctr??0,len:W,hsh:K},z={hash:$,head:G,apld:Y};if(Q&&X!==void 0)z.body=X;if(Y===v0&&V.err!==void 0)z.err=V.err;return z}var QV=1048576,YV=1048576,wZ=64;function bJ($){return $.sig.length+$.kdm.length+$.headCph.length+$.bodyCph.length}async function iJ($,V,Z,J,Q){if(J.length<1)return 0;let[Y,X]=await $.push(J);if(X!==0)return X;if(!Y)return 27;for(let K of Y){if(K.status!==0){console.error("push err",K);continue}let G=Q[K.idx];if(!G){console.error("no hash",K);continue}await V.uploads.deq(Z,[G])}let W=await V.hosts.get(Z);if(W){let K=W.lastSeq,G=K,z=[];for(let R of Y)if(R.status===0)z.push(R.seq);z.sort((R,I)=>R-I);for(let R of z)if(R===K+1)K=R;if(K>G)await V.hosts.touch(Z,K)}return 0}async function UZ($,V){if(V.length<1)return M([]);let Z=new Map,J=[];for(let W of V)Z.set(W.seq,W),J.push(W.seq);let[Q,Y]=await $.pull(J);if(Y!==0)return N(Y);if(!Q)return N(27);let X=[];for(let{seq:W,bodyCph:K}of Q){let G=Z.get(W);if(!G)continue;X.push({dl:G,bodyCph:K})}return M(X)}async function yJ($,V,Z,J){if(J.length<1)return M({parts:[],hashes:[]});let Q=[],Y=[],X=[],W=new Map;for(let{dl:G,bodyCph:z}of J){let{head:R,kdm:I,seq:U,host:w}=G,[F,O]=await MZ(G,Z);if(O!==0||!F){let f=W.get(w)??[];f.push(U),W.set(w,f);continue}let{headEnc:P,headEncHash:q}=F,T=V.deriveCipher(I,"decrypt"),[H,D]=await v$(P,z,T,Z,q);if(D!==0||!H){let f=W.get(w)??[];f.push(U),W.set(w,f);continue}let x={head:R,body:H.bod},B=H.headHash;X.push({key:B,data:qZ(x)}),Q.push(x),Y.push(B);let k=W.get(w)??[];k.push(U),W.set(w,k)}let K=await $.messages.add(X);for(let[G,z]of W)await $.downloads.deq(G,z);for(let G=0;G<K.length;G++){let z=K[G];if(z!==0&&z!==15)console.error("ERR storing",j[z],"for message",G)}return M({parts:Q,hashes:Y})}async function MZ($,V){let Z=$.headEnc;if(!Z){let Q=new b,Y=Q.writeStruct(J0,$.head);if(Y!==0)return N(Y);Z=Q.result()}if($.headEncHash)return M({headEnc:Z,headEncHash:$.headEncHash});let J=await V.blake3(Z);return M({headEnc:Z,headEncHash:J})}async function OZ($,V,Z){let J=new Set;for(let X of V)J.add(E(X));if(J.size<1)return;let Q=Array.from(await $.downloads.list());if(Q.length<1)return;let Y=new Map;for(let X of Q){let W;if(X.headEncHash)W=E(X.headEncHash);else{let[G,z]=await MZ(X,Z);if(z!==0||!G)continue;W=E(G.headEncHash)}if(!J.has(W))continue;let K=Y.get(X.host)??[];K.push(X.seq),Y.set(X.host,K)}for(let[X,W]of Y)await $.downloads.deq(X,W)}async function XV({conn:$,store:V,enclave:Z,host:J,crypto:Q,onProgress:Y,peekProgressEvery:X,peekConcurrency:W}){let K=await $.identity(),G=[],[z,R]=await $.peek(J.lastSeq);if(R!==0)return R;let I=z.length,U=X??o0,w=W??wZ;if(Y&&I>0)Y({phase:"peek",host:J.label,done:0,total:I});let F=0,O=await ZV(z,w,async(q)=>{let[T,H]=await H$(q,K.publicKey,Z,Q),D;if(H!==0||!T)D={ok:!1,seq:q.seq,stat:H};else{let x=await Q.blake3(T.headEnc);D={ok:!0,seq:q.seq,kdm:T.kdm,headEnc:T.headEnc,headEncHash:x}}if(F+=1,Y&&VV(F,I,U))Y({phase:"peek",host:J.label,done:F,total:I});return D}),P=new Set;for(let q of O){if(!q.ok){console.error("peek: decrypting item head",q.stat);continue}let T=E(q.headEncHash);if(await V.messages.has(q.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await V.uploads.deq(J.label,[q.headEncHash]),await V.downloads.deq(J.label,[q.seq]);continue}if(P.has(T)){await V.downloads.deq(J.label,[q.seq]);continue}let D=new v(q.headEnc),[x,B]=D.readStruct(J0);if(B!==0){console.error("peek: reading item head",B);continue}P.add(T),G.push({kdm:q.kdm,head:x,seq:q.seq,host:J.label,headEnc:q.headEnc,headEncHash:q.headEncHash})}if(await V.downloads.enq(G),z.length>0){let q=Math.max(...z.map((T)=>T.seq));await V.hosts.recordStats(J.label,{lastSeq:q})}if(Y)Y({phase:"peek",host:J.label,done:I,total:I});return 0}async function HZ({conn:$,store:V,host:Z,maxPushBytes:J,onProgress:Q}){let Y=J??QV,X=await V.uploads.list(Z.label),W=X.length,K=0;if(Q&&W>0)Q({phase:"push",host:Z.label,done:0,total:W});let G=[],z=[],R=0,I=async()=>{if(G.length<1)return 0;let U=G.length,w=await iJ($,V,Z.label,G,z);if(G=[],z=[],R=0,w===0){if(K+=U,Q)Q({phase:"push",host:Z.label,done:K,total:W})}return w};for(let U of X){let w=await V.messages.get(U);if(!w){K+=1;continue}let F={...w.head,bod:w.body},[O,P]=await $.seal(F);if(P!==0)return P;if(!O)return 12;let q=bJ(O);if(G.length>0&&R+q>Y){let T=await I();if(T!==0)return T}if(G.push(O),z.push(U),R+=q,R>=Y){let T=await I();if(T!==0)return T}}return I()}async function WV({conn:$,store:V,enclave:Z,host:J,crypto:Q,maxPullBytes:Y,onProgress:X},W){let K=Y??YV,G=await V.downloads.list(),z=Array.from(G).filter((O)=>O.host===J.label);if(z.length<1)return 15;let R=g0(z,(O)=>O.head),I=IZ(R,(O)=>O.head.len,K),U=R.length,w=0;if(X)X({phase:"pull",host:J.label,done:0,total:U});let F=UZ($,I[0]);for(let O=0;O<I.length;O++){let[P,q]=await F;if(q!==0||!P)return q;if(w+=I[O].length,X)X({phase:"pull",host:J.label,done:w,total:U});let T=I[O+1];if(T)F=UZ($,T);if(X)X({phase:"open",host:J.label,done:w,total:U});let H=g0(P,(x)=>x.dl.head),[,D]=await yJ(V,Z,Q,H);if(D!==0)return D;if(W){if(X)X({phase:"exec",host:J.label,done:w,total:U});await W()}}return 0}function qZ({head:$,body:V}){let Z={eid:$.eid,body:V,apld:b0};if($.off!==0)Z.off=$.off;if($.ctr!==0)Z.ctr=$.ctr;return Z}async function PZ($,{conn:V,store:Z,enclave:J,host:Q,crypto:Y,onProgress:X},W){let K=Q.label,G=await V.identity(),z=new v($),[R,I]=z.readStructs(G$);if(I!==0){console.error("Failed decoding notif",j[I]);return}let U=!1,F=(await Z.hosts.get(K))?.lastSeq,O=[],P=!1;for(let H of R){let[D,x]=await H$({seq:H.seq,headCph:H.headCph},G.publicKey,J,Y);if(x!==0){console.error("Failed decrypting notif",j[x]);continue}let B=await Y.blake3(D.headEnc);if(await Z.messages.has(B))continue;let k=new v(D.headEnc),[f,g]=k.readStruct(J0);if(g!==0){console.error("Failed to parse head",j[g]);continue}if(!H.bodyCph&&f.len>0)P=!0,await Z.downloads.enq([{seq:H.seq,host:K,kdm:D.kdm,head:f,headEnc:D.headEnc,headEncHash:B}]);else O.push({...D,head:f,bodyCph:H.bodyCph,headEncHash:B});if(F===void 0||H.seq!==F+1)console.log("out of seq",H.seq,F),U=!0;else F=H.seq}if(F!==void 0)await Z.hosts.touch(Q.label,F);let q=[];for(let H of O){let D=J.deriveCipher(H.kdm,"decrypt"),[x,B]=await v$(H.headEnc,H.bodyCph,D,Y);if(B!==0){console.error("Failed to open body",j[B]);continue}q.push({key:H.headEncHash,data:qZ({head:H.head,body:x.bod})})}let T=await Z.messages.add(q);for(let H=0;H<T.length;H++){let D=T[H];if(D!==0&&D!==15)console.error("ERR storing",j[D],"for message",H)}if(X&&q.length>0)X({phase:"open",host:Q.label,done:q.length,total:q.length});if(U||P||q.length>0)W()}async function KV($,V={}){let Z=V.pull!==!1,J=V.push===!0,{conn:Q,store:Y,enclave:X,host:W,crypto:K,onProgress:G,peekProgressEvery:z,peekConcurrency:R}=$,I=await Q.identity(),[U,w]=await Q.peek(0);if(w!==0)return N(w);let F=U.length,O=z??o0,P=R??wZ;if(G&&F>0)G({phase:"peek",host:W.label,done:0,total:F});let q=0,T=await ZV(U,P,async(L)=>{let[m,S]=await H$(L,I.publicKey,X,K),i;if(S!==0||!m)i={ok:!1,seq:L.seq,stat:S};else{let _=await K.blake3(m.headEnc);i={ok:!0,seq:L.seq,kdm:m.kdm,headEnc:m.headEnc,headEncHash:_}}if(q+=1,G&&VV(q,F,O))G({phase:"peek",host:W.label,done:q,total:F});return i}),H=new Map;for(let L of T){if(!L.ok)continue;let m=E(L.headEncHash),S=H.get(m);if(S)S.count+=1;else H.set(m,{hash:L.headEncHash,count:1,sample:L})}let D=0,x=[];for(let L of H.values()){if(L.count>1)D+=L.count-1;x.push(L.hash)}let B=U.length,k=H.size,f=await r0(x,K),g=[],C=0;for(let L of H.values()){if(await Y.messages.has(L.hash)){await Y.uploads.deq(W.label,[L.hash]);continue}if(C+=1,!Z)continue;let S=L.sample,i=new v(S.headEnc),[_,n]=i.readStruct(J0);if(n!==0){console.error("reconcile: reading msg header",n);continue}g.push({kdm:S.kdm,head:_,seq:S.seq,host:W.label,headEnc:S.headEnc,headEncHash:S.headEncHash})}if(g.length>0)await Y.downloads.enq(g);let y=0;if(J){let L=await Y.messages.listKeys(),m=new Set(H.keys()),S=[];for(let i of L)if(!m.has(E(i)))y+=1,S.push(i);if(S.length>0)await Y.uploads.enq(W.label,S)}else{let L=await Y.messages.listKeys(),m=new Set(H.keys());for(let S of L)if(!m.has(E(S)))y+=1}let l=U.length>0?Math.max(...U.map((L)=>L.seq)):0;if(await Y.hosts.recordStats(W.label,{setLastSeq:l}),G)G({phase:"peek",host:W.label,done:F,total:F});return M({msgcheck:f,numBags:B,uniqueMsgs:k,numDupes:D,missingLocal:C,missingHost:y})}class GV{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new O$;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=o0;lastProgress=$V;scheduledSync;constructor($,V,Z,J,Q,Y=!0,X=QV,W=YV,K){this.clock=$;this.state=V;this.store=Z;this.transport=J;this.crypto=Q;this.forceSkewHandlingByDefault=Y;this.onScheduleSync=K;this.maxPushBytes=X,this.maxPullBytes=W,this.clientState=new T0(()=>this.getClientState()),this.xferState=new T0(()=>this.getXferState()),this.scheduledSync=new e$(zZ,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(G){console.error("Debounced sync failed:",G)}})}emitProgress=($)=>{this.lastProgress=$,this.xferState.emit()};async setSeed($){await this.store.seed.save($),this.clientState.emit()}async getClientState(){let{store:$,connections:V}=this,Z=await $.seed.load(),J=await $.hosts.list(),Q=!1;for(let Y of V.values())if(Y.isConnected()){Q=!0;break}return{hasSeed:Z!==void 0,hasHost:Array.from(J).length>0,connected:Q}}async getXferState(){let{uploads:$,downloads:V}=this.store,Z=await $.count();return{numDownloads:await V.count(),numUploads:Z,progress:this.lastProgress}}apply=($,V)=>{return this.enqueueApplyJob(()=>this.doApply($,V))};async doApply($,V={enqueueUpload:!0,triggerUpload:!0}){let Z=[],J=[];for(let{head:Y,body:X}of $){let W=new b;W.writeStruct(J0,Y);let K=W.result(),G=await this.crypto.blake3(K),z={eid:Y.eid,body:X,apld:b0};if(Y.off!==0)z.off=Y.off;if(Y.ctr!==0)z.ctr=Y.ctr;Z.push(G),J.push({key:G,data:z})}await this.store.messages.add(J),await OZ(this.store,Z,this.crypto);let Q=await this.doApplyHashes(Z);if(V.enqueueUpload){let Y=[];for(let X=0;X<Z.length;X++){let W=Q[X];if(W===0||W===15)Y.push(Z[X])}if(Y.length>0){let X=await this.store.hosts.list();for(let W of X)await this.store.uploads.enq(W.label,Y);this.xferState.emit()}}if(V.triggerUpload)this.scheduleSync();return Q}enqueueApplyJob($){let V=this.applyChain.then($,$);return this.applyChain=V.then(()=>{return},()=>{return}),V}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let $=await this.store.messages.list({apld:b0});if($.length<1)return[];let V=g0($,(Z)=>Z.head);return this.applyStored(V)}applyHashes=($)=>{return this.enqueueApplyJob(()=>this.doApplyHashes($))};async doApplyHashes($){let V=[];for(let Q of $){let Y=await this.store.messages.get(Q);if(Y)V.push(Y)}let Z=await this.applyStored(V),J=new Map;for(let Q=0;Q<V.length;Q++)J.set(E(V[Q].hash),Z[Q]??12);return $.map((Q)=>J.get(E(Q))??13)}async applyStored($){if($.length<1)return[];let V=$.map((Y)=>({...Y.head,bod:Y.body})),Z=await this.state.apply(V),J=[],Q=[];for(let Y=0;Y<$.length;Y++){let X=Z[Y];if(X===0||X===15)J.push($[Y].hash);else if(X!==void 0&&FZ(X))Q.push({key:$[Y].hash,err:X})}if(J.length>0)await this.store.messages.markApplied(J);if(Q.length>0)await this.store.messages.markFailed(Q);return Z}async insertRaw($){let{clock:V,crypto:Z}=this,[J,Q]=await ZZ({now:V.now(),bod:$,crypto:Z});if(Q!==0)return N(Q);let X=(await this.apply([{head:J,body:$}]))[0];if(X!==0&&X!==15)return N(X??12);return M(J)}async makeUpdate($,V){let{clock:Z,crypto:J}=this,Q=Z.now();if($.updatedAt.getTime()>Q.getTime())return N(4);let Y=$.ctr+1,[X,W]=await I$({now:Q,eid:$.eid,ctr:Y,bod:V,crypto:J});if(W!==0)return N(W);return M({head:X,body:V})}async updateWithSkew($,V,Z){if(Z===!1)return N(4);let{clock:J,crypto:Q}=this,Y=J.now(),X=new v($.eid),[W,K]=X.readStruct($0);if(K!==0)return N(K);let G=$.updatedAt.getTime()-W.ts.getTime(),z={eid:$.eid,off:G+1,ctr:$.ctr+1,len:0},I=(await this.apply([{head:z,body:void 0}]))[0];if(I!==0&&I!==15)return N(I??12);if(V===void 0)return M(z);let[U,w]=X$({id:W.id,ts:Y});if(w!==0)return N(w);let[F,O]=await I$({now:Y,eid:U,ctr:0,bod:V,crypto:Q});if(O!==0)return N(O);let q=(await this.apply([{head:F,body:V}]))[0];if(q!==0&&q!==15)return N(q??12);return M(F)}async updateRaw($,V,Z=this.forceSkewHandlingByDefault){if($.updatedAt.getTime()>this.clock.now().getTime())return this.updateWithSkew($,V,Z);return this.enqueueApplyJob(async()=>{let[J,Q]=await this.makeUpdate($,V);if(Q!==0)return N(Q);let X=(await this.doApply([J]))[0];if(X!==0&&X!==15)return N(X??12);return M(J.head)})}async insert($){let{body:V,type:Z,gid:J,pid:Q,tags:Y}=$,W=C0({body:V,type:Z,gid:J,pid:Q,tags:Y});return this.insertRaw(W)}async update($){let{prior:V,body:Z,type:J,gid:Q,pid:Y,tags:X,force:W}=$,G=C0({body:Z,type:J,gid:Q,pid:Y,tags:X});return this.updateRaw(V,G,W??this.forceSkewHandlingByDefault)}async delete($){let V=$.force??!0;if("prior"in $)return this.updateRaw($.prior,void 0,V);let[Z,J]=await this.revFromArchive($.eid);if(J!==0)return N(J);return this.updateRaw(Z,void 0,V)}async revFromArchive($){let V=await this.store.messages.last($);if(V)return GZ(V.head);let Z=new v($),[J,Q]=Z.readStruct($0);if(Q!==0)return N(Q);return M({eid:$,ctr:-1,updatedAt:J.ts})}async genEID($){let{clock:V,crypto:Z}=this,J=V.now();if($!==void 0)return X$({id:$,ts:J});let Q=await Z.genRandomBytes(8);return X$({id:Q,ts:J})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:$,crypto:V,store:Z}=this,J=await Z.seed.load();if(!J)return 22;await this.drainApplyQueue();for(let[Q,Y]of $){let X=await Z.hosts.get(Q);if(!X)continue;let W={conn:Y,store:Z,enclave:J,host:X,crypto:V,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},K=await XV(W);if(K!==0)return console.error(`Failed to peek: ${K}`),this.emitProgress({phase:"idle"}),K;this.xferState.emit();let G=await HZ(W);if(G!==0)return console.error(`Failed to push: ${G}`),this.emitProgress({phase:"idle"}),G;this.xferState.emit();let z=await WV(W,async()=>{await this.drainApplyQueue()});if(z!==0&&z!==15)return console.error(`Failed to pull: ${z}`),this.emitProgress({phase:"idle"}),z;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async rebuild($){if(this.scheduledSync.cancel(),await this.syncRuns.flush(),$?.checkHost??!0){let Z=await this.repull();if(Z!==0)return Z}return this.enqueueApplyJob(()=>this.replay())}async msgcheck(){let $=await this.store.messages.listKeys();return r0($,this.crypto)}listMsgs($){return this.store.messages.list($)}countMsgs($){return this.store.messages.count($)}async reconcile($,V){this.scheduledSync.cancel(),await this.syncRuns.flush();let{connections:Z,crypto:J,store:Q}=this,Y=await Q.seed.load();if(!Y)return N(22);let X=await Q.hosts.get($);if(!X)return N(13);let W=Z.get($);if(!W||!W.isConnected()){if(await this.connectToHost(X,!1,!1),X=await Q.hosts.get($),!X)return N(13);W=Z.get($)}if(!W)return N(12);let K={conn:W,store:Q,enclave:Y,crypto:J,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},[G,z]=await KV({...K,host:X},V);if(this.xferState.emit(),z!==0)return this.emitProgress({phase:"idle"}),N(z);if(!G)return this.emitProgress({phase:"idle"}),N(12);if(V?.sync===!1)return this.emitProgress({phase:"idle"}),M(G);let R=await this.sync();if(R!==0)return N(R);let I=await Q.hosts.get($);if(!I)return N(13);let[U,w]=await KV({...K,host:I},{pull:!1,push:!1});if(this.xferState.emit(),this.emitProgress({phase:"idle"}),w!==0)return N(w);if(!U)return N(12);return M(U)}async repull(){let{connections:$,crypto:V,store:Z}=this,J=await Z.seed.load();if(!J)return 22;let Q=Array.from(await Z.hosts.list());if(Q.length<1)return 0;for(let Y of Q){let X=$.get(Y.label);if(!X||!X.isConnected())await this.connectToHost(Y,!1,!1)}for(let[Y,X]of $){let W=await Z.hosts.get(Y);if(!W)continue;let K={conn:X,store:Z,enclave:J,host:{...W,lastSeq:0},crypto:V,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},G=await XV(K);if(G!==0)return console.error(`rebuild: failed to peek: ${G}`),this.emitProgress({phase:"idle"}),G;this.xferState.emit();let z=await WV(K);if(z!==0&&z!==15)return console.error(`rebuild: failed to pull: ${z}`),this.emitProgress({phase:"idle"}),z;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async replay(){let $=await this.state.clear();if($!==0)return $;let V=await this.store.messages.list(),Z=g0(V,(Y)=>Y.head),J=Z.length;if(J<1)return this.emitProgress({phase:"idle"}),0;let Q=0;while(Q<Z.length){let Y=0,X=0,W=Q;for(let G=Q;G<Z.length&&X<100&&Y<102400;G++)Y+=Z[G].head.len,X++,W=G+1;let K=Z.slice(Q,W);await this.applyStored(K),this.emitProgress({phase:"exec",done:W,total:J}),Q=W}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=$V,this.clientState.emit(),this.xferState.emit()}import=async($,V)=>{let{crypto:Z,store:J}=this,Q=V?.onProgress,Y=await J.seed.load();if(!Y)return 22;console.time("import: decoding file...");let X=await $.bytes(),[W,K]=await VZ(X,Z,Y);if(K!==0)return K;console.timeEnd("import: decoding file...");let G=0;while(G<W.length){let z=0,R=0,I=G;for(let F=G;F<W.length&&R<100&&z<102400;F++)z+=W[F].head.len,R++,I=F+1;let U=W.slice(G,I);console.time(`import: applying [${G}, ${I}]`);let w=await this.apply(U,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${G}, ${I}]`);for(let F=0;F<U.length;F++){let O=w[F];if(O!==0&&O!==15)console.warn(`failed to import msg ${G+F}: ${j[O]}`)}if(Q)queueMicrotask(()=>Q(I,W.length,0));this.emitProgress({phase:"import",done:I,total:W.length}),G=I}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:$,store:V}=this,Z=await V.seed.load();if(!Z)return N(22);let J=await V.messages.list();return $Z("export",0,J,$,Z)}async export($){let[V,Z]=await this.exportBytes();if(Z!==0)return Z;if(!V)return 12;let J=new Blob([V.slice()]);return RZ(J,$),0}async link($,V=!0){if(await this.store.hosts.add($),this.clientState.emit(),V){let Z=await this.store.hosts.get($.label);if(Z)await this.connectToHost(Z)}}async unlink($){await this.store.hosts.del($),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:Y,store:X,transport:W}=this,K=Q.get($.label);if(K){if(K.isConnected())return;try{K.closeListener()}catch{}Q.delete($.label)}let G=await X.seed.load();if(!G)return;console.info(`Connecting to ${$.handle} (${$.label})`);let z=new R$(G,Y,$,J,W($),(R)=>X.hosts.set($.label,R));if(await z.register(),V)await z.listen(async(R)=>{let I={conn:z,store:X,enclave:G,host:$,crypto:Y,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return PZ(R,I,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(Q.set($.label,z),this.clientState.emit(),Z)this.scheduleSync()};async connect($=!0,V=!0){let{connectToHost:Z,scheduleSync:J,store:Q}=this;if(!await Q.seed.load())return;await this.drainApplyQueue();let X=await Q.hosts.list();for(let W of X)await Z(W,$,!1);if(V)J()}disconnect=async()=>{for(let $ of this.connections.values())try{$.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var A0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function C$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function zV($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function c($,...V){if(!zV($))throw Error("Uint8Array expected");if(V.length>0&&!V.includes($.length))throw Error("Uint8Array expected of length "+V+", got length="+$.length)}function NV($,V=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(V&&$.finished)throw Error("Hash#digest() has already been called")}function CZ($,V){c($);let Z=V.outputLen;if($.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function RV($){if(typeof $!=="boolean")throw Error(`boolean expected, not ${$}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var R0=($)=>new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4));var uJ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!uJ)throw Error("Non little-endian hardware is not supported");function lJ($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function T$($){if(typeof $==="string")$=lJ($);else if(zV($))$=A$($);else throw Error("Uint8Array expected, got "+typeof $);return $}function TZ($,V){if(V==null||typeof V!=="object")throw Error("options must be defined");return Object.assign($,V)}function AZ($,V){if($.length!==V.length)return!1;let Z=0;for(let J=0;J<$.length;J++)Z|=$[J]^V[J];return Z===0}var DZ=($,V)=>{function Z(J,...Q){if(c(J),$.nonceLength!==void 0){let z=Q[0];if(!z)throw Error("nonce / iv required");if($.varSizeNonce)c(z);else c(z,$.nonceLength)}let Y=$.tagLength;if(Y&&Q[1]!==void 0)c(Q[1]);let X=V(J,...Q),W=(z,R)=>{if(R!==void 0){if(z!==2)throw Error("cipher output not supported");c(R)}},K=!1;return{encrypt(z,R){if(K)throw Error("cannot encrypt() twice with same key + nonce");return K=!0,c(z),W(X.encrypt.length,R),X.encrypt(z,R)},decrypt(z,R){if(c(z),Y&&z.length<Y)throw Error("invalid ciphertext length: smaller than tagLength="+Y);return W(X.decrypt.length,R),X.decrypt(z,R)}}}return Object.assign(Z,$),Z};function IV($,V,Z=!0){if(V===void 0)return new Uint8Array($);if(V.length!==$)throw Error("invalid output length, expected "+$+", got: "+V.length);if(Z&&!hJ(V))throw Error("invalid output, must be aligned");return V}function hJ($){return $.byteOffset%4===0}function A$($){return Uint8Array.from($)}function K0(...$){for(let V=0;V<$.length;V++)$[V].fill(0)}function D$($=32){if(A0&&typeof A0.getRandomValues==="function")return A0.getRandomValues(new Uint8Array($));if(A0&&typeof A0.randomBytes==="function")return A0.randomBytes($);throw Error("crypto.getRandomValues must be defined")}var jZ=($)=>Uint8Array.from($.split("").map((V)=>V.charCodeAt(0))),pJ=jZ("expand 16-byte k"),nJ=jZ("expand 32-byte k"),cJ=R0(pJ),dJ=R0(nJ);function A($,V){return $<<V|$>>>32-V}function FV($){return $.byteOffset%4===0}var _$=64,rJ=16,LZ=4294967295,_Z=new Uint32Array;function oJ($,V,Z,J,Q,Y,X,W){let K=Q.length,G=new Uint8Array(_$),z=R0(G),R=FV(Q)&&FV(Y),I=R?R0(Q):_Z,U=R?R0(Y):_Z;for(let w=0;w<K;X++){if($(V,Z,J,z,X,W),X>=LZ)throw Error("arx: counter overflow");let F=Math.min(_$,K-w);if(R&&F===_$){let O=w/4;if(w%4!==0)throw Error("arx: invalid block position");for(let P=0,q;P<rJ;P++)q=O+P,U[q]=I[q]^z[P];w+=_$;continue}for(let O=0,P;O<F;O++)P=w+O,Y[P]=Q[P]^G[O];w+=F}}function xZ($,V){let{allowShortKeys:Z,extendNonceFn:J,counterLength:Q,counterRight:Y,rounds:X}=TZ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},V);if(typeof $!=="function")throw Error("core must be a function");return C$(Q),C$(X),RV(Y),RV(Z),(W,K,G,z,R=0)=>{c(W),c(K),c(G);let I=G.length;if(z===void 0)z=new Uint8Array(I);if(c(z),C$(R),R<0||R>=LZ)throw Error("arx: counter overflow");if(z.length<I)throw Error(`arx: output (${z.length}) is shorter than data (${I})`);let U=[],w=W.length,F,O;if(w===32)U.push(F=A$(W)),O=dJ;else if(w===16&&Z)F=new Uint8Array(32),F.set(W),F.set(W,16),O=cJ,U.push(F);else throw Error(`arx: invalid 32-byte key, got length=${w}`);if(!FV(K))U.push(K=A$(K));let P=R0(F);if(J){if(K.length!==24)throw Error("arx: extended nonce must be 24 bytes");J(O,P,R0(K.subarray(0,16)),P),K=K.subarray(16)}let q=16-Q;if(q!==K.length)throw Error(`arx: nonce must be ${q} or 16 bytes`);if(q!==12){let H=new Uint8Array(12);H.set(K,Y?0:12-K.length),K=H,U.push(K)}let T=R0(K);return oJ($,O,P,T,G,z,R,X),K0(...U),z}}var r=($,V)=>$[V++]&255|($[V++]&255)<<8;class EZ{constructor($){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,$=T$($),c($,32);let V=r($,0),Z=r($,2),J=r($,4),Q=r($,6),Y=r($,8),X=r($,10),W=r($,12),K=r($,14);this.r[0]=V&8191,this.r[1]=(V>>>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|Y<<12)&255,this.r[5]=Y>>>1&8190,this.r[6]=(Y>>>14|X<<2)&8191,this.r[7]=(X>>>11|W<<5)&8065,this.r[8]=(W>>>8|K<<8)&8191,this.r[9]=K>>>5&127;for(let G=0;G<8;G++)this.pad[G]=r($,16+2*G)}process($,V,Z=!1){let J=Z?0:2048,{h:Q,r:Y}=this,X=Y[0],W=Y[1],K=Y[2],G=Y[3],z=Y[4],R=Y[5],I=Y[6],U=Y[7],w=Y[8],F=Y[9],O=r($,V+0),P=r($,V+2),q=r($,V+4),T=r($,V+6),H=r($,V+8),D=r($,V+10),x=r($,V+12),B=r($,V+14),k=Q[0]+(O&8191),f=Q[1]+((O>>>13|P<<3)&8191),g=Q[2]+((P>>>10|q<<6)&8191),C=Q[3]+((q>>>7|T<<9)&8191),y=Q[4]+((T>>>4|H<<12)&8191),l=Q[5]+(H>>>1&8191),L=Q[6]+((H>>>14|D<<2)&8191),m=Q[7]+((D>>>11|x<<5)&8191),S=Q[8]+((x>>>8|B<<8)&8191),i=Q[9]+(B>>>5|J),_=0,n=_+k*X+f*(5*F)+g*(5*w)+C*(5*U)+y*(5*I);_=n>>>13,n&=8191,n+=l*(5*R)+L*(5*z)+m*(5*G)+S*(5*K)+i*(5*W),_+=n>>>13,n&=8191;let o=_+k*W+f*X+g*(5*F)+C*(5*w)+y*(5*U);_=o>>>13,o&=8191,o+=l*(5*I)+L*(5*R)+m*(5*z)+S*(5*G)+i*(5*K),_+=o>>>13,o&=8191;let e=_+k*K+f*W+g*X+C*(5*F)+y*(5*w);_=e>>>13,e&=8191,e+=l*(5*U)+L*(5*I)+m*(5*R)+S*(5*z)+i*(5*G),_+=e>>>13,e&=8191;let h=_+k*G+f*K+g*W+C*X+y*(5*F);_=h>>>13,h&=8191,h+=l*(5*w)+L*(5*U)+m*(5*I)+S*(5*R)+i*(5*z),_+=h>>>13,h&=8191;let z0=_+k*z+f*G+g*K+C*W+y*X;_=z0>>>13,z0&=8191,z0+=l*(5*F)+L*(5*w)+m*(5*U)+S*(5*I)+i*(5*R),_+=z0>>>13,z0&=8191;let j0=_+k*R+f*z+g*G+C*K+y*W;_=j0>>>13,j0&=8191,j0+=l*X+L*(5*F)+m*(5*w)+S*(5*U)+i*(5*I),_+=j0>>>13,j0&=8191;let L0=_+k*I+f*R+g*z+C*G+y*K;_=L0>>>13,L0&=8191,L0+=l*W+L*X+m*(5*F)+S*(5*w)+i*(5*U),_+=L0>>>13,L0&=8191;let x0=_+k*U+f*I+g*R+C*z+y*G;_=x0>>>13,x0&=8191,x0+=l*K+L*W+m*X+S*(5*F)+i*(5*w),_+=x0>>>13,x0&=8191;let E0=_+k*w+f*U+g*I+C*R+y*z;_=E0>>>13,E0&=8191,E0+=l*G+L*K+m*W+S*X+i*(5*F),_+=E0>>>13,E0&=8191;let f0=_+k*F+f*w+g*U+C*I+y*R;_=f0>>>13,f0&=8191,f0+=l*z+L*G+m*K+S*W+i*X,_+=f0>>>13,f0&=8191,_=(_<<2)+_|0,_=_+n|0,n=_&8191,_=_>>>13,o+=_,Q[0]=n,Q[1]=o,Q[2]=e,Q[3]=h,Q[4]=z0,Q[5]=j0,Q[6]=L0,Q[7]=x0,Q[8]=E0,Q[9]=f0}finalize(){let{h:$,pad:V}=this,Z=new Uint16Array(10),J=$[1]>>>13;$[1]&=8191;for(let X=2;X<10;X++)$[X]+=J,J=$[X]>>>13,$[X]&=8191;$[0]+=J*5,J=$[0]>>>13,$[0]&=8191,$[1]+=J,J=$[1]>>>13,$[1]&=8191,$[2]+=J,Z[0]=$[0]+5,J=Z[0]>>>13,Z[0]&=8191;for(let X=1;X<10;X++)Z[X]=$[X]+J,J=Z[X]>>>13,Z[X]&=8191;Z[9]-=8192;let Q=(J^1)-1;for(let X=0;X<10;X++)Z[X]&=Q;Q=~Q;for(let X=0;X<10;X++)$[X]=$[X]&Q|Z[X];$[0]=($[0]|$[1]<<13)&65535,$[1]=($[1]>>>3|$[2]<<10)&65535,$[2]=($[2]>>>6|$[3]<<7)&65535,$[3]=($[3]>>>9|$[4]<<4)&65535,$[4]=($[4]>>>12|$[5]<<1|$[6]<<14)&65535,$[5]=($[6]>>>2|$[7]<<11)&65535,$[6]=($[7]>>>5|$[8]<<8)&65535,$[7]=($[8]>>>8|$[9]<<5)&65535;let Y=$[0]+V[0];$[0]=Y&65535;for(let X=1;X<8;X++)Y=($[X]+V[X]|0)+(Y>>>16)|0,$[X]=Y&65535;K0(Z)}update($){NV(this);let{buffer:V,blockLen:Z}=this;$=T$($);let J=$.length;for(let Q=0;Q<J;){let Y=Math.min(Z-this.pos,J-Q);if(Y===Z){for(;Z<=J-Q;Q+=Z)this.process($,Q);continue}if(V.set($.subarray(Q,Q+Y),this.pos),this.pos+=Y,Q+=Y,this.pos===Z)this.process(V,0,!1),this.pos=0}return this}destroy(){K0(this.h,this.r,this.buffer,this.pad)}digestInto($){NV(this),CZ($,this),this.finished=!0;let{buffer:V,h:Z}=this,{pos:J}=this;if(J){V[J++]=1;for(;J<16;J++)V[J]=0;this.process(V,0,!0)}this.finalize();let Q=0;for(let Y=0;Y<8;Y++)$[Q++]=Z[Y]>>>0,$[Q++]=Z[Y]>>>8;return $}digest(){let{buffer:$,outputLen:V}=this;this.digestInto($);let Z=$.slice(0,V);return this.destroy(),Z}}function aJ($){let V=(J,Q)=>$(Q).update(T$(J)).digest(),Z=$(new Uint8Array(32));return V.outputLen=Z.outputLen,V.blockLen=Z.blockLen,V.create=(J)=>$(J),V}var UV=aJ(($)=>new EZ($));function sJ($,V,Z,J,Q,Y=20){let X=$[0],W=V[0],K=V[1],G=V[2],z=V[3],R=$[1],I=Z[0],U=Z[1],w=Q,F=0,O=$[2],P=V[4],q=V[5],T=V[6],H=V[7],D=$[3],x=X,B=W,k=K,f=G,g=z,C=R,y=I,l=U,L=w,m=F,S=O,i=P,_=q,n=T,o=H,e=D;for(let z0=0;z0<Y;z0+=2)g^=A(x+_|0,7),L^=A(g+x|0,9),_^=A(L+g|0,13),x^=A(_+L|0,18),m^=A(C+B|0,7),n^=A(m+C|0,9),B^=A(n+m|0,13),C^=A(B+n|0,18),o^=A(S+y|0,7),k^=A(o+S|0,9),y^=A(k+o|0,13),S^=A(y+k|0,18),f^=A(e+i|0,7),l^=A(f+e|0,9),i^=A(l+f|0,13),e^=A(i+l|0,18),B^=A(x+f|0,7),k^=A(B+x|0,9),f^=A(k+B|0,13),x^=A(f+k|0,18),y^=A(C+g|0,7),l^=A(y+C|0,9),g^=A(l+y|0,13),C^=A(g+l|0,18),i^=A(S+m|0,7),L^=A(i+S|0,9),m^=A(L+i|0,13),S^=A(m+L|0,18),_^=A(e+o|0,7),n^=A(_+e|0,9),o^=A(n+_|0,13),e^=A(o+n|0,18);let h=0;J[h++]=X+x|0,J[h++]=W+B|0,J[h++]=K+k|0,J[h++]=G+f|0,J[h++]=z+g|0,J[h++]=R+C|0,J[h++]=I+y|0,J[h++]=U+l|0,J[h++]=w+L|0,J[h++]=F+m|0,J[h++]=O+S|0,J[h++]=P+i|0,J[h++]=q+_|0,J[h++]=T+n|0,J[h++]=H+o|0,J[h++]=D+e|0}function tJ($,V,Z,J){let Q=$[0],Y=V[0],X=V[1],W=V[2],K=V[3],G=$[1],z=Z[0],R=Z[1],I=Z[2],U=Z[3],w=$[2],F=V[4],O=V[5],P=V[6],q=V[7],T=$[3];for(let D=0;D<20;D+=2)K^=A(Q+O|0,7),I^=A(K+Q|0,9),O^=A(I+K|0,13),Q^=A(O+I|0,18),U^=A(G+Y|0,7),P^=A(U+G|0,9),Y^=A(P+U|0,13),G^=A(Y+P|0,18),q^=A(w+z|0,7),X^=A(q+w|0,9),z^=A(X+q|0,13),w^=A(z+X|0,18),W^=A(T+F|0,7),R^=A(W+T|0,9),F^=A(R+W|0,13),T^=A(F+R|0,18),Y^=A(Q+W|0,7),X^=A(Y+Q|0,9),W^=A(X+Y|0,13),Q^=A(W+X|0,18),z^=A(G+K|0,7),R^=A(z+G|0,9),K^=A(R+z|0,13),G^=A(K+R|0,18),F^=A(w+U|0,7),I^=A(F+w|0,9),U^=A(I+F|0,13),w^=A(U+I|0,18),O^=A(T+q|0,7),P^=A(O+T|0,9),q^=A(P+O|0,13),T^=A(q+P|0,18);let H=0;J[H++]=Q,J[H++]=G,J[H++]=w,J[H++]=T,J[H++]=z,J[H++]=R,J[H++]=I,J[H++]=U}var wV=xZ(sJ,{counterRight:!0,extendNonceFn:tJ}),MV=DZ({blockSize:64,nonceLength:24,tagLength:16},($,V)=>{return{encrypt(Z,J){J=IV(Z.length+32,J,!1);let Q=J.subarray(0,32),Y=J.subarray(32);J.set(Z,32),K0(Q),wV($,V,J,J);let X=UV(Y,Q);return J.set(X,16),K0(J.subarray(0,16),X),J.subarray(16)},decrypt(Z,J){c(Z),J=IV(Z.length+32,J,!1);let Q=J.subarray(0,32),Y=J.subarray(32,48),X=J.subarray(48);J.set(Z,32),K0(Q);let W=wV($,V,Q,Q),K=UV(X,W);if(!AZ(Y,K))throw Error("invalid tag");return wV($,V,J.subarray(16),J.subarray(16)),K0(Q,Y,K),X}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function eJ($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function a0($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function D0($,...V){if(!eJ($))throw Error("Uint8Array expected");if(V.length>0&&!V.includes($.length))throw Error("Uint8Array expected of length "+V+", got length="+$.length)}function s0($,V=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(V&&$.finished)throw Error("Hash#digest() has already been called")}function j$($,V){D0($);let Z=V.outputLen;if($.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function fZ($){return new Uint8Array($.buffer,$.byteOffset,$.byteLength)}function i0($){return new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4))}function y0(...$){for(let V=0;V<$.length;V++)$[V].fill(0)}function t0($,V){return $<<32-V|$>>>V}var SZ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function kZ($){return $<<24&4278190080|$<<8&16711680|$>>>8&65280|$>>>24&255}var BZ=SZ?($)=>$:($)=>kZ($);function $Q($){for(let V=0;V<$.length;V++)$[V]=kZ($[V]);return $}var s=SZ?($)=>$:$Q;function VQ($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function u0($){if(typeof $==="string")$=VQ($);return D0($),$}class OV{}function mZ($){let V=(J,Q)=>$(Q).update(u0(J)).digest(),Z=$({});return V.outputLen=Z.outputLen,V.blockLen=Z.blockLen,V.create=(J)=>$(J),V}var gZ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var L$=BigInt(4294967295),vZ=BigInt(32);function HV($,V=!1){if(V)return{h:Number($&L$),l:Number($>>vZ&L$)};return{h:Number($>>vZ&L$)|0,l:Number($&L$)|0}}function I0($,V,Z,J,Q){return $=$+V+Q|0,J=t0(J^$,16),Z=Z+J|0,V=t0(V^Z,12),{a:$,b:V,c:Z,d:J}}function F0($,V,Z,J,Q){return $=$+V+Q|0,J=t0(J^$,8),Z=Z+J|0,V=t0(V^Z,7),{a:$,b:V,c:Z,d:J}}class qV extends OV{constructor($,V){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,a0($),a0(V),this.blockLen=$,this.outputLen=V,this.buffer=new Uint8Array($),this.buffer32=i0(this.buffer)}update($){s0(this),$=u0($),D0($);let{blockLen:V,buffer:Z,buffer32:J}=this,Q=$.length,Y=$.byteOffset,X=$.buffer;for(let W=0;W<Q;){if(this.pos===V)s(J),this.compress(J,0,!1),s(J),this.pos=0;let K=Math.min(V-this.pos,Q-W),G=Y+W;if(K===V&&!(G%4)&&W+K<Q){let z=new Uint32Array(X,G,Math.floor((Q-W)/4));s(z);for(let R=0;W+V<Q;R+=J.length,W+=V)this.length+=V,this.compress(z,R,!1);s(z);continue}Z.set($.subarray(W,W+K),this.pos),this.pos+=K,this.length+=K,W+=K}return this}digestInto($){s0(this),j$($,this);let{pos:V,buffer32:Z}=this;this.finished=!0,y0(this.buffer.subarray(V)),s(Z),this.compress(Z,0,!0),s(Z);let J=i0($);this.get().forEach((Q,Y)=>J[Y]=BZ(Q))}digest(){let{buffer:$,outputLen:V}=this;this.digestInto($);let Z=$.slice(0,V);return this.destroy(),Z}_cloneInto($){let{buffer:V,length:Z,finished:J,destroyed:Q,outputLen:Y,pos:X}=this;return $||($=new this.constructor({dkLen:Y})),$.set(...this.get()),$.buffer.set(V),$.destroyed=Q,$.finished=J,$.length=Z,$.pos=X,$.outputLen=Y,$}clone(){return this._cloneInto()}}function PV($,V,Z,J,Q,Y,X,W,K,G,z,R,I,U,w,F,O,P,q,T){let H=0;for(let D=0;D<J;D++)({a:Q,b:K,c:I,d:O}=I0(Q,K,I,O,Z[V+$[H++]])),{a:Q,b:K,c:I,d:O}=F0(Q,K,I,O,Z[V+$[H++]]),{a:Y,b:G,c:U,d:P}=I0(Y,G,U,P,Z[V+$[H++]]),{a:Y,b:G,c:U,d:P}=F0(Y,G,U,P,Z[V+$[H++]]),{a:X,b:z,c:w,d:q}=I0(X,z,w,q,Z[V+$[H++]]),{a:X,b:z,c:w,d:q}=F0(X,z,w,q,Z[V+$[H++]]),{a:W,b:R,c:F,d:T}=I0(W,R,F,T,Z[V+$[H++]]),{a:W,b:R,c:F,d:T}=F0(W,R,F,T,Z[V+$[H++]]),{a:Q,b:G,c:w,d:T}=I0(Q,G,w,T,Z[V+$[H++]]),{a:Q,b:G,c:w,d:T}=F0(Q,G,w,T,Z[V+$[H++]]),{a:Y,b:z,c:F,d:O}=I0(Y,z,F,O,Z[V+$[H++]]),{a:Y,b:z,c:F,d:O}=F0(Y,z,F,O,Z[V+$[H++]]),{a:X,b:R,c:I,d:P}=I0(X,R,I,P,Z[V+$[H++]]),{a:X,b:R,c:I,d:P}=F0(X,R,I,P,Z[V+$[H++]]),{a:W,b:K,c:U,d:q}=I0(W,K,U,q,Z[V+$[H++]]),{a:W,b:K,c:U,d:q}=F0(W,K,U,q,Z[V+$[H++]]);return{v0:Q,v1:Y,v2:X,v3:W,v4:K,v5:G,v6:z,v7:R,v8:I,v9:U,v10:w,v11:F,v12:O,v13:P,v14:q,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},U0=gZ.slice(),bZ=(()=>{let $=Array.from({length:16},(J,Q)=>Q),V=(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=$;J<7;J++,Q=V(Q))Z.push(...Q);return Uint8Array.from(Z)})();class CV extends qV{constructor($={},V=0){super(64,$.dkLen===void 0?32:$.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}=$,Q=J!==void 0;if(Z!==void 0){if(Q)throw Error('Only "key" or "context" can be specified at same time');let Y=u0(Z).slice();D0(Y,32),this.IV=i0(Y),s(this.IV),this.flags=V|G0.KEYED_HASH}else if(Q){let Y=u0(J),X=new CV({dkLen:32},G0.DERIVE_KEY_CONTEXT).update(Y).digest();this.IV=i0(X),s(this.IV),this.flags=V|G0.DERIVE_KEY_MATERIAL}else this.IV=U0.slice(),this.flags=V;this.state=this.IV.slice(),this.bufferOut=fZ(this.bufferOut32)}get(){return[]}set(){}b2Compress($,V,Z,J=0){let{state:Q,pos:Y}=this,{h:X,l:W}=HV(BigInt($),!0),{v0:K,v1:G,v2:z,v3:R,v4:I,v5:U,v6:w,v7:F,v8:O,v9:P,v10:q,v11:T,v12:H,v13:D,v14:x,v15:B}=PV(bZ,J,Z,7,Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7],U0[0],U0[1],U0[2],U0[3],X,W,Y,V);Q[0]=K^O,Q[1]=G^P,Q[2]=z^q,Q[3]=R^T,Q[4]=I^H,Q[5]=U^D,Q[6]=w^x,Q[7]=F^B}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 Y,X=this.chunksDone+1;Z||!(X&1);X>>=1){if(!(Y=this.stack.pop()))break;this.buffer32.set(Y,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($){$=super._cloneInto($);let{IV:V,flags:Z,state:J,chunkPos:Q,posOut:Y,chunkOut:X,stack:W,chunksDone:K}=this;return $.state.set(J.slice()),$.stack=W.map((G)=>Uint32Array.from(G)),$.IV.set(V),$.flags=Z,$.chunkPos=Q,$.chunksDone=K,$.posOut=Y,$.chunkOut=X,$.enableXOF=this.enableXOF,$.bufferOut32.set(this.bufferOut32),$}destroy(){this.destroyed=!0,y0(this.state,this.buffer32,this.IV,this.bufferOut32),y0(...this.stack)}b2CompressOut(){let{state:$,pos:V,flags:Z,buffer32:J,bufferOut32:Q}=this,{h:Y,l:X}=HV(BigInt(this.chunkOut++));s(J);let{v0:W,v1:K,v2:G,v3:z,v4:R,v5:I,v6:U,v7:w,v8:F,v9:O,v10:P,v11:q,v12:T,v13:H,v14:D,v15:x}=PV(bZ,0,J,7,$[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],U0[0],U0[1],U0[2],U0[3],X,Y,V,Z);Q[0]=W^F,Q[1]=K^O,Q[2]=G^P,Q[3]=z^q,Q[4]=R^T,Q[5]=I^H,Q[6]=U^D,Q[7]=w^x,Q[8]=$[0]^F,Q[9]=$[1]^O,Q[10]=$[2]^P,Q[11]=$[3]^q,Q[12]=$[4]^T,Q[13]=$[5]^H,Q[14]=$[6]^D,Q[15]=$[7]^x,s(J),s(Q),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,y0(this.buffer.subarray(this.pos));let $=this.flags|G0.ROOT;if(this.stack.length)$|=G0.PARENT,s(this.buffer32),this.compress(this.buffer32,0,!0),s(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else $|=(!this.chunkPos?G0.CHUNK_START:0)|G0.CHUNK_END;this.flags=$,this.b2CompressOut()}writeInto($){s0(this,!1),D0($),this.finish();let{blockLen:V,bufferOut:Z}=this;for(let J=0,Q=$.length;J<Q;){if(this.posOut>=V)this.b2CompressOut();let Y=Math.min(V-this.posOut,Q-J);$.set(Z.subarray(this.posOut,this.posOut+Y),J),this.posOut+=Y,J+=Y}return $}xofInto($){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto($)}xof($){return a0($),this.xofInto(new Uint8Array($))}digestInto($){if(j$($,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto($),this.destroy(),$}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var iZ=mZ(($)=>new CV($));var TV=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function yZ($){let V=new Uint8Array(TV.length+32);return V.set(TV),V.set($.subarray(0,32),TV.length),V}function uZ($){return typeof $==="string"?new TextEncoder().encode($):$}function l0($){let V=new ArrayBuffer($.byteLength);return new Uint8Array(V).set($),V}class AV{verifyKeys=new Map;signKeys=new Map;async genRandomBytes($){return D$($)}async gen256BitSecureRandomSeed(){return D$(32)}async encryptXSalsa20Poly1305Combined($,V){let Z=D$(24),Q=MV(V,Z).encrypt($);return new Uint8Array([...Z,...Q])}async decryptXSalsa20Poly1305Combined($,V){let Z=$.slice(0,24),J=$.slice(24);return MV(V,Z).decrypt(J)}async deriveEd25519KeyPair($){let V=$,Z=yZ(V),J=await globalThis.crypto.subtle.importKey("pkcs8",l0(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 Y=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:Q.x},{name:"Ed25519"},!0,["verify"]),X=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",Y)),W=new Uint8Array(64);return W.set(V,0),W.set(X,32),this.signKeys.set(X0(V),J),this.verifyKeys.set(X0(X),Y),{keyType:"ed25519",privateKey:W,publicKey:X}}async importSignKey($){let V=$.subarray(0,32),Z=X0(V),J=this.signKeys.get(Z);if(J)return J;let Q=yZ(V),Y=await globalThis.crypto.subtle.importKey("pkcs8",l0(Q),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Z,Y),Y}async importVerifyKey($){let V=X0($),Z=this.verifyKeys.get(V);if(Z)return Z;let J=await globalThis.crypto.subtle.importKey("raw",l0($),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set(V,J),J}async signEd25519($,V){let Z=uZ($),J=await this.importSignKey(V),Q=await globalThis.crypto.subtle.sign({name:"Ed25519"},J,l0(Z));return new Uint8Array(Q)}async checkSigEd25519($,V,Z){let J=uZ(V);try{let Q=await this.importVerifyKey(Z);return await globalThis.crypto.subtle.verify({name:"Ed25519"},Q,l0($),l0(J))}catch{return!1}}async blake3($){return iZ($)}}var ZQ=new AV,_0=ZQ;class DV{db;constructor($){this.db=$}async enq($){let V=[...$];if(V.length===0)return;let Z=this.db.transaction(Q0,"readwrite"),J=Z.objectStore(Q0);return new Promise((Q,Y)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>Y(Z.error);for(let X of V){let W=`${X.host}:${X.seq}`;J.put(X,W)}})}async deq($,V){let Z=[...V];if(Z.length===0)return;let J=this.db.transaction(Q0,"readwrite"),Q=J.objectStore(Q0);return new Promise((Y,X)=>{J.oncomplete=()=>Y(),J.onerror=()=>X(J.error);for(let W of Z){let K=`${$}:${W}`;Q.delete(K)}})}async list(){let V=this.db.transaction(Q0,"readonly").objectStore(Q0);return new Promise((Z,J)=>{let Q=V.getAll();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async count(){let V=this.db.transaction(Q0,"readonly").objectStore(Q0);return new Promise((Z,J)=>{let Q=V.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let $=this.db.transaction(Q0,"readwrite"),V=$.objectStore(Q0);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),V.clear()})}}function lZ($){return{label:$.label,handle:new URL($.handle),idx:$.idx,lastSeq:$.lastSeq||0,clockOffset:$.clockOffset,subscription:$.subscription}}function JQ($,V){let Z={...$};if(V.setLastSeq!==void 0)Z.lastSeq=V.setLastSeq;else if(V.lastSeq!==void 0){let J=Z.lastSeq||0;if(V.lastSeq>J)Z.lastSeq=V.lastSeq}return delete Z.numBags,delete Z.numDupes,Z}class _V{db;constructor($){this.db=$}async add($){return this.put({...$,lastSeq:0})}async put($){let V={...$,handle:$.handle.toString(),lastSeq:$.lastSeq??0},Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,Y)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>Y(Z.error),J.put(V)})}async touch($,V){return this.recordStats($,{lastSeq:V})}async recordStats($,V){let Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,Y)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>Y(Z.error);let X=J.get($);X.onsuccess=()=>{let W=X.result;if(!W)return;J.put(JQ(W,V))}})}async get($){let Z=this.db.transaction(t,"readonly").objectStore(t);return new Promise((J,Q)=>{let Y=Z.get($);Y.onsuccess=()=>{let X=Y.result;if(!X)J(void 0);else J(lZ(X))},Y.onerror=()=>Q(Y.error)})}async set($,V){let Z=await this.get($);if(!Z)return 13;try{return await this.put({...Z,...V}),0}catch{return 18}}async del($){let V=this.db.transaction(t,"readwrite"),Z=V.objectStore(t);return new Promise((J,Q)=>{V.oncomplete=()=>J(),V.onerror=()=>Q(V.error),Z.delete($)})}async list(){let V=this.db.transaction(t,"readonly").objectStore(t);return new Promise((Z,J)=>{let Q=V.getAll();Q.onsuccess=()=>{let Y=Q.result;Z(Y.map(lZ))},Q.onerror=()=>J(Q.error)})}async wipe(){let $=this.db.transaction(t,"readwrite"),V=$.objectStore(t);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),V.clear()})}}class jV{crypto;db;constructor($,V){this.crypto=V;this.db=$}async add($){let V=this.db.transaction(u,"readwrite"),Z=V.objectStore(u);return new Promise((J)=>{if($.length===0){J([]);return}let Q=Array($.length).fill(0);V.oncomplete=()=>J(Q),V.onerror=()=>{for(let Y=0;Y<Q.length;Y++)Q[Y]=18;J(Q)};for(let Y=0;Y<$.length;Y++){let{key:X,data:W}=$[Y],K=E(X),G=Z.put(W,K);G.onerror=(z)=>{z.preventDefault(),Q[Y]=18}}})}async del($){let V=[...$];if(V.length===0)return;let Z=this.db.transaction(u,"readwrite"),J=Z.objectStore(u);return new Promise((Q,Y)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>Y(Z.error);for(let X of V){let W=E(X);J.delete(W)}})}async get($){let Z=this.db.transaction(u,"readonly").objectStore(u);return new Promise((J,Q)=>{let Y=E($),X=Z.get(Y);X.onsuccess=async()=>{let W=X.result;if(W)J(await P$($,W,this.crypto));else J(void 0)},X.onerror=()=>Q(X.error)})}async has($){return await this.get($)!==void 0}async list($){let V=$?.apld,Z=$?.body!==!1,Q=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Y,X)=>{let W=[],K=V===void 0?Q.openCursor():Q.index(e0).openCursor(IDBKeyRange.only(V));K.onsuccess=(G)=>{let z=G.target.result;if(z){let R=V===void 0?z.key:z.primaryKey,I=z.value;W.push({hash:N0(R),data:I}),z.continue()}else Promise.all(W.map(({hash:R,data:I})=>P$(R,I,this.crypto,{body:Z}))).then(Y).catch(X)},K.onerror=()=>X(K.error)})}async count($){let Z=this.db.transaction(u,"readonly").objectStore(u);return new Promise((J,Q)=>{let Y=$===void 0?Z.count():Z.index(e0).count(IDBKeyRange.only($));Y.onsuccess=()=>J(Y.result),Y.onerror=()=>Q(Y.error)})}async listKeys(){let V=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let Q=[],Y=V.openKeyCursor();Y.onsuccess=(X)=>{let W=X.target.result;if(W)Q.push(N0(W.key)),W.continue();else Z(Q)},Y.onerror=()=>J(Y.error)})}async last($){let Z=this.db.transaction(u,"readonly").objectStore(u);return new Promise((J,Q)=>{let Y,X=Z.openCursor();X.onsuccess=async(W)=>{let K=W.target.result;if(K){let{key:G,value:z}=K;if(V0($,z.eid)){if(!Y||(z.ctr??0)>(Y.data.ctr??0)||(z.ctr??0)===(Y.data.ctr??0)&&(z.off??0)>(Y.data.off??0))Y={key:G,data:z}}K.continue()}else if(Y){let G=N0(Y.key);J(await P$(G,Y.data,this.crypto))}else J(void 0)},X.onerror=()=>Q(X.error)})}async markApplied($){let V=[...$];if(V.length===0)return;let Z=this.db.transaction(u,"readwrite"),J=Z.objectStore(u);return new Promise((Q,Y)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>Y(Z.error);for(let X of V){let W=E(X),K=J.get(W);K.onsuccess=()=>{let G=K.result;if(!G)return;JV(G,q$),J.put(G,W)},K.onerror=(G)=>{G.preventDefault()}}})}async markFailed($){let V=[...$];if(V.length===0)return;let Z=this.db.transaction(u,"readwrite"),J=Z.objectStore(u);return new Promise((Q,Y)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>Y(Z.error);for(let{key:X,err:W}of V){let K=E(X),G=J.get(K);G.onsuccess=()=>{let z=G.result;if(!z)return;JV(z,v0,W),J.put(z,K)},G.onerror=(z)=>{z.preventDefault()}}})}async wipe(){let $=this.db.transaction(u,"readwrite"),V=$.objectStore(u);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),V.clear()})}}class x${#J;#$;constructor($,V){this.#J=$,this.#$=V}deriveCipher($,V){let Z=$.slice(),J=(X)=>this.#Q(Z,X),Q=(X)=>this.#Y(Z,X);return{encrypt:Object.freeze({encrypt:J}),decrypt:Object.freeze({decrypt:Q}),both:Object.freeze({encrypt:J,decrypt:Q})}[V]}async deriveIdentity($,V=0){let Z=$,J=V,Q=await this.#Z(Z,J);return Object.freeze({publicKey:Q.publicKey,sign:(Y)=>this.#W(Z,J,Y),kdmFor:(Y)=>this.#K(Z,J,Y)})}async#Q($,V){let Z=await this.#V($);return this.#$.encryptXSalsa20Poly1305Combined(V,Z)}async#Y($,V){let Z=await this.#V($);return this.#$.decryptXSalsa20Poly1305Combined(V,Z)}async#V($){return this.#$.blake3(K$(this.#J,$))}async#X($,V){let Z=new TextEncoder().encode($),J=new Uint8Array(8);return new DataView(J.buffer).setBigUint64(0,BigInt(V),!1),await this.#V(K$(Z,J))}async#Z($,V){let Z=await this.#X($,V);return this.#$.deriveEd25519KeyPair(Z)}async#W($,V,Z){let J=await this.#Z($,V);return this.#$.signEd25519(Z,J.privateKey)}async#K($,V,Z){let J=await this.#Z($,V),Q=K$(J.privateKey,Z);return(await this.#$.blake3(Q)).slice(0,O0)}}class LV{enclave;db;constructor($){this.db=$}async save($){let V=X0($),Z=this.db.transaction(w0,"readwrite"),J=Z.objectStore(w0);return new Promise((Q,Y)=>{Z.oncomplete=()=>{this.enclave=new x$($,_0),Q(this.enclave)},Z.onerror=()=>Y(Z.error),J.put(V,"seed")})}async load(){if(this.enclave)return this.enclave;let V=this.db.transaction(w0,"readonly").objectStore(w0);return new Promise((Z,J)=>{let Q=V.get("seed");Q.onsuccess=()=>{let Y=Q.result;if(!Y)Z(void 0);else{let X=W$(Y);this.enclave=new x$(X,_0),Z(this.enclave)}},Q.onerror=()=>J(Q.error)})}async wipe(){this.enclave=void 0;let $=this.db.transaction(w0,"readwrite"),V=$.objectStore(w0);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),V.delete("seed")})}}class xV{db;constructor($){this.db=$}async enq($,V){let Z=[...V];if(Z.length===0)return;let J=this.db.transaction(Y0,"readwrite"),Q=J.objectStore(Y0);return new Promise((Y,X)=>{J.oncomplete=()=>Y(),J.onerror=()=>X(J.error);for(let W of Z){let K=X0(W);Q.put({host:$,hash:K})}})}async deq($,V){let Z=[...V];if(Z.length===0)return;let J=this.db.transaction(Y0,"readwrite"),Q=J.objectStore(Y0);return new Promise((Y,X)=>{J.oncomplete=()=>Y(),J.onerror=()=>X(J.error);for(let W of Z){let K=X0(W);Q.delete([$,K])}})}async list($){let Z=this.db.transaction(Y0,"readonly").objectStore(Y0);return new Promise((J,Q)=>{let Y=Z.getAll();Y.onsuccess=()=>{let W=Y.result.filter((K)=>K.host===$).map((K)=>K.hash);J(W.map((K)=>W$(K)))},Y.onerror=()=>Q(Y.error)})}async count(){let V=this.db.transaction(Y0,"readonly").objectStore(Y0);return new Promise((Z,J)=>{let Q=V.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let $=this.db.transaction(Y0,"readwrite"),V=$.objectStore(Y0);return new Promise((Z,J)=>{$.oncomplete=()=>Z(),$.onerror=()=>J($.error),V.clear()})}}var w0="seedMeta",t="hosts",Y0="uploadQueue",Q0="downloadQueue",u="messages",e0="apld",hZ=3;class nZ{seed;hosts;uploads;downloads;messages;db;constructor($,V){this.db=$,this.seed=new LV($),this.hosts=new _V($),this.uploads=new xV($),this.downloads=new DV($),this.messages=new jV($,V)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}var pZ="diplomatic-store-db";async function QQ(){return new Promise(($,V)=>{let Z=indexedDB.open(pZ,hZ);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!J.objectStoreNames.contains(w0))J.createObjectStore(w0);if(!J.objectStoreNames.contains(t))J.createObjectStore(t,{keyPath:"label"});if(!J.objectStoreNames.contains(Y0))J.createObjectStore(Y0,{keyPath:["host","hash"]});if(!J.objectStoreNames.contains(Q0))J.createObjectStore(Q0);let Y;if(!J.objectStoreNames.contains(u))Y=J.createObjectStore(u);else{if(!Q)throw Error("missing upgrade transaction for messages store");Y=Q.objectStore(u)}if(!Y.indexNames.contains(e0))Y.createIndex(e0,"apld",{unique:!1})},Z.onblocked=()=>{console.warn(`[DIPLOMATIC] protocol store IDB upgrade blocked (${pZ} → v${hZ}); waiting for other connections to close`)},Z.onsuccess=()=>{let J=Z.result;J.onversionchange=()=>{J.close()},$(J)},Z.onerror=()=>V(Z.error??Error("protocol store IndexedDB open failed"))})}async function cZ($){let V=await QQ();if(typeof navigator<"u"&&navigator.storage?.persist)try{await Promise.race([navigator.storage.persist(),new Promise((Z)=>{setTimeout(()=>Z(!1),2000)})])}catch{}return new nZ(V,$)}class EV{client;entDB;post;whenReady;resolveReady;rejectReady;constructor($){this.post=$,this.whenReady=new Promise((V,Z)=>{this.resolveReady=V,this.rejectReady=Z})}async init(){try{let $=await cZ(_0),V=await KZ({cache:!1}),Z=new U$(V.apply,()=>V.clear(),(Y)=>{if(Y.length<1)return;this.post({kind:"dirty",eids:Y.map((X)=>X.slice())})}),J=Z.clear;Z.clear=async()=>{let Y=await J();if(Y===0)this.post({kind:"wiped"});return Y};let Q=new GV(new b$,Z,$,eV,_0);this.client=Q,this.entDB=V,Q.clientState.listen(()=>{this.emitClientState()}),Q.xferState.listen(()=>{this.emitXferState()}),await this.emitClientState(),await this.emitXferState(),this.post({kind:"ready"}),this.markReady()}catch($){let V=$ instanceof Error?$:Error(String($));throw this.post({kind:"initError",message:V.message}),this.failReady(V),V}}markReady(){let $=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,$)$()}failReady($){let V=this.rejectReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V($)}requireClient(){if(!this.client)throw Error("WorkerRuntime not initialized");return this.client}async emitClientState(){let $=this.client;if(!$)return;let V=await $.clientState.get();this.post({kind:"clientState",state:V})}async emitXferState(){let $=this.client;if(!$)return;let V=await $.xferState.get();this.post({kind:"xferState",state:V})}hostFromSerialized($){return{handle:new URL($.handle),label:$.label,idx:$.idx}}async handle($){await this.whenReady;let V=this.requireClient();switch($.op){case"ping":return"pong";case"setSeed":{await V.setSeed(YQ($.seed));return}case"link":{await V.link(this.hostFromSerialized($.host),$.connect??!0);return}case"unlink":{await V.unlink($.label);return}case"connect":{await V.connect($.listen??!0,$.sync??!0);return}case"disconnect":{await V.disconnect();return}case"sync":return await V.sync();case"rebuild":return await V.rebuild({checkHost:$.checkHost??!0});case"reconcile":{let[Z,J]=await V.reconcile($.hostLabel,{pull:$.pull,push:$.push,sync:$.sync});if(J!==0)throw new W0(J);if(!Z)throw new W0(12);return Z}case"msgcheck":return await V.msgcheck();case"entcheck":{let Z=this.entDB;if(!Z)throw new W0(12);let[J,Q]=await Z.checksum(_0);if(Q!==0)throw new W0(Q);if(!J)throw new W0(12);return J}case"wipe":{await V.wipe();return}case"import":{let Z=$.bytes.slice(),J=new Blob([Z]),Q=new File([J],"import.dip");return await V.import(Q)}case"export":{let[Z,J]=await V.exportBytes();if(J!==0)throw new W0(J);if(!Z)throw new W0(12);return Z}case"getClientState":return await V.clientState.get();case"getXferState":return await V.xferState.get();default:{let Z=$;throw Error("unknown worker command")}}}}class W0 extends Error{status;constructor($){super(`WorkerStatusError: ${j[$]}`);this.status=$;this.name="WorkerStatusError"}}function E$($,V){return{kind:"reply",id:$,ok:!0,result:V}}function fV($,V){return{kind:"reply",id:$,ok:!1,status:V}}function YQ($){if($.length!==32)throw new W0(10);return $}var P0=globalThis,dZ=new EV(($,V)=>{if(V&&V.length>0)P0.postMessage($,V);else P0.postMessage($)});P0.onmessage=($)=>{let V=$.data;if(!mV(V))return;XQ(V)};async function XQ($){try{let V=await dZ.handle($);if(($.op==="export"||$.op==="msgcheck"||$.op==="entcheck")&&V instanceof Uint8Array){let Z=V.slice();P0.postMessage(E$($.id,Z),[Z.buffer]);return}if($.op==="reconcile"&&V&&typeof V==="object"&&"msgcheck"in V&&V.msgcheck instanceof Uint8Array){let Z=V.msgcheck.slice(),J={...V,msgcheck:Z};P0.postMessage(E$($.id,J),[Z.buffer]);return}P0.postMessage(E$($.id,V))}catch(V){if(V instanceof W0){P0.postMessage(fV($.id,V.status));return}console.error("worker command failed",V),P0.postMessage(fV($.id,12))}}dZ.init().catch(($)=>{console.error("worker init failed",$)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@interncom/diplomatic",
3
- "version": "0.8.2",
3
+ "version": "0.8.4",
4
4
  "type": "module",
5
5
  "description": "Secure sync layer and CLI utilities for DIPLOMATIC",
6
6
  "files": [