@interncom/diplomatic 0.11.2 → 0.11.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.
@@ -22,7 +22,7 @@ import type { ApldState, Applier, HostStatsUpdate, IClient, IDiplomaticClientSta
22
22
  import { APLD_APPLIED, APLD_ERROR, APLD_PENDING, apldFromStored, isApldState, isPendingApply, isTerminalApplyFailure, setApld } from "./types";
23
23
  import type { SyncProgressEvent } from "./progress";
24
24
  import { defaultPeekProgressEvery, idleProgress, shouldEmitItemProgress } from "./progress";
25
- import { clearLargeBlobSeed, createLargeBlobCred, discoverLargeBlobSeed, largeBlobCapable, PasskeySeedStore, readLargeBlobSeed, readLargeBlobUnlock, storeSeedLargeBlob, writeLargeBlobSeed } from "./passkey/seed";
25
+ import { clearLargeBlobSeed, createLargeBlobCred, defaultWebAuthnRpId, discoverLargeBlobSeed, largeBlobCapable, PasskeySeedStore, readLargeBlobSeed, readLargeBlobUnlock, storeSeedLargeBlob, writeLargeBlobSeed } from "./passkey/seed";
26
26
  import type { LargeBlobRp, LargeBlobUnlock } from "./passkey/seed";
27
27
  import { checksumEntRevs, checksumSet, cmpBytes, encodeEntRev } from "./shared/checksum";
28
28
  import { openDiplomaticClient, type OpenDiplomaticClientMainOptions, type OpenDiplomaticClientOptions, type OpenDiplomaticClientWorkerOptions, type OpenedDiplomaticClient } from "./openClient";
@@ -33,5 +33,5 @@ export declare function genWebClient(stateMgr: IStateManager, url: URL): Promise
33
33
  client: SyncClient<URL>;
34
34
  setSeed: (seedHex: string) => Promise<void>;
35
35
  }>;
36
- export { APLD_APPLIED, APLD_ERROR, APLD_PENDING, apldFromStored, b64tob, btob64, btoh, CachedEntDB, checksumEntRevs, checksumSet, clearLargeBlobSeed, Clock, cmpBytes, createLargeBlobCred, crypto, Decoder, defaultPeekProgressEvery, discoverLargeBlobSeed, eidCodec, encodeEntRev, Encoder, EntDBMemory, EntIDB, EntitiesQuery, EntityID, entStateManager, genSingletonEID, GroupID, hostHTTPTransport, htob, HTTPTransport, IDBStore, idleProgress, IEntDB, IEntity, isApldState, isLiveEnt, isPendingApply, isTerminalApplyFailure, isTombstone, IStore, largeBlobCapable, MasterSeed, MemoryStore, normalizeTags, nullEntDB, nullStateManager, openDiplomaticClient, openEntDB, openIDBStore, PasskeySeedStore, readLargeBlobSeed, readLargeBlobUnlock, revFromEntity, revFromHead, setApld, shouldEmitItemProgress, SingletonStateManager, StateManager, Status, storeSeedLargeBlob, SyncClient, TypedEventEmitter, useClient, useClientState, useClientXferState, useStateWatcher, useStateWatcherSuspense, useSyncOnResume, WorkerClient, writeLargeBlobSeed, };
36
+ export { APLD_APPLIED, APLD_ERROR, APLD_PENDING, apldFromStored, b64tob, btob64, btoh, CachedEntDB, checksumEntRevs, checksumSet, clearLargeBlobSeed, Clock, cmpBytes, createLargeBlobCred, crypto, Decoder, defaultPeekProgressEvery, defaultWebAuthnRpId, discoverLargeBlobSeed, eidCodec, encodeEntRev, Encoder, EntDBMemory, EntIDB, EntitiesQuery, EntityID, entStateManager, genSingletonEID, GroupID, hostHTTPTransport, htob, HTTPTransport, IDBStore, idleProgress, IEntDB, IEntity, isApldState, isLiveEnt, isPendingApply, isTerminalApplyFailure, isTombstone, IStore, largeBlobCapable, MasterSeed, MemoryStore, normalizeTags, nullEntDB, nullStateManager, openDiplomaticClient, openEntDB, openIDBStore, PasskeySeedStore, readLargeBlobSeed, readLargeBlobUnlock, revFromEntity, revFromHead, setApld, shouldEmitItemProgress, SingletonStateManager, StateManager, Status, storeSeedLargeBlob, SyncClient, TypedEventEmitter, useClient, useClientState, useClientXferState, useStateWatcher, useStateWatcherSuspense, useSyncOnResume, WorkerClient, writeLargeBlobSeed, };
37
37
  export type { ApldState, Applier, CachedEntDBOptions, EntDBMemoryOptions, HostHandle, HostStatsUpdate, IClient, ICrypto, IDeleteParams, IDiplomaticClientState, IEntRev, IEntRow, IHostConnectionInfo, IHostRow, IMessage, IMutateOp, IOp, IStateManager, IStoredMessage, IStoredMessageData, IStoredMessageWrite, ITombstone, ITransport, IUpdateParams, LargeBlobRp, LargeBlobUnlock, ListMsgsOpts, OpenDiplomaticClientMainOptions, OpenDiplomaticClientOptions, OpenDiplomaticClientWorkerOptions, OpenedDiplomaticClient, OpenEntDBOptions, ReconcileOpts, ReconcileReport, SetSeedOpts, SyncProgressEvent, WipeOpts, WorkerClientOptions, };
@@ -1 +1 @@
1
- function zQ($){let V=$.length,Q=0,Z=0;while(Z<V){let J=$.charCodeAt(Z++);if((J&4294967168)===0){Q++;continue}else if((J&4294965248)===0)Q+=2;else{if(J>=55296&&J<=56319){if(Z<V){let W=$.charCodeAt(Z);if((W&64512)===56320)++Z,J=((J&1023)<<10)+(W&1023)+65536}}if((J&4294901760)===0)Q+=3;else Q+=4}}return Q}function mZ($,V,Q){let Z=$.length,J=Q,W=0;while(W<Z){let Y=$.charCodeAt(W++);if((Y&4294967168)===0){V[J++]=Y;continue}else if((Y&4294965248)===0)V[J++]=Y>>6&31|192;else{if(Y>=55296&&Y<=56319){if(W<Z){let X=$.charCodeAt(W);if((X&64512)===56320)++W,Y=((Y&1023)<<10)+(X&1023)+65536}}if((Y&4294901760)===0)V[J++]=Y>>12&15|224,V[J++]=Y>>6&63|128;else V[J++]=Y>>18&7|240,V[J++]=Y>>12&63|128,V[J++]=Y>>6&63|128}V[J++]=Y&63|128}}var BZ=new TextEncoder,kZ=50;function gZ($,V,Q){BZ.encodeInto($,V.subarray(Q))}function IQ($,V,Q){if($.length>kZ)gZ($,V,Q);else mZ($,V,Q)}var vZ=4096;function ZV($,V,Q){let Z=V,J=Z+Q,W=[],Y="";while(Z<J){let X=$[Z++];if((X&128)===0)W.push(X);else if((X&224)===192){let G=$[Z++]&63;W.push((X&31)<<6|G)}else if((X&240)===224){let G=$[Z++]&63,K=$[Z++]&63;W.push((X&31)<<12|G<<6|K)}else if((X&248)===240){let G=$[Z++]&63,K=$[Z++]&63,I=$[Z++]&63,R=(X&7)<<18|G<<12|K<<6|I;if(R>65535)R-=65536,W.push(R>>>10&1023|55296),R=56320|R&1023;W.push(R)}else W.push(X);if(W.length>=vZ)Y+=String.fromCharCode(...W),W.length=0}if(W.length>0)Y+=String.fromCharCode(...W);return Y}var iZ=new TextDecoder,yZ=200;function uZ($,V,Q){let Z=$.subarray(V,V+Q);return iZ.decode(Z)}function RQ($,V,Q){if(Q>yZ)return uZ($,V,Q);else return ZV($,V,Q)}class l0{type;data;constructor($,V){this.type=$,this.data=V}}class V0 extends Error{constructor($){super($);let V=Object.create(V0.prototype);Object.setPrototypeOf(this,V),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:V0.name})}}var p0=4294967295;function NQ($,V,Q){let Z=Q/4294967296,J=Q;$.setUint32(V,Z),$.setUint32(V+4,J)}function C$($,V,Q){let Z=Math.floor(Q/4294967296),J=Q;$.setUint32(V,Z),$.setUint32(V+4,J)}function w$($,V){let Q=$.getInt32(V),Z=$.getUint32(V+4);return Q*4294967296+Z}function UQ($,V){let Q=$.getUint32(V),Z=$.getUint32(V+4);return Q*4294967296+Z}var bZ=-1,hZ=4294967295,lZ=17179869183;function pZ({sec:$,nsec:V}){if($>=0&&V>=0&&$<=lZ)if(V===0&&$<=hZ){let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,$),Q}else{let Q=$/4294967296,Z=$&4294967295,J=new Uint8Array(8),W=new DataView(J.buffer);return W.setUint32(0,V<<2|Q&3),W.setUint32(4,Z),J}else{let Q=new Uint8Array(12),Z=new DataView(Q.buffer);return Z.setUint32(0,V),C$(Z,4,$),Q}}function nZ($){let V=$.getTime(),Q=Math.floor(V/1000),Z=(V-Q*1000)*1e6,J=Math.floor(Z/1e9);return{sec:Q+J,nsec:Z-J*1e9}}function cZ($){if($ instanceof Date){let V=nZ($);return pZ(V)}else return null}function dZ($){let V=new DataView($.buffer,$.byteOffset,$.byteLength);switch($.byteLength){case 4:{let Q=V.getUint32(0),Z=0;return{sec:Q,nsec:0}}case 8:{let Q=V.getUint32(0),Z=V.getUint32(4),J=(Q&3)*4294967296+Z,W=Q>>>2;return{sec:J,nsec:W}}case 12:{let Q=w$(V,4),Z=V.getUint32(0);return{sec:Q,nsec:Z}}default:throw new V0(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${$.length}`)}}function rZ($){let V=dZ($);return new Date(V.sec*1000+V.nsec/1e6)}var FQ={type:bZ,encode:cZ,decode:rZ};class n0{static defaultCodec=new n0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(FQ)}register({type:$,encode:V,decode:Q}){if($>=0)this.encoders[$]=V,this.decoders[$]=Q;else{let Z=-1-$;this.builtInEncoders[Z]=V,this.builtInDecoders[Z]=Q}}tryToEncode($,V){for(let Q=0;Q<this.builtInEncoders.length;Q++){let Z=this.builtInEncoders[Q];if(Z!=null){let J=Z($,V);if(J!=null){let W=-1-Q;return new l0(W,J)}}}for(let Q=0;Q<this.encoders.length;Q++){let Z=this.encoders[Q];if(Z!=null){let J=Z($,V);if(J!=null)return new l0(Q,J)}}if($ instanceof l0)return $;return null}decode($,V,Q){let Z=V<0?this.builtInDecoders[-1-V]:this.decoders[V];if(Z)return Z($,V,Q);else return new l0(V,$)}}function oZ($){return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer}function W$($){if($ instanceof Uint8Array)return $;else if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);else if(oZ($))return new Uint8Array($);else return Uint8Array.from($)}var aZ=100,sZ=2048;class T${extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??n0.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.maxDepth=$?.maxDepth??aZ,this.initialBufferSize=$?.initialBufferSize??sZ,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 T$({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($),Q=new Uint8Array(V),Z=new DataView(V);Q.set(this.bytes),this.view=Z,this.bytes=Q}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 Q=zQ($);this.ensureBufferSizeToWrite(5+Q),this.writeStringHeader(Q),IQ($,this.bytes,this.pos),this.pos+=Q}encodeObject($,V){let Q=this.extensionCodec.tryToEncode($,this.context);if(Q!=null)this.encodeExtension(Q);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 Q=W$($);this.writeU8a(Q)}encodeArray($,V){let Q=$.length;if(Q<16)this.writeU8(144+Q);else if(Q<65536)this.writeU8(220),this.writeU16(Q);else if(Q<4294967296)this.writeU8(221),this.writeU32(Q);else throw Error(`Too large array: ${Q}`);for(let Z of $)this.doEncode(Z,V+1)}countWithoutUndefined($,V){let Q=0;for(let Z of V)if($[Z]!==void 0)Q++;return Q}encodeMap($,V){let Q=Object.keys($);if(this.sortKeys)Q.sort();let Z=this.ignoreUndefined?this.countWithoutUndefined($,Q):Q.length;if(Z<16)this.writeU8(128+Z);else if(Z<65536)this.writeU8(222),this.writeU16(Z);else if(Z<4294967296)this.writeU8(223),this.writeU32(Z);else throw Error(`Too large map object: ${Z}`);for(let J of Q){let W=$[J];if(!(this.ignoreUndefined&&W===void 0))this.encodeString(J),this.doEncode(W,V+1)}}encodeExtension($){if(typeof $.data==="function"){let Q=$.data(this.pos+6),Z=Q.length;if(Z>=4294967296)throw Error(`Too large extension object: ${Z}`);this.writeU8(201),this.writeU32(Z),this.writeI8($.type),this.writeU8a(Q);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),NQ(this.view,this.pos,$),this.pos+=8}writeI64($){this.ensureBufferSizeToWrite(8),C$(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 f0($,V){return new T$(V).encodeSharedRef($)}function A$($){return`${$<0?"-":""}0x${Math.abs($).toString(16).padStart(2,"0")}`}var tZ=16,eZ=16;class JV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor($=tZ,V=eZ){this.maxKeyLength=$,this.maxLengthPerKey=V,this.caches=[];for(let Q=0;Q<this.maxKeyLength;Q++)this.caches.push([])}canBeCached($){return $>0&&$<=this.maxKeyLength}find($,V,Q){let Z=this.caches[Q-1];$:for(let J of Z){let W=J.bytes;for(let Y=0;Y<Q;Y++)if(W[Y]!==$[V+Y])continue $;return J.str}return null}store($,V){let Q=this.caches[$.length-1],Z={bytes:$,str:V};if(Q.length>=this.maxLengthPerKey)Q[Math.random()*Q.length|0]=Z;else Q.push(Z)}decode($,V,Q){let Z=this.find($,V,Q);if(Z!=null)return this.hit++,Z;this.miss++;let J=ZV($,V,Q),W=Uint8Array.prototype.slice.call($,V,V+Q);return this.store(W,J),J}}var WV="array",X$="map_key",MQ="map_value",$J=($)=>{if(typeof $==="string"||typeof $==="number")return $;throw new V0("The type of key must be string or number but "+typeof $)};class HQ{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState($){let V=this.getUninitializedStateFromPool();V.type=WV,V.position=0,V.size=$,V.array=Array($)}pushMapState($){let V=this.getUninitializedStateFromPool();V.type=X$,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===WV){let Q=$;Q.size=0,Q.array=void 0,Q.position=0,Q.type=void 0}if($.type===X$||$.type===MQ){let Q=$;Q.size=0,Q.map=void 0,Q.readCount=0,Q.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var Y$=-1,YV=new DataView(new ArrayBuffer(0)),VJ=new Uint8Array(YV.buffer);try{YV.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 OQ=RangeError("Insufficient data"),QJ=new JV;class D${extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=YV;bytes=VJ;headByte=Y$;stack=new HQ;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??n0.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.rawStrings=$?.rawStrings??!1,this.maxStrLength=$?.maxStrLength??p0,this.maxBinLength=$?.maxBinLength??p0,this.maxArrayLength=$?.maxArrayLength??p0,this.maxMapLength=$?.maxMapLength??p0,this.maxExtLength=$?.maxExtLength??p0,this.keyDecoder=$?.keyDecoder!==void 0?$.keyDecoder:QJ,this.mapKeyConverter=$?.mapKeyConverter??$J}clone(){return new D$({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=Y$,this.stack.reset()}setBuffer($){let V=W$($);this.bytes=V,this.view=new DataView(V.buffer,V.byteOffset,V.byteLength),this.pos=0}appendBuffer($){if(this.headByte===Y$&&!this.hasRemaining(1))this.setBuffer($);else{let V=this.bytes.subarray(this.pos),Q=W$($),Z=new Uint8Array(V.length+Q.length);Z.set(V),Z.set(Q,V.length),this.setBuffer(Z)}}hasRemaining($){return this.view.byteLength-this.pos>=$}createExtraByteError($){let{view:V,pos:Q}=this;return RangeError(`Extra ${V.byteLength-Q} 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,Q;for await(let Y of $){if(V)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(Y);try{Q=this.doDecodeSync(),V=!0}catch(X){if(!(X instanceof RangeError))throw X}this.totalPos+=this.pos}if(V){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Q}let{headByte:Z,pos:J,totalPos:W}=this;throw RangeError(`Insufficient data in parsing ${A$(Z)} at ${W} (${J} 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 Q=V,Z=-1;for await(let J of $){if(V&&Z===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(J),Q)Z=this.readArraySize(),Q=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--Z===0)break}catch(W){if(!(W instanceof RangeError))throw W}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 Z=$-128;if(Z!==0){this.pushMapState(Z),this.complete();continue $}else V={}}else if($<160){let Z=$-144;if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else V=[]}else{let Z=$-160;V=this.decodeString(Z,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 Z=this.lookU8();V=this.decodeString(Z,1)}else if($===218){let Z=this.lookU16();V=this.decodeString(Z,2)}else if($===219){let Z=this.lookU32();V=this.decodeString(Z,4)}else if($===220){let Z=this.readU16();if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else V=[]}else if($===221){let Z=this.readU32();if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else V=[]}else if($===222){let Z=this.readU16();if(Z!==0){this.pushMapState(Z),this.complete();continue $}else V={}}else if($===223){let Z=this.readU32();if(Z!==0){this.pushMapState(Z),this.complete();continue $}else V={}}else if($===196){let Z=this.lookU8();V=this.decodeBinary(Z,1)}else if($===197){let Z=this.lookU16();V=this.decodeBinary(Z,2)}else if($===198){let Z=this.lookU32();V=this.decodeBinary(Z,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 Z=this.lookU8();V=this.decodeExtension(Z,1)}else if($===200){let Z=this.lookU16();V=this.decodeExtension(Z,2)}else if($===201){let Z=this.lookU32();V=this.decodeExtension(Z,4)}else throw new V0(`Unrecognized type byte: ${A$($)}`);this.complete();let Q=this.stack;while(Q.length>0){let Z=Q.top();if(Z.type===WV)if(Z.array[Z.position]=V,Z.position++,Z.position===Z.size)V=Z.array,Q.release(Z);else continue $;else if(Z.type===X$){if(V==="__proto__")throw new V0("The key __proto__ is not allowed");Z.key=this.mapKeyConverter(V),Z.type=MQ;continue $}else if(Z.map[Z.key]=V,Z.readCount++,Z.readCount===Z.size)V=Z.map,Q.release(Z);else{Z.key=null,Z.type=X$;continue $}}return V}}readHeadByte(){if(this.headByte===Y$)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=Y$}readArraySize(){let $=this.readHeadByte();switch($){case 220:return this.readU16();case 221:return this.readU32();default:if($<160)return $-144;else throw new V0(`Unrecognized array type byte: ${A$($)}`)}}pushMapState($){if($>this.maxMapLength)throw new V0(`Max length exceeded: map length (${$}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState($)}pushArrayState($){if($>this.maxArrayLength)throw new V0(`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 V0(`Max length exceeded: UTF-8 byte length (${$}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+V+$)throw OQ;let Q=this.pos+V,Z;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached($))Z=this.keyDecoder.decode(this.bytes,Q,$);else Z=RQ(this.bytes,Q,$);return this.pos+=V+$,Z}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===X$;return!1}decodeBinary($,V){if($>this.maxBinLength)throw new V0(`Max length exceeded: bin length (${$}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining($+V))throw OQ;let Q=this.pos+V,Z=this.bytes.subarray(Q,Q+$);return this.pos+=V+$,Z}decodeExtension($,V){if($>this.maxExtLength)throw new V0(`Max length exceeded: ext length (${$}) > maxExtLength (${this.maxExtLength})`);let Q=this.view.getInt8(this.pos+V),Z=this.decodeBinary($,V+1);return this.extensionCodec.decode(Z,Q,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let $=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 $=UQ(this.view,this.pos);return this.pos+=8,$}readI64(){let $=w$(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 XV($,V){return new D$(V).decode($)}class A0{listeners=new Map;addEventListener($,V){let Q=this.listeners.get($);if(!Q)Q=new Set,this.listeners.set($,Q);return Q.add(V),()=>{this.removeEventListener($,V)}}removeEventListener($,V){let Q=this.listeners.get($);if(Q){if(Q.delete(V),Q.size===0)this.listeners.delete($)}}emit($,V){let Q=this.listeners.get($);if(Q){let Z=Array.from(Q);for(let J of Z)J(V)}}emitAll($){let V=Array.from(this.listeners.keys());for(let Q of V)this.emit(Q,$)}}class R0{getter;static eventName="update";emitter;constructor($){this.getter=$;this.emitter=new A0}get=()=>this.getter();async emit(){let $=await this.getter();queueMicrotask(()=>this.emitter.emit(R0.eventName,$))}listen($){return this.emitter.addEventListener(R0.eventName,$),()=>{this.emitter.removeEventListener(R0.eventName,$)}}}var D0=64;var qQ=32,_0=8;var _$=32;var PQ=30000,CQ=512,_;((w)=>{w[w.Success=0]="Success";w[w.InvalidSignature=3]="InvalidSignature";w[w.ClockOutOfSync=4]="ClockOutOfSync";w[w.UserNotRegistered=5]="UserNotRegistered";w[w.ServerMisconfigured=6]="ServerMisconfigured";w[w.MissingBody=7]="MissingBody";w[w.ExtraBodyContent=8]="ExtraBodyContent";w[w.MissingParam=9]="MissingParam";w[w.InvalidParam=10]="InvalidParam";w[w.InvalidRequest=11]="InvalidRequest";w[w.InternalError=12]="InternalError";w[w.NotFound=13]="NotFound";w[w.InvalidMessage=14]="InvalidMessage";w[w.NoChange=15]="NoChange";w[w.DatabaseClosed=16]="DatabaseClosed";w[w.StorageError=17]="StorageError";w[w.DatabaseError=18]="DatabaseError";w[w.HashMismatch=19]="HashMismatch";w[w.DecryptionError=20]="DecryptionError";w[w.NotImplemented=21]="NotImplemented";w[w.MissingSeed=22]="MissingSeed";w[w.OutOfBounds=23]="OutOfBounds";w[w.HostError=24]="HostError";w[w.CommunicationError=25]="CommunicationError";w[w.VarLimitExceeded=26]="VarLimitExceeded";w[w.InvalidResponse=27]="InvalidResponse";w[w.ConnectionClosed=28]="ConnectionClosed"})(_||={});function F($){return[$,0]}function z($){return[void 0,$]}function ZJ($){if($<0)console.info("N",$),console.trace();if(typeof $!=="bigint")$=BigInt($);if($<0n)return z(10);let V=[];while($>0n){let Q=Number($&0x7fn);if($>>=7n,$>0n)V.push(Q|128);else V.push(Q)}if(V.length===0)return F(new Uint8Array([0]));if(V.length>8)return z(26);return F(new Uint8Array(V))}function JJ($,V=0){let Q=0n,Z=0,J=V;while(!0){if(J>=$.length)return z(14);let W=$[J++];if(W===void 0)return z(14);if(Q|=BigInt(W&127)<<BigInt(Z),(W&128)===0){if(J-V>8)return z(26);return F({value:Q>0x1fffffffffffffn?Q:Number(Q),bytesRead:J-V})}if(Z+=7,Z>=56)return z(26)}}class k{data;pos=0;constructor($){this.data=$}static async fromResponse($){let V=await $.arrayBuffer(),Q=new Uint8Array(V);return new k(Q)}readBigInt(){if(this.pos+8>this.data.length)return z(7);let $=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,F($)}readDate(){let[$,V]=this.readVarInt();if(V!==0)return z(V);return F(new Date($))}readVarInt(){let[$,V]=JJ(this.data,this.pos);if(V!==0)return z(V);this.pos+=$.bytesRead;let Q=$.value;return F(typeof Q==="bigint"?Number(Q):Q)}readVarString(){let[$,V]=this.readVarInt();if(V!==0)return z(V);let[Q,Z]=this.readBytes($);if(Z!==0)return z(Z);let J=new TextDecoder().decode(Q);return F(J)}readBytes($){if($<0)return z(10);if(this.pos+$>this.data.length)return z(23);let V=this.data.slice(this.pos,this.pos+$);return this.pos+=$,F(V)}readVarBytes(){let[$,V]=this.readVarInt();if(V!==0)return z(V);return this.readBytes($)}readStruct($){return $.decode(this)}readStructs($){let V=[];while(!this.done()){let[Q,Z]=this.readStruct($);if(Z!==0)return z(Z);V.push(Q)}return F(V)}readBytesSeq($){let V=[];while(!this.done()){let[Q,Z]=this.readBytes($);if(Z!==0)return z(Z);V.push(Q)}return F(V)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class g{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,Q]=ZJ($);if(Q!==0)return Q;return this.parts.push(V),0}writeVarString($){let V=new TextEncoder().encode($),Q=this.writeVarInt(V.length);if(Q!==0)return Q;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 Q of V){let Z=this.writeStruct($,Q);if(Z!==0)return Z}return 0}writeBytesSeq($){for(let V of $)this.writeBytes(V)}result(){let $=this.parts.reduce((Z,J)=>Z+J.length,0),V=new Uint8Array($),Q=0;for(let Z of this.parts)V.set(Z,Q),Q+=Z.length;return V}*scan(){for(let $ of this.parts)yield $}}async function GV($,V){let Q=new g,Z=Q.writeDate(V);if(Z!==0)return z(Z);let J=Q.result(),W=await $.sign(J);return F({pubKey:$.publicKey,sig:W,timestamp:V})}async function j0($,V,Q){let Z=Q.now().getTime(),J=$.timestamp.getTime();if(Math.abs(Z-J)>PQ)return 4;let Y=new g;Y.writeDate($.timestamp);let X=Y.result();if(!await V.checkSigEd25519($.sig,X,$.pubKey))return 3;return 0}var o={encode($,V){let Q=$.writeVarBytes(V.id);if(Q!==0)return Q;let Z=$.writeDate(V.ts);if(Z!==0)return Z;return 0},decode($){let[V,Q]=$.readVarBytes();if(Q!==0)return z(Q);let[Z,J]=$.readDate();if(J!==0)return z(J);return F({id:V,ts:Z})}};function c0($){let V=new g,Q=V.writeStruct(o,$);if(Q!==0)return z(Q);let Z=V.result();return F(Z)}async function WJ($){return c0({id:$,ts:new Date(0)})}var X0={encode($,V){let Q=$.writeVarBytes(V.eid);if(Q!==0)return Q;let Z=$.writeVarInt(V.off);if(Z!==0)return Z;let J=$.writeVarInt(V.ctr);if(J!==0)return J;let W=$.writeVarInt(V.len);if(W!==0)return W;if(V.hsh)$.writeBytes(V.hsh);return 0},decode($){let[V,Q]=$.readVarBytes();if(Q!==0)return z(Q);let Z=new k(V),[,J]=o.decode(Z);if(J!==0)return z(J);let[W,Y]=$.readVarInt();if(Y!==0)return z(Y);let[X,G]=$.readVarInt();if(G!==0)return z(G);let[K,I]=$.readVarInt();if(I!==0)return z(I);let R;if(K>0){let[N,U]=$.readBytes(_$);if(U!==0)return z(U);R=N}return F({eid:V,off:W,ctr:X,len:K,hsh:R})}};function t($){return Array.from($).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}function L0($){if($.length%2!==0)throw Error("Invalid hex string");let V=new Uint8Array($.length/2);for(let Q=0;Q<$.length;Q+=2)V[Q/2]=Number.parseInt($.substr(Q,2),16);return V}function e($,V){if($===V)return!0;if($.byteLength!==V.byteLength)return!1;return $.every((Q,Z)=>Q===V[Z])}var L;if(typeof Uint8Array.prototype.toBase64==="function")L=($)=>$.toBase64();else L=($)=>btoa(String.fromCharCode(...$));var Q0;if(typeof Uint8Array.fromBase64==="function")Q0=($)=>Uint8Array.fromBase64($);else Q0=($)=>Uint8Array.from(atob($),(V)=>V.charCodeAt(0));function j$($,V){let Q=new Uint8Array($.length+V.length);return Q.set($,0),Q.set(V,$.length),Q}function wQ($,V,Q){return Q.checkSigEd25519($.sig,$.headCph,V)}async function TQ($,V,Q,Z){let J;if($.bod&&$.len>0)J=await Q.blake3($.bod);let W=new g,Y=X0.encode(W,{...$,hsh:J});if(Y!==0)return z(Y);let X=W.result(),G=await V.kdmFor(X),K=Z.deriveCipher(G,"encrypt"),I=await K.encrypt(X),R=$.bod?await K.encrypt($.bod):new Uint8Array(0),N=await V.sign(I);return F({sig:N,kdm:G,headCph:I,bodyCph:R})}async function KV($,V,Q,Z,J){let W=new k($),[Y,X]=X0.decode(W);if(X!==0)return z(14);let G;try{G=V&&V.length>0?await Q.decrypt(V):void 0}catch{return z(20)}let K=Y.hsh&&G===void 0,I=Y.hsh===void 0&&G!==void 0;if(K||I)return z(19);if(Y.hsh&&G){let N=await Z.blake3(G);if(!e(N,Y.hsh))return z(19)}let R=J??await Z.blake3($);return F({msgHead:Y,bod:G,headHash:R})}class M0{now(){return new Date}}function AQ($,V,Q,Z){let J=V.getTime()-$.getTime(),W=Q.getTime()-Z.getTime();return(J+W)/2}var G$={encode($,V){if($.writeVarInt(V.quota),V.quota>0){if(V.usage===void 0)return 9;$.writeVarInt(V.usage)}return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return z(Q);let Z;if(V>0){let[J,W]=$.readVarInt();if(W!==0)return z(W);Z=J}return F({quota:V,usage:Z})}};var zV={encode($,V){$.writeBytes(new Uint8Array([V.status]));let Q=$.writeDate(V.timeRcvd);if(Q!==0)return Q;let Z=$.writeDate(V.timeSent);if(Z!==0)return Z;let J=$.writeVarInt(V.subscription.term);if(J!==0)return J;let W=$.writeVarInt(V.subscription.elapsed);if(W!==0)return W;let Y=$.writeStruct(G$,V.subscription.stat);if(Y!==0)return Y;let X=$.writeStruct(G$,V.subscription.dyn);if(X!==0)return X;return 0},decode($){let[V,Q]=$.readBytes(1);if(Q!==0)return z(Q);let Z=V[0],[J,W]=$.readDate();if(W!==0)return z(W);let[Y,X]=$.readDate();if(X!==0)return z(X);let[G,K]=$.readVarInt();if(K!==0)return z(K);let[I,R]=$.readVarInt();if(R!==0)return z(R);let[N,U]=$.readStruct(G$);if(U!==0)return z(U);let[M,O]=$.readStruct(G$);if(O!==0)return z(O);return F({status:Z,timeRcvd:J,timeSent:Y,subscription:{term:G,elapsed:I,stat:N,dyn:M}})}};var IV={encode($,V){let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;let Z=$.writeVarInt(V.seq);if(Z!==0)return Z;return 0},decode($){let[V,Q]=$.readVarBytes();if(Q!==0)return z(Q);let[Z,J]=$.readVarInt();if(J!==0)return z(J);return F({headCph:V,seq:Z})}};var Y0={encode($,V){$.writeBytes(V.pubKey),$.writeBytes(V.sig);let Q=$.writeDate(V.timestamp);if(Q!==0)return Q;return 0},decode($){let[V,Q]=$.readBytes(qQ);if(Q!==0)return z(Q);let[Z,J]=$.readBytes(D0);if(J!==0)return z(J);let[W,Y]=$.readDate();if(Y!==0)return z(Y);return F({pubKey:V,sig:Z,timestamp:W})}};var DQ={async encodeReq($,V,Q,Z,J){let W=J.writeStruct(Y0,Q);if(W!==0)return W;for(let Y of Z)J.writeVarInt(Y);return 0},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W}=$,[Y,X]=V.readStruct(Y0);if(X!==0)return X;let G=await j0(Y,J,Z);if(G!==0)return G;let{pubKey:K}=Y,[I,R]=await W.hasUser(K);if(R!==0)return R;if(!I)return 5;let[N,U]=V.readVarInt();if(U!==0)return U;if(!V.done())return 8;let[M,O]=await W.listHeads(K,N);if(O!==0)return O;return Q.writeStructs(IV,M)},decodeResp($){return $.readStructs(IV)}};var RV={encode($,V){$.writeVarInt(V.seq);let Q=$.writeVarBytes(V.bodyCph);if(Q!==0)return Q;return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return z(Q);let[Z,J]=$.readVarBytes();if(J!==0)return z(J);return F({seq:V,bodyCph:Z})}};var _Q={async encodeReq($,V,Q,Z,J){let W=J.writeStruct(Y0,Q);if(W!==0)return W;for(let Y of Z){let X=J.writeVarInt(Y);if(X!==0)return X}return 0},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W}=$,[Y,X]=V.readStruct(Y0);if(X!==0)return X;let G=await j0(Y,J,Z);if(G!==0)return G;let{pubKey:K}=Y,[I,R]=await W.hasUser(K);if(R!==0)return R;if(!I)return 5;let N=[];while(!V.done()){let[O,H]=V.readVarInt();if(H!==0)return H;N.push(O)}console.info(`PULL: ${N.length} bags`);let[U,M]=await W.getBodies(K,N);if(M!==0)return M;if(!U)return 17;for(let{seq:O,bodyCph:H}of U){let C={seq:O,bodyCph:H},P=Q.writeStruct(RV,C);if(P!==0)return P}return 0},decodeResp($){return $.readStructs(RV)}};var NV={encode($,V){$.writeBytes(V.sig),$.writeBytes(V.kdm);let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;let Z=$.writeVarBytes(V.bodyCph);if(Z!==0)return Z;return 0},decode($){let[V,Q]=$.readBytes(D0);if(Q!==0)return z(Q);let[Z,J]=$.readBytes(_0);if(J!==0)return z(J);let[W,Y]=$.readVarBytes();if(Y!==0)return z(Y);let[X,G]=$.readVarBytes();if(G!==0)return z(G);return F({sig:V,kdm:Z,headCph:W,bodyCph:X})}};var L$={encode($,V){let Q=$.writeVarInt(V.seq);if(Q!==0)return Q;let Z=$.writeVarBytes(V.headCph);if(Z!==0)return Z;let J=V.bodyCph?V.bodyCph.length:0,W=$.writeVarInt(J);if(W!==0)return W;if(J>0){if(!V.bodyCph)return 10;$.writeBytes(V.bodyCph)}return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return z(Q);let[Z,J]=$.readVarBytes();if(J!==0)return z(J);let[W,Y]=$.readVarInt();if(Y!==0)return z(Y);let X;if(W>0){let[G,K]=$.readBytes(W);if(K!==0)return z(K);X=G}return F({seq:V,headCph:Z,bodyCph:X})}};var x$={encode($,V){$.writeBytes(V.sig),$.writeBytes(V.kdm);let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;return 0},decode($){let[V,Q]=$.readBytes(D0);if(Q!==0)return z(Q);let[Z,J]=$.readBytes(_0);if(J!==0)return z(J);let[W,Y]=$.readVarBytes();if(Y!==0)return z(Y);return F({sig:V,kdm:Z,headCph:W})}};var S$={encode($,V){if($.writeVarInt(V.idx),$.writeBytes(new Uint8Array([V.status])),V.status===0)$.writeVarInt(V.seq);return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return z(Q);let[Z,J]=$.readBytes(1);if(J!==0)return z(J);let W=Z[0];if(W!==0)return F({idx:V,status:W});let[Y,X]=$.readVarInt();if(X!==0)return z(X);return F({idx:V,status:W,seq:Y})}};var jQ={async encodeReq($,V,Q,Z,J){let W=J.writeStruct(Y0,Q);if(W!==0)return W;let Y=J.writeStructs(NV,Z);if(Y!==0)return Y;return 0},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W,notifier:Y}=$,[X,G]=V.readStruct(Y0);if(G!==0)return G;let K=await j0(X,J,Z);if(K!==0)return K;let{pubKey:I}=X,[R,N]=await W.hasUser(I);if(N!==0)return N;if(!R)return 5;let[U,M]=V.readStructs(NV);if(M!==0)return M;console.info(`PUSH: ${U.length} bags`);let O=[],H=[];for(let q=0;q<U.length;q++){let D=U[q];if(!await wQ(D,I,J)){let B={idx:q,status:3},m=Q.writeStruct(S$,B);if(m!==0)return m;continue}O.push(q),H.push(D)}let[C,P]=await W.setBags(I,H);if(P!==0)return P;if(!C||C.length!==H.length)return 17;let T=[];for(let q=0;q<H.length;q++){let D=H[q],S=O[q],B=C[q],m=new g,f=m.writeStruct(x$,D);if(f!==0)return f;let i=m.result(),w={seq:B,headCph:i};if(U.length===1&&D.bodyCph.length<=CQ)w.bodyCph=D.bodyCph;T.push(w);let b={idx:S,status:0,seq:B},l=Q.writeStruct(S$,b);if(l!==0)return l}if(T.length>0){let q=new g,D=q.writeStructs(L$,T);if(D!==0)return D;let S=q.result();await Promise.resolve(Y.push(I,S))}return 0},decodeResp($){return $.readStructs(S$)}};var LQ={async encodeReq($,V,Q,Z,J){return J.writeStruct(Y0,Q)},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W}=$,[Y,X]=V.readStruct(Y0);if(X!==0)return X;let G=await j0(Y,J,Z);if(G!==0)return G;let{pubKey:K}=Y;if(!V.done())return 8;let[I,R]=await W.addUser(K);if(R!==0)return R;return 0},decodeResp($){return F(void 0)}};class UV{url;websocket;constructor($){this.url=$}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect($,V,Q=()=>{},Z=()=>{}){let{url:J}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let W=new g;W.writeStruct(Y0,$);let Y=W.result(),X=t(Y);return J.searchParams.set("t",X),this.websocket=new WebSocket(J),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),Z()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Q()},this.websocket.onmessage=(G)=>{let K=new Uint8Array(G.data);V(K)},this.websocket.onerror=(G)=>{console.log(`ERROR: ${JSON.stringify(G)}`),this.websocket=void 0,Q()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var a={user:{path:"/user",endpoint:LQ,name:0},push:{path:"/push",endpoint:jQ,name:2},peek:{path:"/peek",endpoint:DQ,name:1},pull:{path:"/pull",endpoint:_Q,name:3}},YJ={0:a.user,2:a.push,1:a.peek,3:a.pull},O8={[a.user.path]:a.user,[a.push.path]:a.push,[a.peek.path]:a.peek,[a.pull.path]:a.pull};class FV{url;listener;constructor($){this.url=$;this.listener=new UV($)}async call($,V){let{path:Q}=YJ[$],Z=new URL(Q,this.url);try{return await XJ(Z,V)}catch{return z(25)}}}var f$=($)=>{return new FV($.handle)};async function XJ($,V){let Q=await fetch($,{method:"POST",body:V.result().slice()});if(!Q.ok)return z(24);let Z=await k.fromResponse(Q);return F(Z)}class E${enclave;crypto;host;clock;transport;updateHostMeta;constructor($,V,Q,Z,J,W){this.enclave=$;this.crypto=V;this.host=Q;this.clock=Z;this.transport=J;this.updateHostMeta=W}async call($,V){let{clock:Q,transport:Z}=this,{endpoint:J,name:W}=$,Y=await this.identity(),X=Q.now(),[G,K]=await GV(Y,X);if(K!==0)return z(K);let I=new g,R=await J.encodeReq(this,Y,G,V,I);if(R!==0)return z(R);let N=Q.now(),[U,M]=await Z.call(W,I),O=Q.now();if(M!==0)return z(M);let[H,C]=U.readStruct(zV);if(C!==0)return z(C);if(H.status!==0)return z(H.status);let T={clockOffset:AQ(N,H.timeRcvd,H.timeSent,O),subscription:H.subscription},q=await this.updateHostMeta(T);if(q!==0)return z(q);return J.decodeResp(U)}identity=()=>{let{host:$,enclave:V}=this;return V.deriveIdentity($.label,$.idx??0)};seal=async($)=>{let{crypto:V,enclave:Q}=this,Z=await this.identity();return TQ($,Z,V,Q)};register=()=>this.call(a.user,[]);peek=($)=>this.call(a.peek,[$]);push=($)=>this.call(a.push,$);pull=($)=>this.call(a.pull,$);listen=async($,V,Q)=>{let{clock:Z,transport:J}=this,{listener:W}=J,Y=await this.identity(),X=Z.now(),[G,K]=await GV(Y,X);if(K!==0)return K;return await W.connect(G,$,V,Q)};isConnected(){let $=this.transport?.listener;if($&&typeof $.connected==="function")return $.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var OV={encode($,V){let Q=$.writeVarString(V.lbl);if(Q!==0)return Q;let Z=$.writeVarInt(V.idx);if(Z!==0)return Z;let J=$.writeVarInt(V.num);if(J!==0)return J;return $.writeBytes(V.hsh),$.writeBytes(V.sig),0},decode($){let[V,Q]=$.readVarString();if(Q!==0)return z(Q);let[Z,J]=$.readVarInt();if(J!==0)return z(J);let[W,Y]=$.readVarInt();if(Y!==0)return z(Y);let[X,G]=$.readBytes(_$);if(G!==0)return z(G);let[K,I]=$.readBytes(D0);if(I!==0)return z(I);return F({lbl:V,idx:Z,num:W,hsh:X,sig:K})}};var MV={encode($,V){let Q=$.writeStruct(OV,V.head);if(Q!==0)return Q;let Z=$.writeVarBytes(V.indexEnc);if(Z!==0)return Z;let J=$.writeVarBytes(V.bodyEnc);if(J!==0)return J;return 0},decode($){let[V,Q]=$.readStruct(OV);if(Q!==0)return z(Q);let[Z,J]=$.readVarBytes();if(J!==0)return z(J);let[W,Y]=$.readVarBytes();if(Y!==0)return z(Y);return F({head:V,indexEnc:Z,bodyEnc:W})}};var HV={encode($,V){$.writeBytes(V.kdm);let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;let Z=$.writeVarInt(V.lenBody);if(Z!==0)return Z;if(V.lenBody>0&&V.offBody!==void 0){let J=$.writeVarInt(V.offBody);if(J!==0)return J}return 0},decode($){let[V,Q]=$.readBytes(_0);if(Q!==0)return z(Q);let[Z,J]=$.readVarBytes();if(J!==0)return z(J);let[W,Y]=$.readVarInt();if(Y!==0)return z(Y);let X;if(W>0){let[G,K]=$.readVarInt();if(K!==0)return z(K);X=G}return F({kdm:V,headCph:Z,lenBody:W,offBody:X})}};async function xQ($,V,Q,Z,J){let W=await J.deriveIdentity($,V),Y=new g,X=new g,G=0,K=0;for(let C of Q){let P=new g,T=P.writeStruct(X0,C.head);if(T!==0)return z(T);let q=P.result(),D=await W.kdmFor(q),S=J.deriveCipher(D,"encrypt"),B=await S.encrypt(q),m=C.body?await S.encrypt(C.body):new Uint8Array(0),f=C.head.len>0&&C.head.hsh!==void 0?m.length:0,i={kdm:D,headCph:B,lenBody:f,offBody:f>0?K:void 0},w=Y.writeStruct(HV,i);if(w!==0)return z(w);if(C.body)X.writeBytes(m),K+=m.length;G++}let I=X.result(),R=Y.result(),N=await Z.blake3(R),U=await W.sign(N),M={lbl:$,idx:V,num:G,hsh:N,sig:U},O=new g;O.writeStruct(MV,{head:M,indexEnc:R,bodyEnc:I});let H=O.result();return F(H)}async function SQ($,V,Q){let[Z,J]=MV.decode(new k($));if(J!==0)return z(J);let{head:W,indexEnc:Y,bodyEnc:X}=Z,G=await Q.deriveIdentity(W.lbl,W.idx);if(!await V.checkSigEd25519(W.sig,W.hsh,G.publicKey))return z(3);let I=await V.blake3(Y);if(!e(I,W.hsh))return z(19);let R=new k(Y),N=[];for(let M=0;M<W.num;M++){let[O,H]=R.readStruct(HV);if(H!==0)return z(H);N.push(O)}if(N.length!==W.num)return z(14);let U=[];for(let M of N){let O=Q.deriveCipher(M.kdm,"decrypt"),H;try{H=await O.decrypt(M.headCph)}catch{return z(20)}let[C,P]=X0.decode(new k(H));if(P!==0)return z(P);let T;if(M.lenBody>0&&M.offBody!==void 0){if(C.hsh===void 0)return z(14);let q=X.slice(M.offBody,M.offBody+M.lenBody);try{T=await O.decrypt(q)}catch{return z(20)}let D=await V.blake3(T);if(!e(D,C.hsh))return z(19)}U.push({head:C,body:T})}return F(U)}async function fQ({now:$,bod:V,crypto:Q}){let Z=await Q.genRandomBytes(8),J=new g,W=J.writeStruct(o,{id:Z,ts:$});if(W!==0)return z(W);let Y=J.result();return m$({now:$,eid:Y,ctr:0,bod:V,crypto:Q})}async function m$({now:$,eid:V,ctr:Q,bod:Z,crypto:J}){let W=new k(V),[Y,X]=o.decode(W);if(X!==0)return z(X);let G=$.getTime()-Y.ts.getTime(),K,I=Z?.length??0;if(Z&&I>0)K=await J.blake3(Z);return F({eid:V,off:G,ctr:Q,len:I,hsh:K})}function EQ($,V){let Q=$.length<V.length?$.length:V.length;for(let Z=0;Z<Q;Z++)if($[Z]!==V[Z])return $[Z]-V[Z];return $.length-V.length}async function d0($,V){let Q=Array.from($);Q.sort(EQ);let Z=0;for(let Y of Q)Z+=Y.length;let J=new Uint8Array(Z),W=0;for(let Y of Q)J.set(Y,W),W+=Y.length;return V.blake3(J)}function mQ($){let V=new g,Q=V.writeVarBytes($.eid);if(Q!==0)return z(Q);let Z=V.writeDate($.updatedAt);if(Z!==0)return z(Z);let J=V.writeVarInt($.ctr);if(J!==0)return z(J);return F(V.result())}async function K$($,V){let Q=[];for(let Z of $){let[J,W]=mQ(Z);if(W!==0||!J)return z(W);Q.push(J)}return F(await d0(Q,V))}var XG=Symbol("EntityID");function BQ($){return"type"in $}var GG=Symbol("MasterSeed"),KG=Symbol("DerivationSeed"),zG=Symbol("PublicKey"),IG=Symbol("PrivateKey"),RG=Symbol("HostSpecificKeyPair"),NG=Symbol("Hash");function GJ($){if(!$)return!1;if(typeof $!=="object")return!1;if("body"in $===!1)return!1;if("type"in $===!1)return!1;return!0}function KJ($){if(!$.bod||$.bod.length===0){let Z={off:$.off,ctr:$.ctr,eid:$.eid};return F(Z)}let V=XV($.bod);if(GJ(V)===!1)return console.warn("msg body invalid",V),z(14);let Q={off:$.off,ctr:$.ctr,eid:$.eid,gid:V.gid,pid:V.pid,tags:V.tags,type:V.type,body:V.body};return F(Q)}class z${applier;emitter=new A0;clearer;onDirtyEids;cacheDriven;peerIngest;constructor($,V,Q,Z){this.applier=$;this.clearer=V,this.onDirtyEids=Q,this.cacheDriven=Z?.cacheDriven??!1,this.peerIngest=Z?.peerIngest}apply=async($)=>{let V=[],Q=[];for(let X of $){let[G,K]=KJ(X);if(Q.push(K),K!==0)continue;V.push(G)}let{stats:Z,types:J,eids:W}=await this.applier(V),Y=[];for(let X=0;X<$.length;X++){let G=Q[X],K=Z[X];if(G!==0){Y.push(G);continue}if(K!==0){Y.push(K);continue}Y.push(0)}if(!this.cacheDriven)for(let X of J)this.emitter.emit(X,null);if(W.length>0)this.onDirtyEids?.(W);return Y};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 qV={apply:async function($){return $.map(()=>0)},clear:async function(){return 0},notify:function($){},refresh:async function($){},on:function($,V){},off:function($,V){}};var n="entities",B$="entity_type_created_at",CV="entity_type_updated_at",wV="entity_type_group_id",TV="entity_type_parent_id",r0="entity_tags",kQ="db",gQ=13;function zJ($){return"typ"in $}function IJ($){let V={bod:$.body,crd:$.createdAt,...$.ctr!==0?{ctr:$.ctr}:{},eid:L($.eid),gid:$.gid,pid:$.pid?L($.pid):void 0,tgs:$.tags,typ:$.type,upd:$.updatedAt};if(V.gid===void 0)delete V.gid;if(V.pid===void 0)delete V.pid;if(V.tgs===void 0)delete V.tgs;if(V.ctr===void 0)delete V.ctr;return V}function RJ($){if(!u($))return{eid:L($.eid),upd:$.updatedAt,...$.ctr!==0?{ctr:$.ctr}:{}};return IJ($)}function o0($){return{body:$.bod,createdAt:$.crd,updatedAt:$.upd,ctr:$.ctr??0,type:$.typ,eid:Q0($.eid),gid:$.gid,pid:$.pid?Q0($.pid):void 0,...$.tgs!==void 0?{tags:$.tgs}:{}}}function PV($){if(zJ($))return o0($);return{eid:Q0($.eid),updatedAt:$.upd,ctr:$.ctr??0}}class AV{db;opening;async init(){await this.ensureDb()}async ensureDb(){if(this.db)return this.db;if(this.opening)return this.opening;return this.opening=UJ().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,Q=[],Z;try{Z=await this.ensureDb()}catch{return{stats:$.map(()=>16),types:V,eids:Q}}let J=Z.transaction(n,"readwrite"),W=J.objectStore(n);return new Promise((Y)=>{let X=Array($.length).fill(0);if($.length<1){Y({stats:[],types:V,eids:Q});return}J.oncomplete=()=>{Y({stats:X,types:V,eids:Q})},J.onerror=()=>{for(let K=0;K<X.length;K++)if(X[K]===void 0)X[K]=18;Y({stats:X,types:V,eids:Q})};let G=new Map;for(let K=0;K<$.length;K++){let I=$[K],R=L(I.eid),N={op:I,index:K},U=G.get(R);if(U)U.push(N);else G.set(R,[N])}for(let[K,I]of G){if(I.length<1)continue;let R=W.get(K);R.onsuccess=()=>{let N=R.result,U=N?PV(N):void 0,M=!1;for(let{op:O,index:H}of I){let[C,P]=a0(U,O);if(P!==0){X[H]=P;continue}if(C===void 0){X[H]=12;continue}M=!0;for(let T of s0(U,C))V.add(T);U=C}if(M)Q.push(I[0].op.eid);if(U){let O=W.put(RJ(U));O.onerror=(H)=>{H.preventDefault();for(let{index:C}of I)X[C]=18}}},R.onerror=()=>{for(let{index:N}of I)X[N]=18}}})};async clear(){let $;try{$=await this.ensureDb()}catch{return 16}let V=$.transaction(n,"readwrite"),Q=V.objectStore(n);return new Promise((Z)=>{V.oncomplete=()=>Z(0),V.onerror=()=>Z(18),Q.clear()})}async getRow($){let V;try{V=await this.ensureDb()}catch{return z(16)}let Q=L($),J=V.transaction(n,"readonly").objectStore(n);return new Promise((W)=>{let Y=J.get(Q);Y.onsuccess=()=>{let X=Y.result;if(!X)W(F(void 0));else W(F(PV(X)))},Y.onerror=()=>W(z(18))})}async getEnt($){let[V,Q]=await this.getRow($);if(Q!==0)return z(Q);if(V===void 0||!u(V))return F(void 0);return F(V)}async getAllOfTypeUpdatedBetween($,V,Q){let Z;try{Z=await this.ensureDb()}catch{return z(16)}let W=Z.transaction(n,"readonly").objectStore(n).index(CV);return new Promise((Y)=>{let X=W.getAll(IDBKeyRange.bound([$,V],[$,Q]));X.onsuccess=()=>{let G=X.result;Y(F(G.map(o0)))},X.onerror=()=>Y(z(18))})}async getGroupMembers($,V){let Q;try{Q=await this.ensureDb()}catch{return z(16)}let J=Q.transaction(n,"readonly").objectStore(n).index(wV);return new Promise((W)=>{let Y=J.getAll(IDBKeyRange.only([$,V]));Y.onsuccess=()=>{let X=Y.result;W(F(X.map(o0)))},Y.onerror=()=>W(z(18))})}async getAllOfType($){let V;try{V=await this.ensureDb()}catch{return z(16)}let Z=V.transaction(n,"readonly").objectStore(n).index(B$);return new Promise((J)=>{let W=Z.getAll(IDBKeyRange.bound([$],[$,[]]));W.onsuccess=()=>{let Y=W.result;J(F(Y.map(o0)))},W.onerror=()=>J(z(18))})}async getByTag($,V){let Q;try{Q=await this.ensureDb()}catch{return z(16)}let J=Q.transaction(n,"readonly").objectStore(n).index(r0);return new Promise((W)=>{let Y=J.getAll(IDBKeyRange.only(V));Y.onsuccess=()=>{let G=Y.result.filter((K)=>K.typ===$).map(o0);W(F(G))},Y.onerror=()=>W(z(18))})}async getAllEntities($){if("pid"in $){let V;try{V=await this.ensureDb()}catch{return z(16)}let Q=L($.pid),J=V.transaction(n,"readonly").objectStore(n).index(TV);return new Promise((W)=>{let Y=J.getAll(IDBKeyRange.only([$.type,Q]));Y.onsuccess=()=>{let G=Y.result.map(o0);W(F(G))},Y.onerror=()=>W(z(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,Q]=await this.getAllEntities($);if(Q!==0)return z(Q);return F(V)}async countEntities({type:$}){let V;try{V=await this.ensureDb()}catch{return z(16)}let Z=V.transaction(n,"readonly").objectStore(n).index(B$);return new Promise((J)=>{let W=IDBKeyRange.bound([$],[$,[]]),Y=Z.count(W);Y.onsuccess=()=>J(F(Y.result)),Y.onerror=()=>J(z(18))})}async checksum($){let V;try{V=await this.ensureDb()}catch{return z(16)}let Z=V.transaction(n,"readonly").objectStore(n),J=[];return new Promise((W)=>{let Y=Z.openCursor();Y.onsuccess=()=>{let X=Y.result;if(X){let G=X.value;J.push(I$(PV(G))),X.continue()}else K$(J,$).then(W)},Y.onerror=()=>W(z(18))})}}function NJ($,V){if(!$.objectStoreNames.contains(n))$.createObjectStore(n,{keyPath:"eid",autoIncrement:!1});let Q=V.objectStore(n);if(!Q.indexNames.contains(B$))Q.createIndex(B$,["typ","crd"],{unique:!1});if(!Q.indexNames.contains(CV))Q.createIndex(CV,["typ","upd"],{unique:!1});if(!Q.indexNames.contains(wV))Q.createIndex(wV,["typ","gid"],{unique:!1});if(!Q.indexNames.contains(TV))Q.createIndex(TV,["typ","pid"],{unique:!1});if(Q.indexNames.contains(r0)){if(Q.index(r0).keyPath!=="tgs")Q.deleteIndex(r0)}if(!Q.indexNames.contains(r0))Q.createIndex(r0,"tgs",{unique:!1,multiEntry:!0})}function UJ(){return new Promise(($,V)=>{let Q=indexedDB.open(kQ,gQ);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!J){V(Error("Transaction is null during EntDB upgrade"));return}try{NJ(Z,J)}catch(W){V(W instanceof Error?W:Error(String(W)))}},Q.onblocked=()=>{console.warn(`[DIPLOMATIC] EntDB IDB upgrade blocked (${kQ} → v${gQ}); waiting for other connections to close`)},Q.onsuccess=()=>$(Q.result),Q.onerror=()=>V(Q.error??Error("EntDB IndexedDB open failed"))})}async function vQ(){let $=new AV;return await $.init(),$}class k${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 Q of $)this.put(Q)}put($){let V=L($.eid),Q=this.ents.get(V);if(Q!==void 0&&u(Q))this.unindex(V,Q);if(this.ents.set(V,$),u($))this.index(V,$)}del($){let V=this.ents.get($);if(V===void 0)return;if(u(V))this.unindex($,V);this.ents.delete($)}index($,V){if(!this.useIndex)return;let Q=this.byType.get(V.type);if(!Q)Q=new Map,this.byType.set(V.type,Q);if(Q.set($,V),V.pid){let Z=L(V.pid),J=this.byTypePid.get(V.type);if(!J)J=new Map,this.byTypePid.set(V.type,J);let W=J.get(Z);if(!W)W=new Map,J.set(Z,W);W.set($,V)}if(typeof V.gid==="string"){let Z=this.byTypeGid.get(V.type);if(!Z)Z=new Map,this.byTypeGid.set(V.type,Z);let J=Z.get(V.gid);if(!J)J=new Map,Z.set(V.gid,J);J.set($,V)}if(V.tags){let Z=this.byTypeTag.get(V.type);if(!Z)Z=new Map,this.byTypeTag.set(V.type,Z);for(let J of V.tags){let W=Z.get(J);if(!W)W=new Map,Z.set(J,W);W.set($,V)}}}unindex($,V){if(!this.useIndex)return;let Q=this.byType.get(V.type);if(Q){if(Q.delete($),Q.size===0)this.byType.delete(V.type)}if(V.pid){let Z=L(V.pid),J=this.byTypePid.get(V.type),W=J?.get(Z);if(W){if(W.delete($),W.size===0)J?.delete(Z)}if(J&&J.size===0)this.byTypePid.delete(V.type)}if(typeof V.gid==="string"){let Z=this.byTypeGid.get(V.type),J=Z?.get(V.gid);if(J){if(J.delete($),J.size===0)Z?.delete(V.gid)}if(Z&&Z.size===0)this.byTypeGid.delete(V.type)}if(V.tags){let Z=this.byTypeTag.get(V.type);if(Z){for(let J of V.tags){let W=Z.get(J);if(W){if(W.delete($),W.size===0)Z.delete(J)}}if(Z.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 Q of $.values())V.push(Q);return V}async apply($){let V=new Set,Q=[],Z=[];for(let J of $){let W=L(J.eid),Y=this.ents.get(W),[X,G]=a0(Y,J);if(G!==0){Z.push(G);continue}if(X===void 0){Z.push(12);continue}for(let K of s0(Y,X))V.add(K);this.put(X),Q.push(J.eid),Z.push(0)}return{stats:Z,types:V,eids:Q}}async clear(){return this.ents.clear(),this.clearIndexes(),0}async getRow($){let V=L($),Q=this.ents.get(V);return F(Q)}async getEnt($){let[V,Q]=await this.getRow($);if(Q!==0)return z(Q);if(V===void 0||!u(V))return F(void 0);return F(V)}async getAllEntities({type:$,gid:V,pid:Q,tag:Z,updatedBetween:J}){if(this.useIndex){if(Q!==void 0){let Y=L(Q);return F(this.bucketList(this.byTypePid.get($)?.get(Y)))}if(V!==void 0)return F(this.bucketList(this.byTypeGid.get($)?.get(V)));if(Z!==void 0)return F(this.bucketList(this.byTypeTag.get($)?.get(Z)));if(J!==void 0){let Y=[],X=this.byType.get($);if(X){for(let G of X.values())if(G.updatedAt>=J.start&&G.updatedAt<=J.end)Y.push(G)}return F(Y)}return F(this.bucketList(this.byType.get($)))}let W=[];if(Q!==void 0){for(let Y of this.ents.values())if(u(Y)&&Y.type===$&&Y.pid&&e(Y.pid,Q))W.push(Y)}else if(V!==void 0){for(let Y of this.ents.values())if(u(Y)&&Y.type===$&&(typeof Y.gid==="string"&&Y.gid===V))W.push(Y)}else if(Z!==void 0){for(let Y of this.ents.values())if(u(Y)&&Y.type===$&&Y.tags&&Y.tags.includes(Z))W.push(Y)}else if(J!==void 0){for(let Y of this.ents.values())if(u(Y)&&Y.type===$&&Y.updatedAt>=J.start&&Y.updatedAt<=J.end)W.push(Y)}else for(let Y of this.ents.values())if(u(Y)&&Y.type===$)W.push(Y);return F(W)}async getEntities($){let[V,Q]=await this.getAllEntities($);if(Q!==0)return z(Q);return F(V)}async countEntities({type:$}){if(this.useIndex)return F(this.byType.get($)?.size??0);let V=0;for(let Q of this.ents.values())if(u(Q)&&Q.type===$)V+=1;return F(V)}async checksum($){let V=[];for(let Q of this.ents.values())V.push(I$(Q));return K$(V,$)}}async function DV($){let V=await vQ();if($?.cache===!1)return V;return new R$(V,void 0,{indexes:$?.indexes})}class R${mem;durable;warmed=new Set;listeners=new Set;chain=Promise.resolve();constructor($,V,Q){if(this.durable=$,this.mem=new k$(V??[],{indexes:Q?.indexes}),V)for(let Z of V)this.warmed.add(Z.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()=>{await this.pullEids($.map((W)=>W.eid));let V=PJ(this.mem,$);this.emit(V.types);let Q=await this.durable.apply($),{changed:Z,status:J}=await this.pullEids($.map((W)=>W.eid));if(this.emit(Z),J!==0)return{stats:$.map(()=>J),types:Q.types,eids:Q.eids};return Q})}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:Q}=await this.pullEids($);return this.emit(V),Q})}async pullEids($){let V=new Set,Q=new Set;for(let Z of $){let J=L(Z);if(Q.has(J))continue;Q.add(J);let W=this.mem.ents.get(J),[Y,X]=await this.durable.getRow(Z);if(X!==0)return{changed:V,status:X};if(Y){if(this.mem.put(Y),!W||!FJ(W,Y)){if(u(Y))V.add(Y.type);if(W!==void 0&&u(W))V.add(W.type)}}else if(W!==void 0){if(this.mem.del(J),u(W))V.add(W.type)}}return{changed:V,status:0}}async warmType($){if(this.warmed.has($))return 0;let[V,Q]=await this.durable.getEntities({type:$});if(Q!==0)return Q;if(V)for(let Z of V){let J=L(Z.eid),W=this.mem.ents.get(J);if(!W||qJ(Z,W))this.mem.put(Z)}return this.warmed.add($),0}async getRow($){let V=L($);if(this.mem.ents.has(V))return this.mem.getRow($);return this.run(async()=>{if(this.mem.ents.has(V))return this.mem.getRow($);let[Q,Z]=await this.durable.getRow($);if(Z!==0)return z(Z);if(Q)this.mem.put(Q);return F(Q)})}async getEnt($){let[V,Q]=await this.getRow($);if(Q!==0)return z(Q);if(V===void 0||!u(V))return F(void 0);return F(V)}async getEntities($){if(!this.warmed.has($.type)){let V=await this.run(()=>this.warmType($.type));if(V!==0)return z(V)}return this.mem.getEntities($)}async countEntities({type:$}){if(!this.warmed.has($)){let V=await this.run(()=>this.warmType($));if(V!==0)return z(V)}return this.mem.countEntities({type:$})}async checksum($){return this.durable.checksum($)}}function FJ($,V){if(u($)!==u(V))return!1;if($.ctr!==V.ctr)return!1;if($.updatedAt.getTime()!==V.updatedAt.getTime())return!1;if(!e($.eid,V.eid))return!1;if(!u($)||!u(V))return!0;if($.createdAt.getTime()!==V.createdAt.getTime())return!1;if($.type!==V.type)return!1;if($.gid!==V.gid)return!1;if(!MJ($.pid,V.pid))return!1;if(!OJ($.tags,V.tags))return!1;return HJ($.body,V.body)}function OJ($,V){if($===V)return!0;if($===void 0||V===void 0)return!1;if($.length!==V.length)return!1;for(let Q=0;Q<$.length;Q++)if($[Q]!==V[Q])return!1;return!0}function MJ($,V){if($===void 0&&V===void 0)return!0;if($===void 0||V===void 0)return!1;return e($,V)}function HJ($,V){if(Object.is($,V))return!0;if($ instanceof Uint8Array&&V instanceof Uint8Array)return e($,V);if($ instanceof Date&&V instanceof Date)return $.getTime()===V.getTime();try{return e(f0($),f0(V))}catch{return!1}}function qJ($,V){let Q=$.updatedAt.getTime(),Z=V.updatedAt.getTime();if(Q!==Z)return Q>Z;return $.ctr>V.ctr}function PJ($,V){let Q=new Set,Z=[];for(let J of V){let W=L(J.eid),Y=$.ents.get(W),[X,G]=a0(Y,J);if(G!==0){Z.push(G);continue}if(X===void 0){Z.push(12);continue}for(let K of s0(Y,X))Q.add(K);$.put(X),Z.push(0)}return{stats:Z,types:Q}}function g$($){if($ instanceof R$){let V=new z$((Q)=>$.apply(Q),()=>$.clear(),void 0,{cacheDriven:!0,peerIngest:async(Q)=>{await $.ingestFromDurable(Q)}});return $.subscribe((Q)=>V.notify(Q)),V}return new z$((V)=>$.apply(V),()=>$.clear())}function u($){return"type"in $}function CJ($){return!u($)}function iQ($){if(!Array.isArray($)||$.length===0)return;let V=new Set,Q=[];for(let Z of $){if(typeof Z!=="string"||Z.length===0)continue;if(V.has(Z))continue;V.add(Z),Q.push(Z)}return Q.length>0?Q:void 0}function I$($){return{eid:$.eid,ctr:$.ctr,updatedAt:$.updatedAt}}function _V($){let V=new k($.eid),[Q,Z]=V.readStruct(o);if(Z!==0)return z(Z);return F({eid:$.eid,ctr:$.ctr,updatedAt:new Date(Q.ts.getTime()+$.off)})}function a0($,V){let Q=new k(V.eid),[Z,J]=Q.readStruct(o);if(J!==0)return z(J);let W=new Date(Z.ts.getTime()+V.off);if($!==void 0&&W<=$.updatedAt)return z(15);if(BQ(V)){let Y=iQ(V.tags);return F({eid:V.eid,gid:V.gid,pid:V.pid,...Y!==void 0?{tags:Y}:{},type:V.type,createdAt:Z.ts,updatedAt:W,ctr:V.ctr,body:V.body})}return F({eid:V.eid,updatedAt:W,ctr:V.ctr})}function s0($,V){let Q=new Set;if($!==void 0&&u($))Q.add($.type);if(u(V))Q.add(V.type);return[...Q]}var wJ={getEnt:async()=>z(21),getRow:async()=>z(21),getEntities:async($)=>z(21),countEntities:async()=>z(21),checksum:async()=>z(21),apply:async($)=>({stats:$.map(()=>21),types:new Set,eids:[]}),clear:async()=>21};class v${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 i$=100;class N${timer=null;delayMs;work;tail=new v$;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 yQ($){let V=new k($.eid),[Q,Z]=o.decode(V);if(Z!==0)return;return Q.ts.getTime()+$.off}function TJ($,V){let Q=yQ($),Z=yQ(V);if(Q===void 0&&Z===void 0)return 0;if(Q===void 0)return 1;if(Z===void 0)return-1;if(Z!==Q)return Z-Q;return V.ctr-$.ctr}function t0($,V){return $.slice().sort((Q,Z)=>TJ(V(Q),V(Z)))}var E0={phase:"idle"},e0=50;function y$($,V,Q){if($<=0||V<=0)return!1;if($===1||$===V)return!0;return $%Q===0}function u$($,V){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob($,V);return}let Q=URL.createObjectURL($),Z=document.createElement("a");Z.href=Q,Z.download=V,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)}function uQ($,V,Q){let Z=[],J=[],W=0;for(let Y of $){let X=V(Y);if(J.length>0&&W+X>Q)Z.push(J),J=[],W=0;if(J.push(Y),W+=X,W>=Q)Z.push(J),J=[],W=0}if(J.length>0)Z.push(J);return Z}async function jV($,V,Q){let Z=$.length;if(Z<1)return[];let J=Array(Z),W=0,Y=Math.min(Math.max(1,V),Z),X=async()=>{while(!0){let K=W;if(W+=1,K>=Z)return;J[K]=await Q($[K],K)}},G=[];for(let K=0;K<Y;K++)G.push(X());return await Promise.all(G),J}async function b$($,V,Q,Z){let J=new k($.headCph),[W,Y]=J.readStruct(x$);if(Y!==0)return z(Y);let{sig:X,kdm:G,headCph:K}=W;if(!await Z.checkSigEd25519(X,K,V))return z(3);let R=Q.deriveCipher(G,"decrypt"),N;try{N=await R.decrypt(K)}catch{return z(20)}return F({kdm:G,headEnc:N})}var H0="f",x0="t",N0="e";function AJ($){return $===H0||$===x0||$===N0}function $$($){if($===!0||$===x0)return x0;if($===N0)return N0;return H0}function DJ($){return $$($.apld)===H0}function LV($){return $!==0&&$!==15&&$!==18&&$!==17}function m0($,V,Q){if($.apld=V,V===N0&&Q!==void 0)$.err=Q;else delete $.err}async function S0($,V,Q,Z){let J=Z?.body!==!1,W=$$(V.apld),Y=V.body,X=Y?.length??0,G;if(J&&Y&&X>0)G=await Q.blake3(Y);let K={eid:V.eid,off:V.off??0,ctr:V.ctr??0,len:X,hsh:G},I={hash:$,head:K,apld:W};if(J&&Y!==void 0)I.body=Y;if(W===N0&&V.err!==void 0)I.err=V.err;return I}var xV=1048576,SV=1048576,hQ=64;function _J($){return $.sig.length+$.kdm.length+$.headCph.length+$.bodyCph.length}async function jJ($,V,Q,Z,J){if(Z.length<1)return 0;let[W,Y]=await $.push(Z);if(Y!==0)return Y;if(!W)return 27;for(let G of W){if(G.status!==0){console.error("push err",G);continue}let K=J[G.idx];if(!K){console.error("no hash",G);continue}await V.uploads.deq(Q,[K])}let X=await V.hosts.get(Q);if(X){let G=X.lastSeq,K=G,I=[];for(let R of W)if(R.status===0)I.push(R.seq);I.sort((R,N)=>R-N);for(let R of I)if(R===G+1)G=R;if(G>K)await V.hosts.touch(Q,G)}return 0}async function bQ($,V){if(V.length<1)return F([]);let Q=new Map,Z=[];for(let X of V)Q.set(X.seq,X),Z.push(X.seq);let[J,W]=await $.pull(Z);if(W!==0)return z(W);if(!J)return z(27);let Y=[];for(let{seq:X,bodyCph:G}of J){let K=Q.get(X);if(!K)continue;Y.push({dl:K,bodyCph:G})}return F(Y)}async function LJ($,V,Q,Z){if(Z.length<1)return F({parts:[],hashes:[]});let J=[],W=[],Y=[],X=new Map;for(let{dl:K,bodyCph:I}of Z){let{head:R,kdm:N,seq:U,host:M}=K,[O,H]=await lQ(K,Q);if(H!==0||!O){let f=X.get(M)??[];f.push(U),X.set(M,f);continue}let{headEnc:C,headEncHash:P}=O,T=V.deriveCipher(N,"decrypt"),[q,D]=await KV(C,I,T,Q,P);if(D!==0||!q){let f=X.get(M)??[];f.push(U),X.set(M,f);continue}let S={head:R,body:q.bod},B=q.headHash;Y.push({key:B,data:cQ(S)}),J.push(S),W.push(B);let m=X.get(M)??[];m.push(U),X.set(M,m)}let G=await $.messages.add(Y);for(let[K,I]of X)await $.downloads.deq(K,I);for(let K=0;K<G.length;K++){let I=G[K];if(I!==0&&I!==15)console.error("ERR storing",_[I],"for message",K)}return F({parts:J,hashes:W})}async function lQ($,V){let Q=$.headEnc;if(!Q){let J=new g,W=J.writeStruct(X0,$.head);if(W!==0)return z(W);Q=J.result()}if($.headEncHash)return F({headEnc:Q,headEncHash:$.headEncHash});let Z=await V.blake3(Q);return F({headEnc:Q,headEncHash:Z})}async function pQ($,V,Q){let Z=new Set;for(let Y of V)Z.add(L(Y));if(Z.size<1)return;let J=Array.from(await $.downloads.list());if(J.length<1)return;let W=new Map;for(let Y of J){let X;if(Y.headEncHash)X=L(Y.headEncHash);else{let[K,I]=await lQ(Y,Q);if(I!==0||!K)continue;X=L(K.headEncHash)}if(!Z.has(X))continue;let G=W.get(Y.host)??[];G.push(Y.seq),W.set(Y.host,G)}for(let[Y,X]of W)await $.downloads.deq(Y,X)}async function fV({conn:$,store:V,enclave:Q,host:Z,crypto:J,onProgress:W,peekProgressEvery:Y,peekConcurrency:X}){let G=await $.identity(),K=[],[I,R]=await $.peek(Z.lastSeq);if(R!==0)return R;let N=I.length,U=Y??e0,M=X??hQ;if(W&&N>0)W({phase:"peek",host:Z.label,done:0,total:N});let O=0,H=await jV(I,M,async(P)=>{let[T,q]=await b$(P,G.publicKey,Q,J),D;if(q!==0||!T)D={ok:!1,seq:P.seq,stat:q};else{let S=await J.blake3(T.headEnc);D={ok:!0,seq:P.seq,kdm:T.kdm,headEnc:T.headEnc,headEncHash:S}}if(O+=1,W&&y$(O,N,U))W({phase:"peek",host:Z.label,done:O,total:N});return D}),C=new Set;for(let P of H){if(!P.ok){console.error("peek: decrypting item head",P.stat);continue}let T=L(P.headEncHash);if(await V.messages.has(P.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await V.uploads.deq(Z.label,[P.headEncHash]),await V.downloads.deq(Z.label,[P.seq]);continue}if(C.has(T)){await V.downloads.deq(Z.label,[P.seq]);continue}let D=new k(P.headEnc),[S,B]=D.readStruct(X0);if(B!==0){console.error("peek: reading item head",B);continue}C.add(T),K.push({kdm:P.kdm,head:S,seq:P.seq,host:Z.label,headEnc:P.headEnc,headEncHash:P.headEncHash})}if(await V.downloads.enq(K),I.length>0){let P=Math.max(...I.map((T)=>T.seq));await V.hosts.recordStats(Z.label,{lastSeq:P})}if(W)W({phase:"peek",host:Z.label,done:N,total:N});return 0}async function nQ({conn:$,store:V,host:Q,maxPushBytes:Z,onProgress:J}){let W=Z??xV,Y=await V.uploads.list(Q.label),X=Y.length,G=0;if(J&&X>0)J({phase:"push",host:Q.label,done:0,total:X});let K=[],I=[],R=0,N=async()=>{if(K.length<1)return 0;let U=K.length,M=await jJ($,V,Q.label,K,I);if(K=[],I=[],R=0,M===0){if(G+=U,J)J({phase:"push",host:Q.label,done:G,total:X})}return M};for(let U of Y){let M=await V.messages.get(U);if(!M){G+=1;continue}let O={...M.head,bod:M.body},[H,C]=await $.seal(O);if(C!==0)return C;if(!H)return 12;let P=_J(H);if(K.length>0&&R+P>W){let T=await N();if(T!==0)return T}if(K.push(H),I.push(U),R+=P,R>=W){let T=await N();if(T!==0)return T}}return N()}async function EV({conn:$,store:V,enclave:Q,host:Z,crypto:J,maxPullBytes:W,onProgress:Y},X){let G=W??SV,K=await V.downloads.list(),I=Array.from(K).filter((H)=>H.host===Z.label);if(I.length<1)return 15;let R=t0(I,(H)=>H.head),N=uQ(R,(H)=>H.head.len,G),U=R.length,M=0;if(Y)Y({phase:"pull",host:Z.label,done:0,total:U});let O=bQ($,N[0]);for(let H=0;H<N.length;H++){let[C,P]=await O;if(P!==0||!C)return P;if(M+=N[H].length,Y)Y({phase:"pull",host:Z.label,done:M,total:U});let T=N[H+1];if(T)O=bQ($,T);if(Y)Y({phase:"open",host:Z.label,done:M,total:U});let q=t0(C,(S)=>S.dl.head),[,D]=await LJ(V,Q,J,q);if(D!==0)return D;if(X){if(Y)Y({phase:"exec",host:Z.label,done:M,total:U});await X()}}return 0}function cQ({head:$,body:V}){let Q={eid:$.eid,body:V,apld:H0};if($.off!==0)Q.off=$.off;if($.ctr!==0)Q.ctr=$.ctr;return Q}async function dQ($,{conn:V,store:Q,enclave:Z,host:J,crypto:W,onProgress:Y},X){let G=J.label,K=await V.identity(),I=new k($),[R,N]=I.readStructs(L$);if(N!==0){console.error("Failed decoding notif",_[N]);return}let U=!1,O=(await Q.hosts.get(G))?.lastSeq,H=[],C=!1;for(let q of R){let[D,S]=await b$({seq:q.seq,headCph:q.headCph},K.publicKey,Z,W);if(S!==0){console.error("Failed decrypting notif",_[S]);continue}let B=await W.blake3(D.headEnc);if(await Q.messages.has(B))continue;let m=new k(D.headEnc),[f,i]=m.readStruct(X0);if(i!==0){console.error("Failed to parse head",_[i]);continue}if(!q.bodyCph&&f.len>0)C=!0,await Q.downloads.enq([{seq:q.seq,host:G,kdm:D.kdm,head:f,headEnc:D.headEnc,headEncHash:B}]);else H.push({...D,head:f,bodyCph:q.bodyCph,headEncHash:B});if(O===void 0||q.seq!==O+1)console.log("out of seq",q.seq,O),U=!0;else O=q.seq}if(O!==void 0)await Q.hosts.touch(J.label,O);let P=[];for(let q of H){let D=Z.deriveCipher(q.kdm,"decrypt"),[S,B]=await KV(q.headEnc,q.bodyCph,D,W);if(B!==0){console.error("Failed to open body",_[B]);continue}P.push({key:q.headEncHash,data:cQ({head:q.head,body:S.bod})})}let T=await Q.messages.add(P);for(let q=0;q<T.length;q++){let D=T[q];if(D!==0&&D!==15)console.error("ERR storing",_[D],"for message",q)}if(Y&&P.length>0)Y({phase:"open",host:J.label,done:P.length,total:P.length});if(U||C||P.length>0)X()}async function mV($,V={}){let Q=V.pull!==!1,Z=V.push===!0,{conn:J,store:W,enclave:Y,host:X,crypto:G,onProgress:K,peekProgressEvery:I,peekConcurrency:R}=$,N=await J.identity(),[U,M]=await J.peek(0);if(M!==0)return z(M);let O=U.length,H=I??e0,C=R??hQ;if(K&&O>0)K({phase:"peek",host:X.label,done:0,total:O});let P=0,T=await jV(U,C,async(x)=>{let[v,E]=await b$(x,N.publicKey,Y,G),y;if(E!==0||!v)y={ok:!1,seq:x.seq,stat:E};else{let j=await G.blake3(v.headEnc);y={ok:!0,seq:x.seq,kdm:v.kdm,headEnc:v.headEnc,headEncHash:j}}if(P+=1,K&&y$(P,O,H))K({phase:"peek",host:X.label,done:P,total:O});return y}),q=new Map;for(let x of T){if(!x.ok)continue;let v=L(x.headEncHash),E=q.get(v);if(E)E.count+=1;else q.set(v,{hash:x.headEncHash,count:1,sample:x})}let D=0,S=[];for(let x of q.values()){if(x.count>1)D+=x.count-1;S.push(x.hash)}let B=U.length,m=q.size,f=await d0(S,G),i=[],w=0;for(let x of q.values()){if(await W.messages.has(x.hash)){await W.uploads.deq(X.label,[x.hash]);continue}if(w+=1,!Q)continue;let E=x.sample,y=new k(E.headEnc),[j,c]=y.readStruct(X0);if(c!==0){console.error("reconcile: reading msg header",c);continue}i.push({kdm:E.kdm,head:j,seq:E.seq,host:X.label,headEnc:E.headEnc,headEncHash:E.headEncHash})}if(i.length>0)await W.downloads.enq(i);let b=0;if(Z){let x=await W.messages.listKeys(),v=new Set(q.keys()),E=[];for(let y of x)if(!v.has(L(y)))b+=1,E.push(y);if(E.length>0)await W.uploads.enq(X.label,E)}else{let x=await W.messages.listKeys(),v=new Set(q.keys());for(let E of x)if(!v.has(L(E)))b+=1}let l=U.length>0?Math.max(...U.map((x)=>x.seq)):0;if(await W.hosts.recordStats(X.label,{setLastSeq:l}),K)K({phase:"peek",host:X.label,done:O,total:O});return F({msgcheck:f,numBags:B,uniqueMsgs:m,numDupes:D,missingLocal:w,missingHost:b})}class B0{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new v$;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=e0;lastProgress=E0;scheduledSync;constructor($,V,Q,Z,J,W=!0,Y=xV,X=SV,G){this.clock=$;this.state=V;this.store=Q;this.transport=Z;this.crypto=J;this.forceSkewHandlingByDefault=W;this.onScheduleSync=G;this.maxPushBytes=Y,this.maxPullBytes=X,this.clientState=new R0(()=>this.getClientState()),this.xferState=new R0(()=>this.getXferState()),this.scheduledSync=new N$(i$,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($,V){await this.store.seed.save($,V),this.clientState.emit()}async getClientState(){let{store:$,connections:V}=this,Q=await $.seed.load(),Z=await $.hosts.list(),J=!1;for(let W of V.values())if(W.isConnected()){J=!0;break}return{hasSeed:Q!==void 0,hasHost:Array.from(Z).length>0,connected:J}}async getXferState(){let{uploads:$,downloads:V}=this.store,Q=await $.count();return{numDownloads:await V.count(),numUploads:Q,progress:this.lastProgress}}apply=($,V)=>{return this.enqueueApplyJob(()=>this.doApply($,V))};async doApply($,V={enqueueUpload:!0,triggerUpload:!0}){let Q=[],Z=[];for(let{head:W,body:Y}of $){let X=new g;X.writeStruct(X0,W);let G=X.result(),K=await this.crypto.blake3(G),I={eid:W.eid,body:Y,apld:H0};if(W.off!==0)I.off=W.off;if(W.ctr!==0)I.ctr=W.ctr;Q.push(K),Z.push({key:K,data:I})}await this.store.messages.add(Z),await pQ(this.store,Q,this.crypto);let J=await this.doApplyHashes(Q);if(V.enqueueUpload){let W=[];for(let Y=0;Y<Q.length;Y++){let X=J[Y];if(X===0||X===15)W.push(Q[Y])}if(W.length>0){let Y=await this.store.hosts.list();for(let X of Y)await this.store.uploads.enq(X.label,W);this.xferState.emit()}}if(V.triggerUpload)this.scheduleSync();return J}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:H0});if($.length<1)return[];let V=t0($,(Q)=>Q.head);return this.applyStored(V)}applyHashes=($)=>{return this.enqueueApplyJob(()=>this.doApplyHashes($))};async doApplyHashes($){let V=[];for(let J of $){let W=await this.store.messages.get(J);if(W)V.push(W)}let Q=await this.applyStored(V),Z=new Map;for(let J=0;J<V.length;J++)Z.set(L(V[J].hash),Q[J]??12);return $.map((J)=>Z.get(L(J))??13)}async applyStored($){if($.length<1)return[];let V=$.map((W)=>({...W.head,bod:W.body})),Q=await this.state.apply(V),Z=[],J=[];for(let W=0;W<$.length;W++){let Y=Q[W];if(Y===0||Y===15)Z.push($[W].hash);else if(Y!==void 0&&LV(Y))J.push({key:$[W].hash,err:Y})}if(Z.length>0)await this.store.messages.markApplied(Z);if(J.length>0)await this.store.messages.markFailed(J);return Q}async insertRaw($){let{clock:V,crypto:Q}=this,[Z,J]=await fQ({now:V.now(),bod:$,crypto:Q});if(J!==0)return z(J);let Y=(await this.apply([{head:Z,body:$}]))[0];if(Y!==0&&Y!==15)return z(Y??12);return F(Z)}async makeUpdate($,V){let{clock:Q,crypto:Z}=this,J=Q.now();if($.updatedAt.getTime()>J.getTime())return z(4);let W=$.ctr+1,[Y,X]=await m$({now:J,eid:$.eid,ctr:W,bod:V,crypto:Z});if(X!==0)return z(X);return F({head:Y,body:V})}async updateWithSkew($,V,Q){if(Q===!1)return z(4);let{clock:Z,crypto:J}=this,W=Z.now(),Y=new k($.eid),[X,G]=Y.readStruct(o);if(G!==0)return z(G);let K=$.updatedAt.getTime()-X.ts.getTime(),I={eid:$.eid,off:K+1,ctr:$.ctr+1,len:0},N=(await this.apply([{head:I,body:void 0}]))[0];if(N!==0&&N!==15)return z(N??12);if(V===void 0)return F(I);let[U,M]=c0({id:X.id,ts:W});if(M!==0)return z(M);let[O,H]=await m$({now:W,eid:U,ctr:0,bod:V,crypto:J});if(H!==0)return z(H);let P=(await this.apply([{head:O,body:V}]))[0];if(P!==0&&P!==15)return z(P??12);return F(O)}async updateRaw($,V,Q=this.forceSkewHandlingByDefault){if($.updatedAt.getTime()>this.clock.now().getTime())return this.updateWithSkew($,V,Q);return this.enqueueApplyJob(async()=>{let[Z,J]=await this.makeUpdate($,V);if(J!==0)return z(J);let Y=(await this.doApply([Z]))[0];if(Y!==0&&Y!==15)return z(Y??12);return F(Z.head)})}async insert($){let{body:V,type:Q,gid:Z,pid:J,tags:W}=$,X=f0({body:V,type:Q,gid:Z,pid:J,tags:W});return this.insertRaw(X)}async update($){let{prior:V,body:Q,type:Z,gid:J,pid:W,tags:Y,force:X}=$,K=f0({body:Q,type:Z,gid:J,pid:W,tags:Y});return this.updateRaw(V,K,X??this.forceSkewHandlingByDefault)}async delete($){let V=$.force??!0;if("prior"in $)return this.updateRaw($.prior,void 0,V);let[Q,Z]=await this.revFromArchive($.eid);if(Z!==0)return z(Z);return this.updateRaw(Q,void 0,V)}async revFromArchive($){let V=await this.store.messages.last($);if(V)return _V(V.head);let Q=new k($),[Z,J]=Q.readStruct(o);if(J!==0)return z(J);return F({eid:$,ctr:-1,updatedAt:Z.ts})}async genEID($){let{clock:V,crypto:Q}=this,Z=V.now();if($!==void 0)return c0({id:$,ts:Z});let J=await Q.genRandomBytes(8);return c0({id:J,ts:Z})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:$,crypto:V,store:Q}=this,Z=await Q.seed.load();if(!Z)return 22;await this.drainApplyQueue();for(let[J,W]of $){let Y=await Q.hosts.get(J);if(!Y)continue;let X={conn:W,store:Q,enclave:Z,host:Y,crypto:V,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},G=await fV(X);if(G!==0)return console.error(`Failed to peek: ${G}`),this.emitProgress({phase:"idle"}),G;this.xferState.emit();let K=await nQ(X);if(K!==0)return console.error(`Failed to push: ${K}`),this.emitProgress({phase:"idle"}),K;this.xferState.emit();let I=await EV(X,async()=>{await this.drainApplyQueue()});if(I!==0&&I!==15)return console.error(`Failed to pull: ${I}`),this.emitProgress({phase:"idle"}),I;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async rebuild($){if(this.scheduledSync.cancel(),await this.syncRuns.flush(),$?.checkHost??!0){let Q=await this.repull();if(Q!==0)return Q}return this.enqueueApplyJob(()=>this.replay())}async msgcheck(){let $=await this.store.messages.listKeys();return d0($,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:Q,crypto:Z,store:J}=this,W=await J.seed.load();if(!W)return z(22);let Y=await J.hosts.get($);if(!Y)return z(13);let X=Q.get($);if(!X||!X.isConnected()){if(await this.connectToHost(Y,!1,!1),Y=await J.hosts.get($),!Y)return z(13);X=Q.get($)}if(!X)return z(12);let G={conn:X,store:J,enclave:W,crypto:Z,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},[K,I]=await mV({...G,host:Y},V);if(this.xferState.emit(),I!==0)return this.emitProgress({phase:"idle"}),z(I);if(!K)return this.emitProgress({phase:"idle"}),z(12);if(V?.sync===!1)return this.emitProgress({phase:"idle"}),F(K);let R=await this.sync();if(R!==0)return z(R);let N=await J.hosts.get($);if(!N)return z(13);let[U,M]=await mV({...G,host:N},{pull:!1,push:!1});if(this.xferState.emit(),this.emitProgress({phase:"idle"}),M!==0)return z(M);if(!U)return z(12);return F(U)}async repull(){let{connections:$,crypto:V,store:Q}=this,Z=await Q.seed.load();if(!Z)return 22;let J=Array.from(await Q.hosts.list());if(J.length<1)return 0;for(let W of J){let Y=$.get(W.label);if(!Y||!Y.isConnected())await this.connectToHost(W,!1,!1)}for(let[W,Y]of $){let X=await Q.hosts.get(W);if(!X)continue;let G={conn:Y,store:Q,enclave:Z,host:{...X,lastSeq:0},crypto:V,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},K=await fV(G);if(K!==0)return console.error(`rebuild: failed to peek: ${K}`),this.emitProgress({phase:"idle"}),K;this.xferState.emit();let I=await EV(G);if(I!==0&&I!==15)return console.error(`rebuild: failed to pull: ${I}`),this.emitProgress({phase:"idle"}),I;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(),Q=t0(V,(W)=>W.head),Z=Q.length;if(Z<1)return this.emitProgress({phase:"idle"}),0;let J=0;while(J<Q.length){let W=0,Y=0,X=J;for(let K=J;K<Q.length&&Y<100&&W<102400;K++)W+=Q[K].head.len,Y++,X=K+1;let G=Q.slice(J,X);await this.applyStored(G),this.emitProgress({phase:"exec",done:X,total:Z}),J=X}return this.emitProgress({phase:"idle"}),0}async wipe($){let V=$?.msgs!==!1,Q=$?.ents!==!1,Z=$?.meta!==!1,J=$?.seed===!0;this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush();let{store:W}=this;if(Z)await W.hosts.wipe(),await W.uploads.wipe(),await W.downloads.wipe();if(V)await W.messages.wipe();if(J)await W.seed.wipe();if(Q)await this.state.clear();this.lastProgress=E0,this.clientState.emit(),this.xferState.emit()}import=async($,V)=>{let{crypto:Q,store:Z}=this,J=V?.onProgress,W=await Z.seed.load();if(!W)return 22;console.time("import: decoding file...");let Y=await $.bytes(),[X,G]=await SQ(Y,Q,W);if(G!==0)return G;console.timeEnd("import: decoding file...");let K=0;while(K<X.length){let I=0,R=0,N=K;for(let O=K;O<X.length&&R<100&&I<102400;O++)I+=X[O].head.len,R++,N=O+1;let U=X.slice(K,N);console.time(`import: applying [${K}, ${N}]`);let M=await this.apply(U,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${K}, ${N}]`);for(let O=0;O<U.length;O++){let H=M[O];if(H!==0&&H!==15)console.warn(`failed to import msg ${K+O}: ${_[H]}`)}if(J)queueMicrotask(()=>J(N,X.length,0));this.emitProgress({phase:"import",done:N,total:X.length}),K=N}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,Q=await V.seed.load();if(!Q)return z(22);let Z=await V.messages.list();return xQ("export",0,Z,$,Q)}async export($){let[V,Q]=await this.exportBytes();if(Q!==0)return Q;if(!V)return 12;let Z=new Blob([V.slice()]);return u$(Z,$),0}async link($,V=!0){if(await this.store.hosts.add($),this.clientState.emit(),V){let Q=await this.store.hosts.get($.label);if(Q)await this.connectToHost(Q)}}async unlink($){await this.store.hosts.del($),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async($,V=!0,Q=!0)=>{let{clock:Z,connections:J,crypto:W,store:Y,transport:X}=this,G=J.get($.label);if(G){if(G.isConnected())return;try{G.closeListener()}catch{}J.delete($.label)}let K=await Y.seed.load();if(!K)return;console.info(`Connecting to ${$.handle} (${$.label})`);let I=new E$(K,W,$,Z,X($),(R)=>Y.hosts.set($.label,R));if(await I.register(),V)await I.listen(async(R)=>{let N={conn:I,store:Y,enclave:K,host:$,crypto:W,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return dQ(R,N,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(J.set($.label,I),this.clientState.emit(),Q)this.scheduleSync()};async connect($=!0,V=!0){let{connectToHost:Q,scheduleSync:Z,store:J}=this;if(!await J.seed.load())return;await this.drainApplyQueue();let Y=await J.hosts.list();for(let X of Y)await Q(X,$,!1);if(V)Z()}disconnect=async()=>{for(let $ of this.connections.values())try{$.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var k0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function h$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function BV($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function d($,...V){if(!BV($))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 rQ($,V){d($);let Q=V.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function gV($){if(typeof $!=="boolean")throw Error(`boolean expected, not ${$}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var q0=($)=>new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4));var xJ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!xJ)throw Error("Non little-endian hardware is not supported");function SJ($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function l$($){if(typeof $==="string")$=SJ($);else if(BV($))$=p$($);else throw Error("Uint8Array expected, got "+typeof $);return $}function oQ($,V){if(V==null||typeof V!=="object")throw Error("options must be defined");return Object.assign($,V)}function aQ($,V){if($.length!==V.length)return!1;let Q=0;for(let Z=0;Z<$.length;Z++)Q|=$[Z]^V[Z];return Q===0}var sQ=($,V)=>{function Q(Z,...J){if(d(Z),$.nonceLength!==void 0){let I=J[0];if(!I)throw Error("nonce / iv required");if($.varSizeNonce)d(I);else d(I,$.nonceLength)}let W=$.tagLength;if(W&&J[1]!==void 0)d(J[1]);let Y=V(Z,...J),X=(I,R)=>{if(R!==void 0){if(I!==2)throw Error("cipher output not supported");d(R)}},G=!1;return{encrypt(I,R){if(G)throw Error("cannot encrypt() twice with same key + nonce");return G=!0,d(I),X(Y.encrypt.length,R),Y.encrypt(I,R)},decrypt(I,R){if(d(I),W&&I.length<W)throw Error("invalid ciphertext length: smaller than tagLength="+W);return X(Y.decrypt.length,R),Y.decrypt(I,R)}}}return Object.assign(Q,$),Q};function vV($,V,Q=!0){if(V===void 0)return new Uint8Array($);if(V.length!==$)throw Error("invalid output length, expected "+$+", got: "+V.length);if(Q&&!fJ(V))throw Error("invalid output, must be aligned");return V}function fJ($){return $.byteOffset%4===0}function p$($){return Uint8Array.from($)}function U0(...$){for(let V=0;V<$.length;V++)$[V].fill(0)}function n$($=32){if(k0&&typeof k0.getRandomValues==="function")return k0.getRandomValues(new Uint8Array($));if(k0&&typeof k0.randomBytes==="function")return k0.randomBytes($);throw Error("crypto.getRandomValues must be defined")}var eQ=($)=>Uint8Array.from($.split("").map((V)=>V.charCodeAt(0))),EJ=eQ("expand 16-byte k"),mJ=eQ("expand 32-byte k"),BJ=q0(EJ),kJ=q0(mJ);function A($,V){return $<<V|$>>>32-V}function iV($){return $.byteOffset%4===0}var c$=64,gJ=16,$Z=4294967295,tQ=new Uint32Array;function vJ($,V,Q,Z,J,W,Y,X){let G=J.length,K=new Uint8Array(c$),I=q0(K),R=iV(J)&&iV(W),N=R?q0(J):tQ,U=R?q0(W):tQ;for(let M=0;M<G;Y++){if($(V,Q,Z,I,Y,X),Y>=$Z)throw Error("arx: counter overflow");let O=Math.min(c$,G-M);if(R&&O===c$){let H=M/4;if(M%4!==0)throw Error("arx: invalid block position");for(let C=0,P;C<gJ;C++)P=H+C,U[P]=N[P]^I[C];M+=c$;continue}for(let H=0,C;H<O;H++)C=M+H,W[C]=J[C]^K[H];M+=O}}function VZ($,V){let{allowShortKeys:Q,extendNonceFn:Z,counterLength:J,counterRight:W,rounds:Y}=oQ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},V);if(typeof $!=="function")throw Error("core must be a function");return h$(J),h$(Y),gV(W),gV(Q),(X,G,K,I,R=0)=>{d(X),d(G),d(K);let N=K.length;if(I===void 0)I=new Uint8Array(N);if(d(I),h$(R),R<0||R>=$Z)throw Error("arx: counter overflow");if(I.length<N)throw Error(`arx: output (${I.length}) is shorter than data (${N})`);let U=[],M=X.length,O,H;if(M===32)U.push(O=p$(X)),H=kJ;else if(M===16&&Q)O=new Uint8Array(32),O.set(X),O.set(X,16),H=BJ,U.push(O);else throw Error(`arx: invalid 32-byte key, got length=${M}`);if(!iV(G))U.push(G=p$(G));let C=q0(O);if(Z){if(G.length!==24)throw Error("arx: extended nonce must be 24 bytes");Z(H,C,q0(G.subarray(0,16)),C),G=G.subarray(16)}let P=16-J;if(P!==G.length)throw Error(`arx: nonce must be ${P} or 16 bytes`);if(P!==12){let q=new Uint8Array(12);q.set(G,W?0:12-G.length),G=q,U.push(G)}let T=q0(G);return vJ($,H,C,T,K,I,R,Y),U0(...U),I}}var s=($,V)=>$[V++]&255|($[V++]&255)<<8;class QZ{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,$=l$($),d($,32);let V=s($,0),Q=s($,2),Z=s($,4),J=s($,6),W=s($,8),Y=s($,10),X=s($,12),G=s($,14);this.r[0]=V&8191,this.r[1]=(V>>>13|Q<<3)&8191,this.r[2]=(Q>>>10|Z<<6)&7939,this.r[3]=(Z>>>7|J<<9)&8191,this.r[4]=(J>>>4|W<<12)&255,this.r[5]=W>>>1&8190,this.r[6]=(W>>>14|Y<<2)&8191,this.r[7]=(Y>>>11|X<<5)&8065,this.r[8]=(X>>>8|G<<8)&8191,this.r[9]=G>>>5&127;for(let K=0;K<8;K++)this.pad[K]=s($,16+2*K)}process($,V,Q=!1){let Z=Q?0:2048,{h:J,r:W}=this,Y=W[0],X=W[1],G=W[2],K=W[3],I=W[4],R=W[5],N=W[6],U=W[7],M=W[8],O=W[9],H=s($,V+0),C=s($,V+2),P=s($,V+4),T=s($,V+6),q=s($,V+8),D=s($,V+10),S=s($,V+12),B=s($,V+14),m=J[0]+(H&8191),f=J[1]+((H>>>13|C<<3)&8191),i=J[2]+((C>>>10|P<<6)&8191),w=J[3]+((P>>>7|T<<9)&8191),b=J[4]+((T>>>4|q<<12)&8191),l=J[5]+(q>>>1&8191),x=J[6]+((q>>>14|D<<2)&8191),v=J[7]+((D>>>11|S<<5)&8191),E=J[8]+((S>>>8|B<<8)&8191),y=J[9]+(B>>>5|Z),j=0,c=j+m*Y+f*(5*O)+i*(5*M)+w*(5*U)+b*(5*N);j=c>>>13,c&=8191,c+=l*(5*R)+x*(5*I)+v*(5*K)+E*(5*G)+y*(5*X),j+=c>>>13,c&=8191;let $0=j+m*X+f*Y+i*(5*O)+w*(5*M)+b*(5*U);j=$0>>>13,$0&=8191,$0+=l*(5*N)+x*(5*R)+v*(5*I)+E*(5*K)+y*(5*G),j+=$0>>>13,$0&=8191;let W0=j+m*G+f*X+i*Y+w*(5*O)+b*(5*M);j=W0>>>13,W0&=8191,W0+=l*(5*U)+x*(5*N)+v*(5*R)+E*(5*I)+y*(5*K),j+=W0>>>13,W0&=8191;let p=j+m*K+f*G+i*X+w*Y+b*(5*O);j=p>>>13,p&=8191,p+=l*(5*M)+x*(5*U)+v*(5*N)+E*(5*R)+y*(5*I),j+=p>>>13,p&=8191;let O0=j+m*I+f*K+i*G+w*X+b*Y;j=O0>>>13,O0&=8191,O0+=l*(5*O)+x*(5*M)+v*(5*U)+E*(5*N)+y*(5*R),j+=O0>>>13,O0&=8191;let i0=j+m*R+f*I+i*K+w*G+b*X;j=i0>>>13,i0&=8191,i0+=l*Y+x*(5*O)+v*(5*M)+E*(5*U)+y*(5*N),j+=i0>>>13,i0&=8191;let y0=j+m*N+f*R+i*I+w*K+b*G;j=y0>>>13,y0&=8191,y0+=l*X+x*Y+v*(5*O)+E*(5*M)+y*(5*U),j+=y0>>>13,y0&=8191;let u0=j+m*U+f*N+i*R+w*I+b*K;j=u0>>>13,u0&=8191,u0+=l*G+x*X+v*Y+E*(5*O)+y*(5*M),j+=u0>>>13,u0&=8191;let b0=j+m*M+f*U+i*N+w*R+b*I;j=b0>>>13,b0&=8191,b0+=l*K+x*G+v*X+E*Y+y*(5*O),j+=b0>>>13,b0&=8191;let h0=j+m*O+f*M+i*U+w*N+b*R;j=h0>>>13,h0&=8191,h0+=l*I+x*K+v*G+E*X+y*Y,j+=h0>>>13,h0&=8191,j=(j<<2)+j|0,j=j+c|0,c=j&8191,j=j>>>13,$0+=j,J[0]=c,J[1]=$0,J[2]=W0,J[3]=p,J[4]=O0,J[5]=i0,J[6]=y0,J[7]=u0,J[8]=b0,J[9]=h0}finalize(){let{h:$,pad:V}=this,Q=new Uint16Array(10),Z=$[1]>>>13;$[1]&=8191;for(let Y=2;Y<10;Y++)$[Y]+=Z,Z=$[Y]>>>13,$[Y]&=8191;$[0]+=Z*5,Z=$[0]>>>13,$[0]&=8191,$[1]+=Z,Z=$[1]>>>13,$[1]&=8191,$[2]+=Z,Q[0]=$[0]+5,Z=Q[0]>>>13,Q[0]&=8191;for(let Y=1;Y<10;Y++)Q[Y]=$[Y]+Z,Z=Q[Y]>>>13,Q[Y]&=8191;Q[9]-=8192;let J=(Z^1)-1;for(let Y=0;Y<10;Y++)Q[Y]&=J;J=~J;for(let Y=0;Y<10;Y++)$[Y]=$[Y]&J|Q[Y];$[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 W=$[0]+V[0];$[0]=W&65535;for(let Y=1;Y<8;Y++)W=($[Y]+V[Y]|0)+(W>>>16)|0,$[Y]=W&65535;U0(Q)}update($){kV(this);let{buffer:V,blockLen:Q}=this;$=l$($);let Z=$.length;for(let J=0;J<Z;){let W=Math.min(Q-this.pos,Z-J);if(W===Q){for(;Q<=Z-J;J+=Q)this.process($,J);continue}if(V.set($.subarray(J,J+W),this.pos),this.pos+=W,J+=W,this.pos===Q)this.process(V,0,!1),this.pos=0}return this}destroy(){U0(this.h,this.r,this.buffer,this.pad)}digestInto($){kV(this),rQ($,this),this.finished=!0;let{buffer:V,h:Q}=this,{pos:Z}=this;if(Z){V[Z++]=1;for(;Z<16;Z++)V[Z]=0;this.process(V,0,!0)}this.finalize();let J=0;for(let W=0;W<8;W++)$[J++]=Q[W]>>>0,$[J++]=Q[W]>>>8;return $}digest(){let{buffer:$,outputLen:V}=this;this.digestInto($);let Q=$.slice(0,V);return this.destroy(),Q}}function iJ($){let V=(Z,J)=>$(J).update(l$(Z)).digest(),Q=$(new Uint8Array(32));return V.outputLen=Q.outputLen,V.blockLen=Q.blockLen,V.create=(Z)=>$(Z),V}var yV=iJ(($)=>new QZ($));function yJ($,V,Q,Z,J,W=20){let Y=$[0],X=V[0],G=V[1],K=V[2],I=V[3],R=$[1],N=Q[0],U=Q[1],M=J,O=0,H=$[2],C=V[4],P=V[5],T=V[6],q=V[7],D=$[3],S=Y,B=X,m=G,f=K,i=I,w=R,b=N,l=U,x=M,v=O,E=H,y=C,j=P,c=T,$0=q,W0=D;for(let O0=0;O0<W;O0+=2)i^=A(S+j|0,7),x^=A(i+S|0,9),j^=A(x+i|0,13),S^=A(j+x|0,18),v^=A(w+B|0,7),c^=A(v+w|0,9),B^=A(c+v|0,13),w^=A(B+c|0,18),$0^=A(E+b|0,7),m^=A($0+E|0,9),b^=A(m+$0|0,13),E^=A(b+m|0,18),f^=A(W0+y|0,7),l^=A(f+W0|0,9),y^=A(l+f|0,13),W0^=A(y+l|0,18),B^=A(S+f|0,7),m^=A(B+S|0,9),f^=A(m+B|0,13),S^=A(f+m|0,18),b^=A(w+i|0,7),l^=A(b+w|0,9),i^=A(l+b|0,13),w^=A(i+l|0,18),y^=A(E+v|0,7),x^=A(y+E|0,9),v^=A(x+y|0,13),E^=A(v+x|0,18),j^=A(W0+$0|0,7),c^=A(j+W0|0,9),$0^=A(c+j|0,13),W0^=A($0+c|0,18);let p=0;Z[p++]=Y+S|0,Z[p++]=X+B|0,Z[p++]=G+m|0,Z[p++]=K+f|0,Z[p++]=I+i|0,Z[p++]=R+w|0,Z[p++]=N+b|0,Z[p++]=U+l|0,Z[p++]=M+x|0,Z[p++]=O+v|0,Z[p++]=H+E|0,Z[p++]=C+y|0,Z[p++]=P+j|0,Z[p++]=T+c|0,Z[p++]=q+$0|0,Z[p++]=D+W0|0}function uJ($,V,Q,Z){let J=$[0],W=V[0],Y=V[1],X=V[2],G=V[3],K=$[1],I=Q[0],R=Q[1],N=Q[2],U=Q[3],M=$[2],O=V[4],H=V[5],C=V[6],P=V[7],T=$[3];for(let D=0;D<20;D+=2)G^=A(J+H|0,7),N^=A(G+J|0,9),H^=A(N+G|0,13),J^=A(H+N|0,18),U^=A(K+W|0,7),C^=A(U+K|0,9),W^=A(C+U|0,13),K^=A(W+C|0,18),P^=A(M+I|0,7),Y^=A(P+M|0,9),I^=A(Y+P|0,13),M^=A(I+Y|0,18),X^=A(T+O|0,7),R^=A(X+T|0,9),O^=A(R+X|0,13),T^=A(O+R|0,18),W^=A(J+X|0,7),Y^=A(W+J|0,9),X^=A(Y+W|0,13),J^=A(X+Y|0,18),I^=A(K+G|0,7),R^=A(I+K|0,9),G^=A(R+I|0,13),K^=A(G+R|0,18),O^=A(M+U|0,7),N^=A(O+M|0,9),U^=A(N+O|0,13),M^=A(U+N|0,18),H^=A(T+P|0,7),C^=A(H+T|0,9),P^=A(C+H|0,13),T^=A(P+C|0,18);let q=0;Z[q++]=J,Z[q++]=K,Z[q++]=M,Z[q++]=T,Z[q++]=I,Z[q++]=R,Z[q++]=N,Z[q++]=U}var uV=VZ(yJ,{counterRight:!0,extendNonceFn:uJ}),bV=sQ({blockSize:64,nonceLength:24,tagLength:16},($,V)=>{return{encrypt(Q,Z){Z=vV(Q.length+32,Z,!1);let J=Z.subarray(0,32),W=Z.subarray(32);Z.set(Q,32),U0(J),uV($,V,Z,Z);let Y=yV(W,J);return Z.set(Y,16),U0(Z.subarray(0,16),Y),Z.subarray(16)},decrypt(Q,Z){d(Q),Z=vV(Q.length+32,Z,!1);let J=Z.subarray(0,32),W=Z.subarray(32,48),Y=Z.subarray(48);Z.set(Q,32),U0(J);let X=uV($,V,J,J),G=yV(Y,X);if(!aQ(W,G))throw Error("invalid tag");return uV($,V,Z.subarray(16),Z.subarray(16)),U0(J,W,G),Y}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function bJ($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function U$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function g0($,...V){if(!bJ($))throw Error("Uint8Array expected");if(V.length>0&&!V.includes($.length))throw Error("Uint8Array expected of length "+V+", got length="+$.length)}function F$($,V=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(V&&$.finished)throw Error("Hash#digest() has already been called")}function d$($,V){g0($);let Q=V.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function ZZ($){return new Uint8Array($.buffer,$.byteOffset,$.byteLength)}function V$($){return new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4))}function Q$(...$){for(let V=0;V<$.length;V++)$[V].fill(0)}function O$($,V){return $<<32-V|$>>>V}var JZ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function WZ($){return $<<24&4278190080|$<<8&16711680|$>>>8&65280|$>>>24&255}var YZ=JZ?($)=>$:($)=>WZ($);function hJ($){for(let V=0;V<$.length;V++)$[V]=WZ($[V]);return $}var Z0=JZ?($)=>$:hJ;function lJ($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function Z$($){if(typeof $==="string")$=lJ($);return g0($),$}class hV{}function XZ($){let V=(Z,J)=>$(J).update(Z$(Z)).digest(),Q=$({});return V.outputLen=Q.outputLen,V.blockLen=Q.blockLen,V.create=(Z)=>$(Z),V}var GZ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var r$=BigInt(4294967295),KZ=BigInt(32);function lV($,V=!1){if(V)return{h:Number($&r$),l:Number($>>KZ&r$)};return{h:Number($>>KZ&r$)|0,l:Number($&r$)|0}}function P0($,V,Q,Z,J){return $=$+V+J|0,Z=O$(Z^$,16),Q=Q+Z|0,V=O$(V^Q,12),{a:$,b:V,c:Q,d:Z}}function C0($,V,Q,Z,J){return $=$+V+J|0,Z=O$(Z^$,8),Q=Q+Z|0,V=O$(V^Q,7),{a:$,b:V,c:Q,d:Z}}class pV extends hV{constructor($,V){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,U$($),U$(V),this.blockLen=$,this.outputLen=V,this.buffer=new Uint8Array($),this.buffer32=V$(this.buffer)}update($){F$(this),$=Z$($),g0($);let{blockLen:V,buffer:Q,buffer32:Z}=this,J=$.length,W=$.byteOffset,Y=$.buffer;for(let X=0;X<J;){if(this.pos===V)Z0(Z),this.compress(Z,0,!1),Z0(Z),this.pos=0;let G=Math.min(V-this.pos,J-X),K=W+X;if(G===V&&!(K%4)&&X+G<J){let I=new Uint32Array(Y,K,Math.floor((J-X)/4));Z0(I);for(let R=0;X+V<J;R+=Z.length,X+=V)this.length+=V,this.compress(I,R,!1);Z0(I);continue}Q.set($.subarray(X,X+G),this.pos),this.pos+=G,this.length+=G,X+=G}return this}digestInto($){F$(this),d$($,this);let{pos:V,buffer32:Q}=this;this.finished=!0,Q$(this.buffer.subarray(V)),Z0(Q),this.compress(Q,0,!0),Z0(Q);let Z=V$($);this.get().forEach((J,W)=>Z[W]=YZ(J))}digest(){let{buffer:$,outputLen:V}=this;this.digestInto($);let Q=$.slice(0,V);return this.destroy(),Q}_cloneInto($){let{buffer:V,length:Q,finished:Z,destroyed:J,outputLen:W,pos:Y}=this;return $||($=new this.constructor({dkLen:W})),$.set(...this.get()),$.buffer.set(V),$.destroyed=J,$.finished=Z,$.length=Q,$.pos=Y,$.outputLen=W,$}clone(){return this._cloneInto()}}function nV($,V,Q,Z,J,W,Y,X,G,K,I,R,N,U,M,O,H,C,P,T){let q=0;for(let D=0;D<Z;D++)({a:J,b:G,c:N,d:H}=P0(J,G,N,H,Q[V+$[q++]])),{a:J,b:G,c:N,d:H}=C0(J,G,N,H,Q[V+$[q++]]),{a:W,b:K,c:U,d:C}=P0(W,K,U,C,Q[V+$[q++]]),{a:W,b:K,c:U,d:C}=C0(W,K,U,C,Q[V+$[q++]]),{a:Y,b:I,c:M,d:P}=P0(Y,I,M,P,Q[V+$[q++]]),{a:Y,b:I,c:M,d:P}=C0(Y,I,M,P,Q[V+$[q++]]),{a:X,b:R,c:O,d:T}=P0(X,R,O,T,Q[V+$[q++]]),{a:X,b:R,c:O,d:T}=C0(X,R,O,T,Q[V+$[q++]]),{a:J,b:K,c:M,d:T}=P0(J,K,M,T,Q[V+$[q++]]),{a:J,b:K,c:M,d:T}=C0(J,K,M,T,Q[V+$[q++]]),{a:W,b:I,c:O,d:H}=P0(W,I,O,H,Q[V+$[q++]]),{a:W,b:I,c:O,d:H}=C0(W,I,O,H,Q[V+$[q++]]),{a:Y,b:R,c:N,d:C}=P0(Y,R,N,C,Q[V+$[q++]]),{a:Y,b:R,c:N,d:C}=C0(Y,R,N,C,Q[V+$[q++]]),{a:X,b:G,c:U,d:P}=P0(X,G,U,P,Q[V+$[q++]]),{a:X,b:G,c:U,d:P}=C0(X,G,U,P,Q[V+$[q++]]);return{v0:J,v1:W,v2:Y,v3:X,v4:G,v5:K,v6:I,v7:R,v8:N,v9:U,v10:M,v11:O,v12:H,v13:C,v14:P,v15:T}}var F0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},w0=GZ.slice(),zZ=(()=>{let $=Array.from({length:16},(Z,J)=>J),V=(Z)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((J)=>Z[J]),Q=[];for(let Z=0,J=$;Z<7;Z++,J=V(J))Q.push(...J);return Uint8Array.from(Q)})();class cV extends pV{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:Q,context:Z}=$,J=Z!==void 0;if(Q!==void 0){if(J)throw Error('Only "key" or "context" can be specified at same time');let W=Z$(Q).slice();g0(W,32),this.IV=V$(W),Z0(this.IV),this.flags=V|F0.KEYED_HASH}else if(J){let W=Z$(Z),Y=new cV({dkLen:32},F0.DERIVE_KEY_CONTEXT).update(W).digest();this.IV=V$(Y),Z0(this.IV),this.flags=V|F0.DERIVE_KEY_MATERIAL}else this.IV=w0.slice(),this.flags=V;this.state=this.IV.slice(),this.bufferOut=ZZ(this.bufferOut32)}get(){return[]}set(){}b2Compress($,V,Q,Z=0){let{state:J,pos:W}=this,{h:Y,l:X}=lV(BigInt($),!0),{v0:G,v1:K,v2:I,v3:R,v4:N,v5:U,v6:M,v7:O,v8:H,v9:C,v10:P,v11:T,v12:q,v13:D,v14:S,v15:B}=nV(zZ,Z,Q,7,J[0],J[1],J[2],J[3],J[4],J[5],J[6],J[7],w0[0],w0[1],w0[2],w0[3],Y,X,W,V);J[0]=G^H,J[1]=K^C,J[2]=I^P,J[3]=R^T,J[4]=N^q,J[5]=U^D,J[6]=M^S,J[7]=O^B}compress($,V=0,Q=!1){let Z=this.flags;if(!this.chunkPos)Z|=F0.CHUNK_START;if(this.chunkPos===15||Q)Z|=F0.CHUNK_END;if(!Q)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,Z,$,V),this.chunkPos+=1,this.chunkPos===16||Q){let J=this.state;this.state=this.IV.slice();for(let W,Y=this.chunksDone+1;Q||!(Y&1);Y>>=1){if(!(W=this.stack.pop()))break;this.buffer32.set(W,0),this.buffer32.set(J,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|F0.PARENT,this.buffer32,0),J=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(J)}this.pos=0}_cloneInto($){$=super._cloneInto($);let{IV:V,flags:Q,state:Z,chunkPos:J,posOut:W,chunkOut:Y,stack:X,chunksDone:G}=this;return $.state.set(Z.slice()),$.stack=X.map((K)=>Uint32Array.from(K)),$.IV.set(V),$.flags=Q,$.chunkPos=J,$.chunksDone=G,$.posOut=W,$.chunkOut=Y,$.enableXOF=this.enableXOF,$.bufferOut32.set(this.bufferOut32),$}destroy(){this.destroyed=!0,Q$(this.state,this.buffer32,this.IV,this.bufferOut32),Q$(...this.stack)}b2CompressOut(){let{state:$,pos:V,flags:Q,buffer32:Z,bufferOut32:J}=this,{h:W,l:Y}=lV(BigInt(this.chunkOut++));Z0(Z);let{v0:X,v1:G,v2:K,v3:I,v4:R,v5:N,v6:U,v7:M,v8:O,v9:H,v10:C,v11:P,v12:T,v13:q,v14:D,v15:S}=nV(zZ,0,Z,7,$[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],w0[0],w0[1],w0[2],w0[3],Y,W,V,Q);J[0]=X^O,J[1]=G^H,J[2]=K^C,J[3]=I^P,J[4]=R^T,J[5]=N^q,J[6]=U^D,J[7]=M^S,J[8]=$[0]^O,J[9]=$[1]^H,J[10]=$[2]^C,J[11]=$[3]^P,J[12]=$[4]^T,J[13]=$[5]^q,J[14]=$[6]^D,J[15]=$[7]^S,Z0(Z),Z0(J),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,Q$(this.buffer.subarray(this.pos));let $=this.flags|F0.ROOT;if(this.stack.length)$|=F0.PARENT,Z0(this.buffer32),this.compress(this.buffer32,0,!0),Z0(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else $|=(!this.chunkPos?F0.CHUNK_START:0)|F0.CHUNK_END;this.flags=$,this.b2CompressOut()}writeInto($){F$(this,!1),g0($),this.finish();let{blockLen:V,bufferOut:Q}=this;for(let Z=0,J=$.length;Z<J;){if(this.posOut>=V)this.b2CompressOut();let W=Math.min(V-this.posOut,J-Z);$.set(Q.subarray(this.posOut,this.posOut+W),Z),this.posOut+=W,Z+=W}return $}xofInto($){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto($)}xof($){return U$($),this.xofInto(new Uint8Array($))}digestInto($){if(d$($,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=XZ(($)=>new cV($));var dV=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function RZ($){let V=new Uint8Array(dV.length+32);return V.set(dV),V.set($.subarray(0,32),dV.length),V}function NZ($){return typeof $==="string"?new TextEncoder().encode($):$}function J$($){let V=new ArrayBuffer($.byteLength);return new Uint8Array(V).set($),V}class rV{verifyKeys=new Map;signKeys=new Map;async genRandomBytes($){return n$($)}async gen256BitSecureRandomSeed(){return n$(32)}async encryptXSalsa20Poly1305Combined($,V){let Q=n$(24),J=bV(V,Q).encrypt($);return new Uint8Array([...Q,...J])}async decryptXSalsa20Poly1305Combined($,V){let Q=$.slice(0,24),Z=$.slice(24);return bV(V,Q).decrypt(Z)}async deriveEd25519KeyPair($){let V=$,Q=RZ(V),Z=await globalThis.crypto.subtle.importKey("pkcs8",J$(Q),{name:"Ed25519"},!0,["sign"]),J=await globalThis.crypto.subtle.exportKey("jwk",Z);if(typeof J.x!=="string")throw Error("Ed25519 JWK missing x");let W=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:J.x},{name:"Ed25519"},!0,["verify"]),Y=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",W)),X=new Uint8Array(64);return X.set(V,0),X.set(Y,32),this.signKeys.set(t(V),Z),this.verifyKeys.set(t(Y),W),{keyType:"ed25519",privateKey:X,publicKey:Y}}async importSignKey($){let V=$.subarray(0,32),Q=t(V),Z=this.signKeys.get(Q);if(Z)return Z;let J=RZ(V),W=await globalThis.crypto.subtle.importKey("pkcs8",J$(J),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Q,W),W}async importVerifyKey($){let V=t($),Q=this.verifyKeys.get(V);if(Q)return Q;let Z=await globalThis.crypto.subtle.importKey("raw",J$($),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set(V,Z),Z}async signEd25519($,V){let Q=NZ($),Z=await this.importSignKey(V),J=await globalThis.crypto.subtle.sign({name:"Ed25519"},Z,J$(Q));return new Uint8Array(J)}async checkSigEd25519($,V,Q){let Z=NZ(V);try{let J=await this.importVerifyKey(Q);return await globalThis.crypto.subtle.verify({name:"Ed25519"},J,J$($),J$(Z))}catch{return!1}}async blake3($){return IZ($)}}var pJ=new rV,r=pJ;import{useEffect as s$,useState as VQ}from"react";class oV{db;constructor($){this.db=$}async enq($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(G0,"readwrite"),Z=Q.objectStore(G0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let Y of V){let X=`${Y.host}:${Y.seq}`;Z.put(Y,X)}})}async deq($,V){let Q=[...V];if(Q.length===0)return;let Z=this.db.transaction(G0,"readwrite"),J=Z.objectStore(G0);return new Promise((W,Y)=>{Z.oncomplete=()=>W(),Z.onerror=()=>Y(Z.error);for(let X of Q){let G=`${$}:${X}`;J.delete(G)}})}async list(){let V=this.db.transaction(G0,"readonly").objectStore(G0);return new Promise((Q,Z)=>{let J=V.getAll();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async count(){let V=this.db.transaction(G0,"readonly").objectStore(G0);return new Promise((Q,Z)=>{let J=V.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let $=this.db.transaction(G0,"readwrite"),V=$.objectStore(G0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}function UZ($){return{label:$.label,handle:new URL($.handle),idx:$.idx,lastSeq:$.lastSeq||0,clockOffset:$.clockOffset,subscription:$.subscription}}function nJ($,V){let Q={...$};if(V.setLastSeq!==void 0)Q.lastSeq=V.setLastSeq;else if(V.lastSeq!==void 0){let Z=Q.lastSeq||0;if(V.lastSeq>Z)Q.lastSeq=V.lastSeq}return delete Q.numBags,delete Q.numDupes,Q}class aV{db;constructor($){this.db=$}async add($){return this.put({...$,lastSeq:0})}async put($){let V={...$,handle:$.handle.toString(),lastSeq:$.lastSeq??0},Q=this.db.transaction(J0,"readwrite"),Z=Q.objectStore(J0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error),Z.put(V)})}async touch($,V){return this.recordStats($,{lastSeq:V})}async recordStats($,V){let Q=this.db.transaction(J0,"readwrite"),Z=Q.objectStore(J0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);let Y=Z.get($);Y.onsuccess=()=>{let X=Y.result;if(!X)return;Z.put(nJ(X,V))}})}async get($){let Q=this.db.transaction(J0,"readonly").objectStore(J0);return new Promise((Z,J)=>{let W=Q.get($);W.onsuccess=()=>{let Y=W.result;if(!Y)Z(void 0);else Z(UZ(Y))},W.onerror=()=>J(W.error)})}async set($,V){let Q=await this.get($);if(!Q)return 13;try{return await this.put({...Q,...V}),0}catch{return 18}}async del($){let V=this.db.transaction(J0,"readwrite"),Q=V.objectStore(J0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),Q.delete($)})}async list(){let V=this.db.transaction(J0,"readonly").objectStore(J0);return new Promise((Q,Z)=>{let J=V.getAll();J.onsuccess=()=>{let W=J.result;Q(W.map(UZ))},J.onerror=()=>Z(J.error)})}async wipe(){let $=this.db.transaction(J0,"readwrite"),V=$.objectStore(J0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}class sV{crypto;db;constructor($,V){this.crypto=V;this.db=$}async add($){let V=this.db.transaction(h,"readwrite"),Q=V.objectStore(h);return new Promise((Z)=>{if($.length===0){Z([]);return}let J=Array($.length).fill(0);V.oncomplete=()=>Z(J),V.onerror=()=>{for(let W=0;W<J.length;W++)J[W]=18;Z(J)};for(let W=0;W<$.length;W++){let{key:Y,data:X}=$[W],G=L(Y),K=Q.put(X,G);K.onerror=(I)=>{I.preventDefault(),J[W]=18}}})}async del($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(h,"readwrite"),Z=Q.objectStore(h);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let Y of V){let X=L(Y);Z.delete(X)}})}async get($){let Q=this.db.transaction(h,"readonly").objectStore(h);return new Promise((Z,J)=>{let W=L($),Y=Q.get(W);Y.onsuccess=async()=>{let X=Y.result;if(X)Z(await S0($,X,this.crypto));else Z(void 0)},Y.onerror=()=>J(Y.error)})}async has($){return await this.get($)!==void 0}async list($){let V=$?.apld,Q=$?.body!==!1,J=this.db.transaction(h,"readonly").objectStore(h);return new Promise((W,Y)=>{let X=[],G=V===void 0?J.openCursor():J.index(M$).openCursor(IDBKeyRange.only(V));G.onsuccess=(K)=>{let I=K.target.result;if(I){let R=V===void 0?I.key:I.primaryKey,N=I.value;X.push({hash:Q0(R),data:N}),I.continue()}else Promise.all(X.map(({hash:R,data:N})=>S0(R,N,this.crypto,{body:Q}))).then(W).catch(Y)},G.onerror=()=>Y(G.error)})}async count($){let Q=this.db.transaction(h,"readonly").objectStore(h);return new Promise((Z,J)=>{let W=$===void 0?Q.count():Q.index(M$).count(IDBKeyRange.only($));W.onsuccess=()=>Z(W.result),W.onerror=()=>J(W.error)})}async listKeys(){let V=this.db.transaction(h,"readonly").objectStore(h);return new Promise((Q,Z)=>{let J=[],W=V.openKeyCursor();W.onsuccess=(Y)=>{let X=Y.target.result;if(X)J.push(Q0(X.key)),X.continue();else Q(J)},W.onerror=()=>Z(W.error)})}async last($){let Q=this.db.transaction(h,"readonly").objectStore(h);return new Promise((Z,J)=>{let W,Y=Q.openCursor();Y.onsuccess=async(X)=>{let G=X.target.result;if(G){let{key:K,value:I}=G;if(e($,I.eid)){if(!W||(I.ctr??0)>(W.data.ctr??0)||(I.ctr??0)===(W.data.ctr??0)&&(I.off??0)>(W.data.off??0))W={key:K,data:I}}G.continue()}else if(W){let K=Q0(W.key);Z(await S0(K,W.data,this.crypto))}else Z(void 0)},Y.onerror=()=>J(Y.error)})}async markApplied($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(h,"readwrite"),Z=Q.objectStore(h);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let Y of V){let X=L(Y),G=Z.get(X);G.onsuccess=()=>{let K=G.result;if(!K)return;m0(K,x0),Z.put(K,X)},G.onerror=(K)=>{K.preventDefault()}}})}async markFailed($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(h,"readwrite"),Z=Q.objectStore(h);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let{key:Y,err:X}of V){let G=L(Y),K=Z.get(G);K.onsuccess=()=>{let I=K.result;if(!I)return;m0(I,N0,X),Z.put(I,G)},K.onerror=(I)=>{I.preventDefault()}}})}async wipe(){let $=this.db.transaction(h,"readwrite"),V=$.objectStore(h);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}class I0{#V;#$;constructor($,V){this.#V=$,this.#$=V}deriveCipher($,V){let Q=$.slice(),Z=(Y)=>this.#Q(Q,Y),J=(Y)=>this.#Z(Q,Y);return{encrypt:Object.freeze({encrypt:Z}),decrypt:Object.freeze({decrypt:J}),both:Object.freeze({encrypt:Z,decrypt:J})}[V]}async deriveIdentity($,V=0){let Q=$,Z=V,J=await this.#W(Q,Z);return Object.freeze({publicKey:J.publicKey,sign:(W)=>this.#X(Q,Z,W),kdmFor:(W)=>this.#G(Q,Z,W)})}async#Q($,V){let Q=await this.#J($);return this.#$.encryptXSalsa20Poly1305Combined(V,Q)}async#Z($,V){let Q=await this.#J($);return this.#$.decryptXSalsa20Poly1305Combined(V,Q)}async#J($){return this.#$.blake3(j$(this.#V,$))}async#Y($,V){let Q=new TextEncoder().encode($),Z=new Uint8Array(8);return new DataView(Z.buffer).setBigUint64(0,BigInt(V),!1),await this.#J(j$(Q,Z))}async#W($,V){let Q=await this.#Y($,V);return this.#$.deriveEd25519KeyPair(Q)}async#X($,V,Q){let Z=await this.#W($,V);return this.#$.signEd25519(Q,Z.privateKey)}async#G($,V,Q){let Z=await this.#W($,V),J=j$(Z.privateKey,Q);return(await this.#$.blake3(J)).slice(0,_0)}}class tV{enclave;db;constructor($){this.db=$}async save($,V){if(V?.persist!==!0)return this.enclave=new I0($,r),this.enclave;let Q=t($),Z=this.db.transaction(T0,"readwrite"),J=Z.objectStore(T0);return new Promise((W,Y)=>{Z.oncomplete=()=>{this.enclave=new I0($,r),W(this.enclave)},Z.onerror=()=>Y(Z.error),J.put(Q,"seed")})}async load(){if(this.enclave)return this.enclave;let V=this.db.transaction(T0,"readonly").objectStore(T0);return new Promise((Q,Z)=>{let J=V.get("seed");J.onsuccess=()=>{let W=J.result;if(!W)Q(void 0);else{let Y=L0(W);this.enclave=new I0(Y,r),Q(this.enclave)}},J.onerror=()=>Z(J.error)})}async wipe(){this.enclave=void 0;let $=this.db.transaction(T0,"readwrite"),V=$.objectStore(T0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.put("","seed"),V.delete("seed")})}}class eV{db;constructor($){this.db=$}async enq($,V){let Q=[...V];if(Q.length===0)return;let Z=this.db.transaction(K0,"readwrite"),J=Z.objectStore(K0);return new Promise((W,Y)=>{Z.oncomplete=()=>W(),Z.onerror=()=>Y(Z.error);for(let X of Q){let G=t(X);J.put({host:$,hash:G})}})}async deq($,V){let Q=[...V];if(Q.length===0)return;let Z=this.db.transaction(K0,"readwrite"),J=Z.objectStore(K0);return new Promise((W,Y)=>{Z.oncomplete=()=>W(),Z.onerror=()=>Y(Z.error);for(let X of Q){let G=t(X);J.delete([$,G])}})}async list($){let Q=this.db.transaction(K0,"readonly").objectStore(K0);return new Promise((Z,J)=>{let W=Q.getAll();W.onsuccess=()=>{let X=W.result.filter((G)=>G.host===$).map((G)=>G.hash);Z(X.map((G)=>L0(G)))},W.onerror=()=>J(W.error)})}async count(){let V=this.db.transaction(K0,"readonly").objectStore(K0);return new Promise((Q,Z)=>{let J=V.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let $=this.db.transaction(K0,"readwrite"),V=$.objectStore(K0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}var T0="seedMeta",J0="hosts",K0="uploadQueue",G0="downloadQueue",h="messages",M$="apld",FZ=3,OZ="diplomatic-store-db";class $Q{seed;hosts;uploads;downloads;messages;db;constructor($,V){this.db=$,this.seed=new tV($),this.hosts=new aV($),this.uploads=new eV($),this.downloads=new oV($),this.messages=new sV($,V)}async wipe(){await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function cJ(){return new Promise(($,V)=>{let Q=indexedDB.open(OZ,FZ);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!Z.objectStoreNames.contains(T0))Z.createObjectStore(T0);if(!Z.objectStoreNames.contains(J0))Z.createObjectStore(J0,{keyPath:"label"});if(!Z.objectStoreNames.contains(K0))Z.createObjectStore(K0,{keyPath:["host","hash"]});if(!Z.objectStoreNames.contains(G0))Z.createObjectStore(G0);let W;if(!Z.objectStoreNames.contains(h))W=Z.createObjectStore(h);else{if(!J)throw Error("missing upgrade transaction for messages store");W=J.objectStore(h)}if(!W.indexNames.contains(M$))W.createIndex(M$,"apld",{unique:!1})},Q.onblocked=()=>{console.warn(`[DIPLOMATIC] protocol store IDB upgrade blocked (${OZ} → v${FZ}); waiting for other connections to close`)},Q.onsuccess=()=>{let Z=Q.result;Z.onversionchange=()=>{Z.close()},$(Z)},Q.onerror=()=>V(Q.error??Error("protocol store IndexedDB open failed"))})}async function o$($){let V=await cJ();if(typeof navigator<"u"&&navigator.storage?.persist)try{await Promise.race([navigator.storage.persist(),new Promise((Q)=>{setTimeout(()=>Q(!1),2000)})])}catch{}return new $Q(V,$)}function MZ($){if(!$||typeof $!=="object")return!1;if(!("kind"in $))return!1;return typeof $.kind==="string"}function HZ($){if(typeof $!=="number")return;return $}function qZ($){if(!$||typeof $!=="object")return;if(!("hasSeed"in $)||!("hasHost"in $)||!("connected"in $))return;if(typeof $.hasSeed!=="boolean"||typeof $.hasHost!=="boolean"||typeof $.connected!=="boolean")return;return{hasSeed:$.hasSeed,hasHost:$.hasHost,connected:$.connected}}function dJ($){if(!$||typeof $!=="object")return;if(!("phase"in $))return;let V=rJ($.phase);if(V===void 0)return;let Q={phase:V};if("host"in $&&typeof $.host==="string")Q.host=$.host;if("done"in $&&typeof $.done==="number")Q.done=$.done;if("total"in $&&typeof $.total==="number")Q.total=$.total;if("bytesDone"in $&&typeof $.bytesDone==="number")Q.bytesDone=$.bytesDone;if("bytesTotal"in $&&typeof $.bytesTotal==="number")Q.bytesTotal=$.bytesTotal;return Q}function rJ($){if($==="peek"||$==="pull"||$==="open"||$==="exec"||$==="push"||$==="import"||$==="idle"||$==="apply")return $==="apply"?"exec":$;return}function PZ($){if(!$||typeof $!=="object")return;if(!("numUploads"in $)||!("numDownloads"in $))return;if(typeof $.numUploads!=="number"||typeof $.numDownloads!=="number")return;let V={phase:"idle"};if("progress"in $){let Q=dJ($.progress);if(Q===void 0)return;V=Q}return{numUploads:$.numUploads,numDownloads:$.numDownloads,progress:V}}var z0="[DIPLOMATIC]";class q${worker;state;store;local;nextId=1;pending=new Map;ready;resolveReady;rejectReady;scheduledSync;cachedClientState={hasSeed:!1,hasHost:!1,connected:!1};cachedXferState={numUploads:0,numDownloads:0,progress:E0};clientState;xferState;constructor($,V,Q,Z,J){this.worker=$,this.state=V,this.store=Q,this.clientState=new R0(async()=>this.cachedClientState),this.xferState=new R0(async()=>this.cachedXferState),this.scheduledSync=new N$(J,async()=>{try{await this.request({id:this.allocId(),op:"sync"})}catch(W){console.error(`${z0} worker sync after local write failed`,W)}}),this.local=new B0(Z,V,Q,()=>{throw Error(`${z0} local writer has no transport (use worker for network)`)},r,!0,void 0,void 0,()=>{this.scheduledSync.schedule()}),this.local.xferState.listen((W)=>{this.cachedXferState={numUploads:W.numUploads,numDownloads:W.numDownloads,progress:this.cachedXferState.progress},this.xferState.emit()}),this.ready=new Promise((W,Y)=>{this.resolveReady=W,this.rejectReady=Y}),this.worker.onmessage=(W)=>{this.onMessage(W.data)},this.worker.onerror=(W)=>{console.error(`${z0} worker error`,W),this.failReady(Error(`${z0} worker failed to load`))},this.worker.onmessageerror=()=>{this.failReady(Error(`${z0} worker message error`))}}failReady($){let V=this.rejectReady;if(this.rejectReady=void 0,this.resolveReady=void 0,V)V($)}async flushScheduledSync(){await this.scheduledSync.flush()}static async connect($,V,Q){let Z=Q.clock??new M0,J=Q.syncDebounceMs??i$,W=new q$(Q.worker,$,V,Z,J),Y=Q.readyTimeoutMs??15000,X;try{let G=W.probeReady();if(await Promise.race([W.ready,G,new Promise((K,I)=>{X=setTimeout(()=>{I(Error(`${z0} worker ready timeout after ${Y}ms`))},Y)})]),X!==void 0)clearTimeout(X),X=void 0;G.catch(()=>{}),await W.hydrateStateFromStore(V),await W.pullRemoteState()}catch(G){throw W.terminate(),G}finally{if(X!==void 0)clearTimeout(X)}return W}async hydrateStateFromStore($){let V=await $.seed.load(),Q=await $.hosts.list();this.cachedClientState={hasSeed:V!==void 0,hasHost:Array.from(Q).length>0,connected:!1};let Z=await $.uploads.count(),J=await $.downloads.count();this.cachedXferState={numUploads:Z,numDownloads:J,progress:E0}}async pullRemoteState(){let $=await this.request({id:this.allocId(),op:"getClientState"}),V=qZ($);if(V!==void 0)this.cachedClientState=V;let Q=await this.request({id:this.allocId(),op:"getXferState"}),Z=PZ(Q);if(Z!==void 0)this.cachedXferState=Z}markReady(){let $=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,$)$()}probeReady(){return new Promise(($,V)=>{let Q=this.allocId();this.pending.set(Q,{resolve:(Z)=>{if(Z==="pong"){this.markReady(),$();return}V(Error(`${z0} worker probe ping failed`))},reject:V}),this.worker.postMessage({id:Q,op:"ping"})})}async ping(){if(await this.ready,await this.request({id:this.allocId(),op:"ping"})!=="pong")throw Error(`${z0} worker ping failed`)}terminate(){this.scheduledSync.cancel(),this.worker.terminate();for(let[,$]of this.pending)$.reject(Error(`${z0} worker terminated`));this.pending.clear()}onMessage($){if(!MZ($))return;let V=$;switch(V.kind){case"ready":{this.markReady();return}case"initError":{this.failReady(Error(`${z0} worker init failed: ${V.message}`));return}case"clientState":{this.cachedClientState=V.state,this.clientState.emit();return}case"xferState":{this.cachedXferState=V.state,this.xferState.emit();return}case"dirty":{this.state.refresh(V.eids.map(aJ));return}case"wiped":{this.state.clear();return}case"reply":{let Q=this.pending.get(V.id);if(!Q)return;if(this.pending.delete(V.id),V.ok)Q.resolve(V.result);else Q.reject(new H$(V.status));return}default:return}}allocId(){let $=this.nextId;return this.nextId+=1,$}request($,V){return new Promise((Q,Z)=>{if(this.pending.set($.id,{resolve:Q,reject:Z}),V&&V.length>0)this.worker.postMessage($,V);else this.worker.postMessage($)})}async requestStatus($,V){try{let Q=await this.request($,V),Z=HZ(Q);if(Z!==void 0)return Z;return 0}catch(Q){if(Q instanceof H$)return Q.status;return 12}}serializeHost($){return{handle:$.handle.href,label:$.label,idx:$.idx??0}}async setSeed($,V){await this.ready,await this.local.setSeed($,V),this.cachedClientState={...this.cachedClientState,hasSeed:!0},this.clientState.emit();let Q=$.slice();await this.request({id:this.allocId(),op:"setSeed",seed:Q,persist:V?.persist},[Q.buffer])}async link($,V=!0){await this.ready,await this.local.link($,!1),await this.request({id:this.allocId(),op:"link",host:this.serializeHost($),connect:V})}async unlink($){await this.ready,await this.local.unlink($),await this.request({id:this.allocId(),op:"unlink",label:$})}async hosts(){return await this.ready,this.local.hosts()}async connect($=!0,V=!0){await this.ready,await this.request({id:this.allocId(),op:"connect",listen:$,sync:V})}async disconnect(){await this.ready,await this.request({id:this.allocId(),op:"disconnect"})}async insertRaw($){return await this.ready,this.local.insertRaw($)}async updateRaw($,V,Q){return await this.ready,this.local.updateRaw($,V,Q)}async insert($){return await this.ready,this.local.insert($)}async update($){return await this.ready,this.local.update($)}async delete($){return await this.ready,this.local.delete($)}async genEID($){return await this.ready,this.local.genEID($)}async sync(){return await this.ready,this.requestStatus({id:this.allocId(),op:"sync"})}async rebuild($){return await this.ready,this.scheduledSync.cancel(),await this.scheduledSync.flush(),this.requestStatus({id:this.allocId(),op:"rebuild",checkHost:$?.checkHost})}async listMsgs($){return await this.ready,this.local.listMsgs($)}async countMsgs($){return await this.ready,this.local.countMsgs($)}async reconcile($,V){await this.ready;try{let Q=await this.request({id:this.allocId(),op:"reconcile",hostLabel:$,pull:V?.pull,push:V?.push,sync:V?.sync});if(!oJ(Q))return z(12);return F(Q)}catch(Q){if(Q instanceof H$&&Q.status!==0)return z(Q.status);return z(12)}}async msgcheck(){await this.ready;let $=await this.request({id:this.allocId(),op:"msgcheck"});if(!($ instanceof Uint8Array))throw Error(`${z0} msgcheck: expected Uint8Array`);return $}async entcheck(){await this.ready;let $=await this.request({id:this.allocId(),op:"entcheck"});if(!($ instanceof Uint8Array))throw Error(`${z0} entcheck: expected Uint8Array`);return $}async wipe($){await this.ready,await this.local.wipe($),await this.request({id:this.allocId(),op:"wipe",msgs:$?.msgs,ents:$?.ents,meta:$?.meta,seed:$?.seed}),await this.hydrateStateFromStore(this.store),this.clientState.emit(),this.xferState.emit()}async import($){await this.ready;let V=new Uint8Array(await $.arrayBuffer());return this.requestStatus({id:this.allocId(),op:"import",bytes:V},[V.buffer])}async export($,V){await this.ready;try{let Q=await this.request({id:this.allocId(),op:"export"});if(!(Q instanceof Uint8Array))return 12;let Z=new Blob([Q.slice()]);return u$(Z,$),0}catch(Q){if(Q instanceof H$)return Q.status;return 12}}}class H$ extends Error{status;constructor($){super(`WorkerReplyError: ${_[$]}`);this.status=$;this.name="WorkerReplyError"}}function oJ($){if(!$||typeof $!=="object")return!1;let V=$;return V.msgcheck instanceof Uint8Array&&V.msgcheck.length===32&&typeof V.numBags==="number"&&typeof V.numDupes==="number"}function aJ($){return $}var v0="[DIPLOMATIC]";async function a$($){let V=$.clock??new M0;if($.worker!==void 0&&sJ($)!==void 0)throw Error(`${v0} worker path requires IndexedDB on both sides; do not pass store (got a custom store)`);if($.worker===void 0){console.info(`${v0} sync on main thread `+"(no worker — app did not request a worker)");let J=await CZ($.store);return tJ(V,$.state,J)}if(typeof Worker>"u")throw Error(`${v0} worker was provided but Worker API is unavailable`);let Q=await CZ(void 0);console.info(`${v0} attaching app-provided sync worker…`);let Z=await q$.connect($.state,Q,{worker:$.worker,readyTimeoutMs:$.readyTimeoutMs,clock:V,syncDebounceMs:$.syncDebounceMs});return await Z.ping(),console.info(`${v0} sync worker active (network + EntDB writes off main; local mutates on main; dirty signals only)`),{client:Z,mode:"worker",dispose:()=>{console.info(`${v0} terminating sync worker`),Z.terminate()}}}function sJ($){if("store"in $)return $.store;return}async function tJ($,V,Q){let Z=new B0($,V,Q,f$,r);return{client:Z,mode:"main",dispose:()=>{Z.disconnect()}}}async function CZ($){if($!==void 0)return $;if(typeof indexedDB>"u")throw Error(`${v0} IndexedDB is unavailable; pass store explicitly (e.g. new MemoryStore(crypto))`);return o$(r)}function eJ($){let[V,Q]=VQ();return s$(()=>{async function Z(){let W=await $.clientState.get();Q(W)}let J=$.clientState.listen(Z);return Z(),()=>{J()}},[$]),V}function $W($){let[V,Q]=VQ();return s$(()=>{async function Z(){let W=await $.xferState.get();Q(W)}let J=$.xferState.listen(Z);return Z(),()=>{J()}},[$]),V}function VW($){s$(()=>{async function V(){try{await $.connect(),await $.sync()}catch(W){console.error("reconnectAndSync failed",W)}}function Q(){V()}function Z(){if(typeof document<"u"&&document.visibilityState==="visible")V()}function J(){V()}if(globalThis.addEventListener("online",Q),typeof document<"u")document.addEventListener("visibilitychange",Z);return globalThis.addEventListener("focus",J),globalThis.addEventListener("pageshow",J),()=>{if(globalThis.removeEventListener("online",Q),typeof document<"u")document.removeEventListener("visibilitychange",Z);globalThis.removeEventListener("focus",J),globalThis.removeEventListener("pageshow",J)}},[$])}function QW($={}){let V=$.clock??new M0,{seed:Q,host:Z,readyTimeoutMs:J}=$,W=$.worker,Y="store"in $?$.store:void 0,[X,G]=VQ({stateMgr:qV});return s$(()=>{let K=!1,I;return(async()=>{let R=await DV();if(K)return;let N=g$(R),U=W!==void 0?await a$({state:N,clock:V,worker:W,readyTimeoutMs:J}):await a$({state:N,clock:V,store:Y,readyTimeoutMs:J});if(K){U.dispose();return}I=U.dispose;let{client:M,mode:O}=U;if(Q)await M.setSeed(Q);if(Z)await M.link(Z);if(K){I();return}G({client:M,entDB:R,stateMgr:N,mode:O,error:void 0})})().catch((R)=>{let N=R instanceof Error?R:Error(String(R));if(console.error("[DIPLOMATIC] useClient init failed",N),!K)G((U)=>({...U,client:void 0,error:N}))}),()=>{K=!0,I?.()}},[V,Q,Z,W,Y,J]),X}import{use as ZW,useEffect as wZ,useRef as JW,useState as WW}from"react";function TZ($,V,Q){let[Z,J]=WW();return wZ(()=>{async function W(){let Y=await Q();J(Y)}return W(),$.on(V,W),()=>{$.off(V,W)}},[$,V,Q]),Z}function YW($,V,Q){let Z=JW(Q());return wZ(()=>{async function J(){Z.current=Q()}return $.on(V,J),()=>{$.off(V,J)}},[$,V,Q]),ZW(Z.current)}function AZ($,V){return`${$}:${V}`}class QQ{queue=new Map;async enq($){for(let V of $){let Q=AZ(V.host,V.seq);this.queue.set(Q,V)}}async deq($,V){for(let Q of V){let Z=AZ($,Q);this.queue.delete(Z)}}async list(){let $=[];for(let V of this.queue.values())$.push(V);return $}async count(){return this.queue.size}async wipe(){this.queue.clear()}}function XW($,V){if(V.setLastSeq!==void 0)$.lastSeq=V.setLastSeq;else if(V.lastSeq!==void 0&&V.lastSeq>$.lastSeq)$.lastSeq=V.lastSeq}class ZQ{hosts=new Map;async add($){let V={...$,lastSeq:0};this.hosts.set($.label,V)}async touch($,V){await this.recordStats($,{lastSeq:V})}async recordStats($,V){let Q=this.hosts.get($);if(!Q)return;XW(Q,V),this.hosts.set($,{...Q})}async get($){return this.hosts.get($)}async set($,V){let Q=this.hosts.get($);if(!Q)return 13;return this.hosts.set($,{...Q,...V}),0}async del($){this.hosts.delete($)}async list(){return this.hosts.values()}async wipe(){this.hosts.clear()}}class JQ{crypto;messages=new Map;constructor($){this.crypto=$}async add($){let V=[];for(let{key:Q,data:Z}of $)this.messages.set(L(Q),Z),V.push(0);return V}async del($){for(let V of $)this.messages.delete(L(V))}async get($){let V=this.messages.get(L($));if(V)return await S0($,V,this.crypto);return}async has($){return this.messages.has(L($))}async list($){let V=$?.apld,Q=$?.body!==!1,Z=[];for(let[J,W]of this.messages){if(V!==void 0&&$$(W.apld)!==V)continue;let Y=Q0(J);Z.push(await S0(Y,W,this.crypto,{body:Q}))}return Z}async count($){if($===void 0)return this.messages.size;let V=0;for(let Q of this.messages.values())if($$(Q.apld)===$)V++;return V}async listKeys(){let $=[];for(let V of this.messages.keys())$.push(Q0(V));return $}async last($){let V;for(let[Q,Z]of this.messages){if(e($,Z.eid)===!1)continue;let J=Q0(Q);if(V===void 0)V={hash:J,data:Z};else if((Z.ctr??0)>(V.data.ctr??0)||(Z.ctr??0)===(V.data.ctr??0)&&(Z.off??0)>(V.data.off??0))V={hash:J,data:Z}}if(V)return await S0(V.hash,V.data,this.crypto);return}async markApplied($){for(let V of $){let Q=this.messages.get(L(V));if(!Q)continue;m0(Q,x0)}}async markFailed($){for(let{key:V,err:Q}of $){let Z=this.messages.get(L(V));if(!Z)continue;m0(Z,N0,Q)}}async wipe(){this.messages.clear()}}class WQ{enclave;async save($,V){return this.enclave=new I0($,r),this.enclave}async load(){return this.enclave}async wipe(){this.enclave=void 0}}class YQ{queue=new Map;async enq($,V){let Q=this.queue.get($)||new Set;this.queue.set($,Q);for(let Z of V)Q.add(t(Z))}async deq($,V){let Q=this.queue.get($);if(Q)for(let Z of V)Q.delete(t(Z))}async list($){let V=this.queue.get($);if(!V)return[];let Q=[];for(let Z of V)Q.push(L0(Z));return Q}async count(){let $=0;for(let V of this.queue.values())$+=V.size;return $}async wipe(){this.queue.clear()}}class DZ{seed=new WQ;hosts=new ZQ;uploads=new YQ;downloads=new QQ;messages;constructor($){this.messages=new JQ($)}async wipe(){await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}class _Z{singletonType;latest;latestOff=-1;emitter=new A0;constructor($){this.singletonType=$}async apply($){for(let V of $){let Q=new k(V.eid),[Z,J]=Q.readStruct(o);if(J!==0)continue;let W=new g;W.writeVarString(this.singletonType);let Y=W.result();if(Z.id.length===Y.length&&Z.id.every((X,G)=>X===Y[G])){if(this.latest===void 0||V.off>this.latestOff)this.latestOff=V.off,this.latest=V.bod,this.emitter.emit(this.singletonType,null)}}return $.map(()=>0)}clear=async()=>{return this.latest=void 0,this.latestOff=-1,this.emitter.emit(this.singletonType,null),0};notify=($)=>{for(let V of $)if(V===this.singletonType)this.emitter.emit(this.singletonType,null)};refresh=async($)=>{this.notify([this.singletonType])};on=($,V)=>{this.emitter.addEventListener($,V)};off=($,V)=>{this.emitter.removeEventListener($,V)}}var XQ=32,t$=32;function P$($){let V=new Uint8Array($);return crypto.getRandomValues(V),V}function GQ($){let V=new Uint8Array($.byteLength);return V.set($),V}function jZ($){if($.byteLength!==XQ)throw Error(`largeBlob: seed must be ${XQ} bytes`);return $}function e$($){if($?.rpId!==void 0)return $.rpId;if(typeof location>"u")throw Error("largeBlob: rpId required outside browser");return location.hostname}function $V(){if(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")throw Error("largeBlob: WebAuthn unavailable")}function VV($){if($===null||$.type!=="public-key"||!("rawId"in $)||typeof $.getClientExtensionResults!=="function")throw Error("largeBlob: expected public-key credential");return $}function GW(){if(typeof navigator>"u")return!1;let $=navigator.userAgent;if(/Chrom(e|ium)|Edg\/|EdgiOS|OPR\/|Firefox|FxiOS|CriOS|Android/.test($))return!1;if(/Safari\//.test($))return!0;return navigator.vendor==="Apple Computer, Inc."&&/AppleWebKit/.test($)}async function KW(){if(typeof PublicKeyCredential>"u")return!1;if(GW())return!0;let $=PublicKeyCredential.getClientCapabilities;if(typeof $!=="function")return!0;let V=await $.call(PublicKeyCredential),Q="extension:largeBlob";if(Q in V)return V[Q]===!0;return!0}async function KQ($){$V();let V=$?.userName??"diplomatic-seed",Q={residentKey:"required",requireResidentKey:!0,userVerification:"required"};if($?.authenticatorAttachment!==void 0)Q.authenticatorAttachment=$.authenticatorAttachment;let Z=await navigator.credentials.create({publicKey:{challenge:P$(t$),rp:{id:e$($),name:$?.rpName??"DIPLOMATIC"},user:{id:P$(16),name:V,displayName:V},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-8},{type:"public-key",alg:-257}],authenticatorSelection:Q,extensions:{largeBlob:{support:"required"}}}}),J=VV(Z);if(J.getClientExtensionResults().largeBlob?.supported!==!0)throw Error("largeBlob: unsupported by authenticator. Seed storage needs a largeBlob-capable authenticator (iOS platform, many YubiKeys). macOS/Chrome/1Password passkeys often lack largeBlob. "+"An empty passkey may have been created — remove it in Passwords if listed.");return new Uint8Array(J.rawId)}async function QV($,V,Q){$V(),jZ(V);let Z=await navigator.credentials.get({publicKey:{challenge:P$(t$),rpId:e$(Q),allowCredentials:[{type:"public-key",id:GQ($)}],userVerification:"required",extensions:{largeBlob:{write:GQ(V)}}}});if(VV(Z).getClientExtensionResults().largeBlob?.written!==!0)throw Error("largeBlob: write not accepted")}async function LZ($,V){let Q=new Uint8Array(XQ);await QV($,Q,V)}async function xZ($,V){return(await SZ($,V)).seed}async function SZ($,V){$V();let Q=await navigator.credentials.get({publicKey:{challenge:P$(t$),rpId:e$(V),allowCredentials:[{type:"public-key",id:GQ($)}],userVerification:"required",extensions:{largeBlob:{read:!0}}}});return fZ(VV(Q))}async function zW($){$V();let V=await navigator.credentials.get({publicKey:{challenge:P$(t$),rpId:e$($),userVerification:"required",extensions:{largeBlob:{read:!0}}}});return fZ(VV(V))}function fZ($){let V=$.getClientExtensionResults().largeBlob?.blob;if(V===void 0)throw Error("largeBlob: missing blob (credential has no seed storage, or largeBlob did not sync)");let Q=new Uint8Array(V);if(Q.every((Z)=>Z===0))throw Error("largeBlob: seed was cleared");return{seed:jZ(Q),credId:new Uint8Array($.rawId)}}async function IW($,V){let Q=await KQ(V);return await QV(Q,$,V),Q}class EZ{#V;#$;#Q;#Z;constructor($){if(this.#Q=$?.rpId,this.#Z=$?.rpName,$?.credId!==void 0)this.#$=$.credId.slice()}get credId(){if(this.#$===void 0)return;return this.#$.slice()}setCredId($){this.#$=$===void 0?void 0:$.slice()}async save($,V){if(V?.persist!==!0)return this.#V=new I0($,r),this.#V;let Q={rpId:this.#Q,rpName:this.#Z},Z=this.#$;if(Z===void 0)Z=await KQ(Q),this.#$=Z;return await QV(Z,$,Q),this.#V=new I0($,r),this.#V}async load(){return this.#V}async unlock(){let $=this.#$;if($===void 0)throw Error("largeBlob: no credential id");let V=await xZ($,{rpId:this.#Q});return this.#V=new I0(V,r),this.#V}async wipe(){let $=this.#$;if($!==void 0)await LZ($,{rpId:this.#Q});this.#V=void 0,this.#$=void 0}}async function F9($,V){let Q=await o$(r),Z=new B0(new M0,$,Q,f$,r);return{client:Z,setSeed:async(W)=>{let Y=L0(W);await Q.seed.save(Y),await Q.hosts.add({handle:V,label:"host",idx:0}),await Z.connect()}}}export{QV as writeLargeBlobSeed,VW as useSyncOnResume,YW as useStateWatcherSuspense,TZ as useStateWatcher,$W as useClientXferState,eJ as useClientState,QW as useClient,IW as storeSeedLargeBlob,y$ as shouldEmitItemProgress,m0 as setApld,_V as revFromHead,I$ as revFromEntity,SZ as readLargeBlobUnlock,xZ as readLargeBlobSeed,o$ as openIDBStore,DV as openEntDB,a$ as openDiplomaticClient,qV as nullStateManager,wJ as nullEntDB,iQ as normalizeTags,KW as largeBlobCapable,CJ as isTombstone,LV as isTerminalApplyFailure,DJ as isPendingApply,u as isLiveEnt,AJ as isApldState,E0 as idleProgress,L0 as htob,f$ as hostHTTPTransport,F9 as genWebClient,WJ as genSingletonEID,g$ as entStateManager,mQ as encodeEntRev,o as eidCodec,zW as discoverLargeBlobSeed,e0 as defaultPeekProgressEvery,r as crypto,KQ as createLargeBlobCred,EQ as cmpBytes,LZ as clearLargeBlobSeed,d0 as checksumSet,K$ as checksumEntRevs,t as btoh,L as btob64,Q0 as b64tob,$$ as apldFromStored,q$ as WorkerClient,A0 as TypedEventEmitter,B0 as SyncClient,_ as Status,z$ as StateManager,_Z as SingletonStateManager,EZ as PasskeySeedStore,DZ as MemoryStore,$Q as IDBStore,FV as HTTPTransport,AV as EntIDB,k$ as EntDBMemory,g as Encoder,k as Decoder,M0 as Clock,R$ as CachedEntDB,H0 as APLD_PENDING,N0 as APLD_ERROR,x0 as APLD_APPLIED};
1
+ function zQ($){let V=$.length,Q=0,Z=0;while(Z<V){let J=$.charCodeAt(Z++);if((J&4294967168)===0){Q++;continue}else if((J&4294965248)===0)Q+=2;else{if(J>=55296&&J<=56319){if(Z<V){let W=$.charCodeAt(Z);if((W&64512)===56320)++Z,J=((J&1023)<<10)+(W&1023)+65536}}if((J&4294901760)===0)Q+=3;else Q+=4}}return Q}function kZ($,V,Q){let Z=$.length,J=Q,W=0;while(W<Z){let Y=$.charCodeAt(W++);if((Y&4294967168)===0){V[J++]=Y;continue}else if((Y&4294965248)===0)V[J++]=Y>>6&31|192;else{if(Y>=55296&&Y<=56319){if(W<Z){let X=$.charCodeAt(W);if((X&64512)===56320)++W,Y=((Y&1023)<<10)+(X&1023)+65536}}if((Y&4294901760)===0)V[J++]=Y>>12&15|224,V[J++]=Y>>6&63|128;else V[J++]=Y>>18&7|240,V[J++]=Y>>12&63|128,V[J++]=Y>>6&63|128}V[J++]=Y&63|128}}var gZ=new TextEncoder,vZ=50;function iZ($,V,Q){gZ.encodeInto($,V.subarray(Q))}function RQ($,V,Q){if($.length>vZ)iZ($,V,Q);else kZ($,V,Q)}var yZ=4096;function ZV($,V,Q){let Z=V,J=Z+Q,W=[],Y="";while(Z<J){let X=$[Z++];if((X&128)===0)W.push(X);else if((X&224)===192){let G=$[Z++]&63;W.push((X&31)<<6|G)}else if((X&240)===224){let G=$[Z++]&63,K=$[Z++]&63;W.push((X&31)<<12|G<<6|K)}else if((X&248)===240){let G=$[Z++]&63,K=$[Z++]&63,R=$[Z++]&63,I=(X&7)<<18|G<<12|K<<6|R;if(I>65535)I-=65536,W.push(I>>>10&1023|55296),I=56320|I&1023;W.push(I)}else W.push(X);if(W.length>=yZ)Y+=String.fromCharCode(...W),W.length=0}if(W.length>0)Y+=String.fromCharCode(...W);return Y}var uZ=new TextDecoder,bZ=200;function hZ($,V,Q){let Z=$.subarray(V,V+Q);return uZ.decode(Z)}function IQ($,V,Q){if(Q>bZ)return hZ($,V,Q);else return ZV($,V,Q)}class l0{type;data;constructor($,V){this.type=$,this.data=V}}class V0 extends Error{constructor($){super($);let V=Object.create(V0.prototype);Object.setPrototypeOf(this,V),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:V0.name})}}var p0=4294967295;function NQ($,V,Q){let Z=Q/4294967296,J=Q;$.setUint32(V,Z),$.setUint32(V+4,J)}function C$($,V,Q){let Z=Math.floor(Q/4294967296),J=Q;$.setUint32(V,Z),$.setUint32(V+4,J)}function w$($,V){let Q=$.getInt32(V),Z=$.getUint32(V+4);return Q*4294967296+Z}function UQ($,V){let Q=$.getUint32(V),Z=$.getUint32(V+4);return Q*4294967296+Z}var lZ=-1,pZ=4294967295,nZ=17179869183;function cZ({sec:$,nsec:V}){if($>=0&&V>=0&&$<=nZ)if(V===0&&$<=pZ){let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,$),Q}else{let Q=$/4294967296,Z=$&4294967295,J=new Uint8Array(8),W=new DataView(J.buffer);return W.setUint32(0,V<<2|Q&3),W.setUint32(4,Z),J}else{let Q=new Uint8Array(12),Z=new DataView(Q.buffer);return Z.setUint32(0,V),C$(Z,4,$),Q}}function dZ($){let V=$.getTime(),Q=Math.floor(V/1000),Z=(V-Q*1000)*1e6,J=Math.floor(Z/1e9);return{sec:Q+J,nsec:Z-J*1e9}}function rZ($){if($ instanceof Date){let V=dZ($);return cZ(V)}else return null}function oZ($){let V=new DataView($.buffer,$.byteOffset,$.byteLength);switch($.byteLength){case 4:{let Q=V.getUint32(0),Z=0;return{sec:Q,nsec:0}}case 8:{let Q=V.getUint32(0),Z=V.getUint32(4),J=(Q&3)*4294967296+Z,W=Q>>>2;return{sec:J,nsec:W}}case 12:{let Q=w$(V,4),Z=V.getUint32(0);return{sec:Q,nsec:Z}}default:throw new V0(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${$.length}`)}}function aZ($){let V=oZ($);return new Date(V.sec*1000+V.nsec/1e6)}var OQ={type:lZ,encode:rZ,decode:aZ};class n0{static defaultCodec=new n0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(OQ)}register({type:$,encode:V,decode:Q}){if($>=0)this.encoders[$]=V,this.decoders[$]=Q;else{let Z=-1-$;this.builtInEncoders[Z]=V,this.builtInDecoders[Z]=Q}}tryToEncode($,V){for(let Q=0;Q<this.builtInEncoders.length;Q++){let Z=this.builtInEncoders[Q];if(Z!=null){let J=Z($,V);if(J!=null){let W=-1-Q;return new l0(W,J)}}}for(let Q=0;Q<this.encoders.length;Q++){let Z=this.encoders[Q];if(Z!=null){let J=Z($,V);if(J!=null)return new l0(Q,J)}}if($ instanceof l0)return $;return null}decode($,V,Q){let Z=V<0?this.builtInDecoders[-1-V]:this.decoders[V];if(Z)return Z($,V,Q);else return new l0(V,$)}}function sZ($){return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer}function W$($){if($ instanceof Uint8Array)return $;else if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);else if(sZ($))return new Uint8Array($);else return Uint8Array.from($)}var tZ=100,eZ=2048;class T${extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??n0.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.maxDepth=$?.maxDepth??tZ,this.initialBufferSize=$?.initialBufferSize??eZ,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 T$({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($),Q=new Uint8Array(V),Z=new DataView(V);Q.set(this.bytes),this.view=Z,this.bytes=Q}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 Q=zQ($);this.ensureBufferSizeToWrite(5+Q),this.writeStringHeader(Q),RQ($,this.bytes,this.pos),this.pos+=Q}encodeObject($,V){let Q=this.extensionCodec.tryToEncode($,this.context);if(Q!=null)this.encodeExtension(Q);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 Q=W$($);this.writeU8a(Q)}encodeArray($,V){let Q=$.length;if(Q<16)this.writeU8(144+Q);else if(Q<65536)this.writeU8(220),this.writeU16(Q);else if(Q<4294967296)this.writeU8(221),this.writeU32(Q);else throw Error(`Too large array: ${Q}`);for(let Z of $)this.doEncode(Z,V+1)}countWithoutUndefined($,V){let Q=0;for(let Z of V)if($[Z]!==void 0)Q++;return Q}encodeMap($,V){let Q=Object.keys($);if(this.sortKeys)Q.sort();let Z=this.ignoreUndefined?this.countWithoutUndefined($,Q):Q.length;if(Z<16)this.writeU8(128+Z);else if(Z<65536)this.writeU8(222),this.writeU16(Z);else if(Z<4294967296)this.writeU8(223),this.writeU32(Z);else throw Error(`Too large map object: ${Z}`);for(let J of Q){let W=$[J];if(!(this.ignoreUndefined&&W===void 0))this.encodeString(J),this.doEncode(W,V+1)}}encodeExtension($){if(typeof $.data==="function"){let Q=$.data(this.pos+6),Z=Q.length;if(Z>=4294967296)throw Error(`Too large extension object: ${Z}`);this.writeU8(201),this.writeU32(Z),this.writeI8($.type),this.writeU8a(Q);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),NQ(this.view,this.pos,$),this.pos+=8}writeI64($){this.ensureBufferSizeToWrite(8),C$(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 f0($,V){return new T$(V).encodeSharedRef($)}function A$($){return`${$<0?"-":""}0x${Math.abs($).toString(16).padStart(2,"0")}`}var $J=16,VJ=16;class JV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor($=$J,V=VJ){this.maxKeyLength=$,this.maxLengthPerKey=V,this.caches=[];for(let Q=0;Q<this.maxKeyLength;Q++)this.caches.push([])}canBeCached($){return $>0&&$<=this.maxKeyLength}find($,V,Q){let Z=this.caches[Q-1];$:for(let J of Z){let W=J.bytes;for(let Y=0;Y<Q;Y++)if(W[Y]!==$[V+Y])continue $;return J.str}return null}store($,V){let Q=this.caches[$.length-1],Z={bytes:$,str:V};if(Q.length>=this.maxLengthPerKey)Q[Math.random()*Q.length|0]=Z;else Q.push(Z)}decode($,V,Q){let Z=this.find($,V,Q);if(Z!=null)return this.hit++,Z;this.miss++;let J=ZV($,V,Q),W=Uint8Array.prototype.slice.call($,V,V+Q);return this.store(W,J),J}}var WV="array",X$="map_key",MQ="map_value",QJ=($)=>{if(typeof $==="string"||typeof $==="number")return $;throw new V0("The type of key must be string or number but "+typeof $)};class qQ{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState($){let V=this.getUninitializedStateFromPool();V.type=WV,V.position=0,V.size=$,V.array=Array($)}pushMapState($){let V=this.getUninitializedStateFromPool();V.type=X$,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===WV){let Q=$;Q.size=0,Q.array=void 0,Q.position=0,Q.type=void 0}if($.type===X$||$.type===MQ){let Q=$;Q.size=0,Q.map=void 0,Q.readCount=0,Q.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var Y$=-1,YV=new DataView(new ArrayBuffer(0)),ZJ=new Uint8Array(YV.buffer);try{YV.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 FQ=RangeError("Insufficient data"),JJ=new JV;class D${extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=YV;bytes=ZJ;headByte=Y$;stack=new qQ;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??n0.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.rawStrings=$?.rawStrings??!1,this.maxStrLength=$?.maxStrLength??p0,this.maxBinLength=$?.maxBinLength??p0,this.maxArrayLength=$?.maxArrayLength??p0,this.maxMapLength=$?.maxMapLength??p0,this.maxExtLength=$?.maxExtLength??p0,this.keyDecoder=$?.keyDecoder!==void 0?$.keyDecoder:JJ,this.mapKeyConverter=$?.mapKeyConverter??QJ}clone(){return new D$({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=Y$,this.stack.reset()}setBuffer($){let V=W$($);this.bytes=V,this.view=new DataView(V.buffer,V.byteOffset,V.byteLength),this.pos=0}appendBuffer($){if(this.headByte===Y$&&!this.hasRemaining(1))this.setBuffer($);else{let V=this.bytes.subarray(this.pos),Q=W$($),Z=new Uint8Array(V.length+Q.length);Z.set(V),Z.set(Q,V.length),this.setBuffer(Z)}}hasRemaining($){return this.view.byteLength-this.pos>=$}createExtraByteError($){let{view:V,pos:Q}=this;return RangeError(`Extra ${V.byteLength-Q} 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,Q;for await(let Y of $){if(V)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(Y);try{Q=this.doDecodeSync(),V=!0}catch(X){if(!(X instanceof RangeError))throw X}this.totalPos+=this.pos}if(V){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Q}let{headByte:Z,pos:J,totalPos:W}=this;throw RangeError(`Insufficient data in parsing ${A$(Z)} at ${W} (${J} 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 Q=V,Z=-1;for await(let J of $){if(V&&Z===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(J),Q)Z=this.readArraySize(),Q=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--Z===0)break}catch(W){if(!(W instanceof RangeError))throw W}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 Z=$-128;if(Z!==0){this.pushMapState(Z),this.complete();continue $}else V={}}else if($<160){let Z=$-144;if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else V=[]}else{let Z=$-160;V=this.decodeString(Z,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 Z=this.lookU8();V=this.decodeString(Z,1)}else if($===218){let Z=this.lookU16();V=this.decodeString(Z,2)}else if($===219){let Z=this.lookU32();V=this.decodeString(Z,4)}else if($===220){let Z=this.readU16();if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else V=[]}else if($===221){let Z=this.readU32();if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else V=[]}else if($===222){let Z=this.readU16();if(Z!==0){this.pushMapState(Z),this.complete();continue $}else V={}}else if($===223){let Z=this.readU32();if(Z!==0){this.pushMapState(Z),this.complete();continue $}else V={}}else if($===196){let Z=this.lookU8();V=this.decodeBinary(Z,1)}else if($===197){let Z=this.lookU16();V=this.decodeBinary(Z,2)}else if($===198){let Z=this.lookU32();V=this.decodeBinary(Z,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 Z=this.lookU8();V=this.decodeExtension(Z,1)}else if($===200){let Z=this.lookU16();V=this.decodeExtension(Z,2)}else if($===201){let Z=this.lookU32();V=this.decodeExtension(Z,4)}else throw new V0(`Unrecognized type byte: ${A$($)}`);this.complete();let Q=this.stack;while(Q.length>0){let Z=Q.top();if(Z.type===WV)if(Z.array[Z.position]=V,Z.position++,Z.position===Z.size)V=Z.array,Q.release(Z);else continue $;else if(Z.type===X$){if(V==="__proto__")throw new V0("The key __proto__ is not allowed");Z.key=this.mapKeyConverter(V),Z.type=MQ;continue $}else if(Z.map[Z.key]=V,Z.readCount++,Z.readCount===Z.size)V=Z.map,Q.release(Z);else{Z.key=null,Z.type=X$;continue $}}return V}}readHeadByte(){if(this.headByte===Y$)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=Y$}readArraySize(){let $=this.readHeadByte();switch($){case 220:return this.readU16();case 221:return this.readU32();default:if($<160)return $-144;else throw new V0(`Unrecognized array type byte: ${A$($)}`)}}pushMapState($){if($>this.maxMapLength)throw new V0(`Max length exceeded: map length (${$}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState($)}pushArrayState($){if($>this.maxArrayLength)throw new V0(`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 V0(`Max length exceeded: UTF-8 byte length (${$}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+V+$)throw FQ;let Q=this.pos+V,Z;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached($))Z=this.keyDecoder.decode(this.bytes,Q,$);else Z=IQ(this.bytes,Q,$);return this.pos+=V+$,Z}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===X$;return!1}decodeBinary($,V){if($>this.maxBinLength)throw new V0(`Max length exceeded: bin length (${$}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining($+V))throw FQ;let Q=this.pos+V,Z=this.bytes.subarray(Q,Q+$);return this.pos+=V+$,Z}decodeExtension($,V){if($>this.maxExtLength)throw new V0(`Max length exceeded: ext length (${$}) > maxExtLength (${this.maxExtLength})`);let Q=this.view.getInt8(this.pos+V),Z=this.decodeBinary($,V+1);return this.extensionCodec.decode(Z,Q,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let $=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 $=UQ(this.view,this.pos);return this.pos+=8,$}readI64(){let $=w$(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 XV($,V){return new D$(V).decode($)}class A0{listeners=new Map;addEventListener($,V){let Q=this.listeners.get($);if(!Q)Q=new Set,this.listeners.set($,Q);return Q.add(V),()=>{this.removeEventListener($,V)}}removeEventListener($,V){let Q=this.listeners.get($);if(Q){if(Q.delete(V),Q.size===0)this.listeners.delete($)}}emit($,V){let Q=this.listeners.get($);if(Q){let Z=Array.from(Q);for(let J of Z)J(V)}}emitAll($){let V=Array.from(this.listeners.keys());for(let Q of V)this.emit(Q,$)}}class I0{getter;static eventName="update";emitter;constructor($){this.getter=$;this.emitter=new A0}get=()=>this.getter();async emit(){let $=await this.getter();queueMicrotask(()=>this.emitter.emit(I0.eventName,$))}listen($){return this.emitter.addEventListener(I0.eventName,$),()=>{this.emitter.removeEventListener(I0.eventName,$)}}}var D0=64;var HQ=32,_0=8;var _$=32;var PQ=30000,CQ=512,_;((w)=>{w[w.Success=0]="Success";w[w.InvalidSignature=3]="InvalidSignature";w[w.ClockOutOfSync=4]="ClockOutOfSync";w[w.UserNotRegistered=5]="UserNotRegistered";w[w.ServerMisconfigured=6]="ServerMisconfigured";w[w.MissingBody=7]="MissingBody";w[w.ExtraBodyContent=8]="ExtraBodyContent";w[w.MissingParam=9]="MissingParam";w[w.InvalidParam=10]="InvalidParam";w[w.InvalidRequest=11]="InvalidRequest";w[w.InternalError=12]="InternalError";w[w.NotFound=13]="NotFound";w[w.InvalidMessage=14]="InvalidMessage";w[w.NoChange=15]="NoChange";w[w.DatabaseClosed=16]="DatabaseClosed";w[w.StorageError=17]="StorageError";w[w.DatabaseError=18]="DatabaseError";w[w.HashMismatch=19]="HashMismatch";w[w.DecryptionError=20]="DecryptionError";w[w.NotImplemented=21]="NotImplemented";w[w.MissingSeed=22]="MissingSeed";w[w.OutOfBounds=23]="OutOfBounds";w[w.HostError=24]="HostError";w[w.CommunicationError=25]="CommunicationError";w[w.VarLimitExceeded=26]="VarLimitExceeded";w[w.InvalidResponse=27]="InvalidResponse";w[w.ConnectionClosed=28]="ConnectionClosed"})(_||={});function O($){return[$,0]}function z($){return[void 0,$]}function WJ($){if($<0)console.info("N",$),console.trace();if(typeof $!=="bigint")$=BigInt($);if($<0n)return z(10);let V=[];while($>0n){let Q=Number($&0x7fn);if($>>=7n,$>0n)V.push(Q|128);else V.push(Q)}if(V.length===0)return O(new Uint8Array([0]));if(V.length>8)return z(26);return O(new Uint8Array(V))}function YJ($,V=0){let Q=0n,Z=0,J=V;while(!0){if(J>=$.length)return z(14);let W=$[J++];if(W===void 0)return z(14);if(Q|=BigInt(W&127)<<BigInt(Z),(W&128)===0){if(J-V>8)return z(26);return O({value:Q>0x1fffffffffffffn?Q:Number(Q),bytesRead:J-V})}if(Z+=7,Z>=56)return z(26)}}class k{data;pos=0;constructor($){this.data=$}static async fromResponse($){let V=await $.arrayBuffer(),Q=new Uint8Array(V);return new k(Q)}readBigInt(){if(this.pos+8>this.data.length)return z(7);let $=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,O($)}readDate(){let[$,V]=this.readVarInt();if(V!==0)return z(V);return O(new Date($))}readVarInt(){let[$,V]=YJ(this.data,this.pos);if(V!==0)return z(V);this.pos+=$.bytesRead;let Q=$.value;return O(typeof Q==="bigint"?Number(Q):Q)}readVarString(){let[$,V]=this.readVarInt();if(V!==0)return z(V);let[Q,Z]=this.readBytes($);if(Z!==0)return z(Z);let J=new TextDecoder().decode(Q);return O(J)}readBytes($){if($<0)return z(10);if(this.pos+$>this.data.length)return z(23);let V=this.data.slice(this.pos,this.pos+$);return this.pos+=$,O(V)}readVarBytes(){let[$,V]=this.readVarInt();if(V!==0)return z(V);return this.readBytes($)}readStruct($){return $.decode(this)}readStructs($){let V=[];while(!this.done()){let[Q,Z]=this.readStruct($);if(Z!==0)return z(Z);V.push(Q)}return O(V)}readBytesSeq($){let V=[];while(!this.done()){let[Q,Z]=this.readBytes($);if(Z!==0)return z(Z);V.push(Q)}return O(V)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class g{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,Q]=WJ($);if(Q!==0)return Q;return this.parts.push(V),0}writeVarString($){let V=new TextEncoder().encode($),Q=this.writeVarInt(V.length);if(Q!==0)return Q;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 Q of V){let Z=this.writeStruct($,Q);if(Z!==0)return Z}return 0}writeBytesSeq($){for(let V of $)this.writeBytes(V)}result(){let $=this.parts.reduce((Z,J)=>Z+J.length,0),V=new Uint8Array($),Q=0;for(let Z of this.parts)V.set(Z,Q),Q+=Z.length;return V}*scan(){for(let $ of this.parts)yield $}}async function GV($,V){let Q=new g,Z=Q.writeDate(V);if(Z!==0)return z(Z);let J=Q.result(),W=await $.sign(J);return O({pubKey:$.publicKey,sig:W,timestamp:V})}async function j0($,V,Q){let Z=Q.now().getTime(),J=$.timestamp.getTime();if(Math.abs(Z-J)>PQ)return 4;let Y=new g;Y.writeDate($.timestamp);let X=Y.result();if(!await V.checkSigEd25519($.sig,X,$.pubKey))return 3;return 0}var o={encode($,V){let Q=$.writeVarBytes(V.id);if(Q!==0)return Q;let Z=$.writeDate(V.ts);if(Z!==0)return Z;return 0},decode($){let[V,Q]=$.readVarBytes();if(Q!==0)return z(Q);let[Z,J]=$.readDate();if(J!==0)return z(J);return O({id:V,ts:Z})}};function c0($){let V=new g,Q=V.writeStruct(o,$);if(Q!==0)return z(Q);let Z=V.result();return O(Z)}async function XJ($){return c0({id:$,ts:new Date(0)})}var X0={encode($,V){let Q=$.writeVarBytes(V.eid);if(Q!==0)return Q;let Z=$.writeVarInt(V.off);if(Z!==0)return Z;let J=$.writeVarInt(V.ctr);if(J!==0)return J;let W=$.writeVarInt(V.len);if(W!==0)return W;if(V.hsh)$.writeBytes(V.hsh);return 0},decode($){let[V,Q]=$.readVarBytes();if(Q!==0)return z(Q);let Z=new k(V),[,J]=o.decode(Z);if(J!==0)return z(J);let[W,Y]=$.readVarInt();if(Y!==0)return z(Y);let[X,G]=$.readVarInt();if(G!==0)return z(G);let[K,R]=$.readVarInt();if(R!==0)return z(R);let I;if(K>0){let[N,U]=$.readBytes(_$);if(U!==0)return z(U);I=N}return O({eid:V,off:W,ctr:X,len:K,hsh:I})}};function t($){return Array.from($).map((Q)=>Q.toString(16).padStart(2,"0")).join("")}function L0($){if($.length%2!==0)throw Error("Invalid hex string");let V=new Uint8Array($.length/2);for(let Q=0;Q<$.length;Q+=2)V[Q/2]=Number.parseInt($.substr(Q,2),16);return V}function e($,V){if($===V)return!0;if($.byteLength!==V.byteLength)return!1;return $.every((Q,Z)=>Q===V[Z])}var L;if(typeof Uint8Array.prototype.toBase64==="function")L=($)=>$.toBase64();else L=($)=>btoa(String.fromCharCode(...$));var Q0;if(typeof Uint8Array.fromBase64==="function")Q0=($)=>Uint8Array.fromBase64($);else Q0=($)=>Uint8Array.from(atob($),(V)=>V.charCodeAt(0));function j$($,V){let Q=new Uint8Array($.length+V.length);return Q.set($,0),Q.set(V,$.length),Q}function wQ($,V,Q){return Q.checkSigEd25519($.sig,$.headCph,V)}async function TQ($,V,Q,Z){let J;if($.bod&&$.len>0)J=await Q.blake3($.bod);let W=new g,Y=X0.encode(W,{...$,hsh:J});if(Y!==0)return z(Y);let X=W.result(),G=await V.kdmFor(X),K=Z.deriveCipher(G,"encrypt"),R=await K.encrypt(X),I=$.bod?await K.encrypt($.bod):new Uint8Array(0),N=await V.sign(R);return O({sig:N,kdm:G,headCph:R,bodyCph:I})}async function KV($,V,Q,Z,J){let W=new k($),[Y,X]=X0.decode(W);if(X!==0)return z(14);let G;try{G=V&&V.length>0?await Q.decrypt(V):void 0}catch{return z(20)}let K=Y.hsh&&G===void 0,R=Y.hsh===void 0&&G!==void 0;if(K||R)return z(19);if(Y.hsh&&G){let N=await Z.blake3(G);if(!e(N,Y.hsh))return z(19)}let I=J??await Z.blake3($);return O({msgHead:Y,bod:G,headHash:I})}class M0{now(){return new Date}}function AQ($,V,Q,Z){let J=V.getTime()-$.getTime(),W=Q.getTime()-Z.getTime();return(J+W)/2}var G$={encode($,V){if($.writeVarInt(V.quota),V.quota>0){if(V.usage===void 0)return 9;$.writeVarInt(V.usage)}return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return z(Q);let Z;if(V>0){let[J,W]=$.readVarInt();if(W!==0)return z(W);Z=J}return O({quota:V,usage:Z})}};var zV={encode($,V){$.writeBytes(new Uint8Array([V.status]));let Q=$.writeDate(V.timeRcvd);if(Q!==0)return Q;let Z=$.writeDate(V.timeSent);if(Z!==0)return Z;let J=$.writeVarInt(V.subscription.term);if(J!==0)return J;let W=$.writeVarInt(V.subscription.elapsed);if(W!==0)return W;let Y=$.writeStruct(G$,V.subscription.stat);if(Y!==0)return Y;let X=$.writeStruct(G$,V.subscription.dyn);if(X!==0)return X;return 0},decode($){let[V,Q]=$.readBytes(1);if(Q!==0)return z(Q);let Z=V[0],[J,W]=$.readDate();if(W!==0)return z(W);let[Y,X]=$.readDate();if(X!==0)return z(X);let[G,K]=$.readVarInt();if(K!==0)return z(K);let[R,I]=$.readVarInt();if(I!==0)return z(I);let[N,U]=$.readStruct(G$);if(U!==0)return z(U);let[M,F]=$.readStruct(G$);if(F!==0)return z(F);return O({status:Z,timeRcvd:J,timeSent:Y,subscription:{term:G,elapsed:R,stat:N,dyn:M}})}};var RV={encode($,V){let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;let Z=$.writeVarInt(V.seq);if(Z!==0)return Z;return 0},decode($){let[V,Q]=$.readVarBytes();if(Q!==0)return z(Q);let[Z,J]=$.readVarInt();if(J!==0)return z(J);return O({headCph:V,seq:Z})}};var Y0={encode($,V){$.writeBytes(V.pubKey),$.writeBytes(V.sig);let Q=$.writeDate(V.timestamp);if(Q!==0)return Q;return 0},decode($){let[V,Q]=$.readBytes(HQ);if(Q!==0)return z(Q);let[Z,J]=$.readBytes(D0);if(J!==0)return z(J);let[W,Y]=$.readDate();if(Y!==0)return z(Y);return O({pubKey:V,sig:Z,timestamp:W})}};var DQ={async encodeReq($,V,Q,Z,J){let W=J.writeStruct(Y0,Q);if(W!==0)return W;for(let Y of Z)J.writeVarInt(Y);return 0},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W}=$,[Y,X]=V.readStruct(Y0);if(X!==0)return X;let G=await j0(Y,J,Z);if(G!==0)return G;let{pubKey:K}=Y,[R,I]=await W.hasUser(K);if(I!==0)return I;if(!R)return 5;let[N,U]=V.readVarInt();if(U!==0)return U;if(!V.done())return 8;let[M,F]=await W.listHeads(K,N);if(F!==0)return F;return Q.writeStructs(RV,M)},decodeResp($){return $.readStructs(RV)}};var IV={encode($,V){$.writeVarInt(V.seq);let Q=$.writeVarBytes(V.bodyCph);if(Q!==0)return Q;return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return z(Q);let[Z,J]=$.readVarBytes();if(J!==0)return z(J);return O({seq:V,bodyCph:Z})}};var _Q={async encodeReq($,V,Q,Z,J){let W=J.writeStruct(Y0,Q);if(W!==0)return W;for(let Y of Z){let X=J.writeVarInt(Y);if(X!==0)return X}return 0},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W}=$,[Y,X]=V.readStruct(Y0);if(X!==0)return X;let G=await j0(Y,J,Z);if(G!==0)return G;let{pubKey:K}=Y,[R,I]=await W.hasUser(K);if(I!==0)return I;if(!R)return 5;let N=[];while(!V.done()){let[F,q]=V.readVarInt();if(q!==0)return q;N.push(F)}console.info(`PULL: ${N.length} bags`);let[U,M]=await W.getBodies(K,N);if(M!==0)return M;if(!U)return 17;for(let{seq:F,bodyCph:q}of U){let C={seq:F,bodyCph:q},P=Q.writeStruct(IV,C);if(P!==0)return P}return 0},decodeResp($){return $.readStructs(IV)}};var NV={encode($,V){$.writeBytes(V.sig),$.writeBytes(V.kdm);let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;let Z=$.writeVarBytes(V.bodyCph);if(Z!==0)return Z;return 0},decode($){let[V,Q]=$.readBytes(D0);if(Q!==0)return z(Q);let[Z,J]=$.readBytes(_0);if(J!==0)return z(J);let[W,Y]=$.readVarBytes();if(Y!==0)return z(Y);let[X,G]=$.readVarBytes();if(G!==0)return z(G);return O({sig:V,kdm:Z,headCph:W,bodyCph:X})}};var L$={encode($,V){let Q=$.writeVarInt(V.seq);if(Q!==0)return Q;let Z=$.writeVarBytes(V.headCph);if(Z!==0)return Z;let J=V.bodyCph?V.bodyCph.length:0,W=$.writeVarInt(J);if(W!==0)return W;if(J>0){if(!V.bodyCph)return 10;$.writeBytes(V.bodyCph)}return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return z(Q);let[Z,J]=$.readVarBytes();if(J!==0)return z(J);let[W,Y]=$.readVarInt();if(Y!==0)return z(Y);let X;if(W>0){let[G,K]=$.readBytes(W);if(K!==0)return z(K);X=G}return O({seq:V,headCph:Z,bodyCph:X})}};var x$={encode($,V){$.writeBytes(V.sig),$.writeBytes(V.kdm);let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;return 0},decode($){let[V,Q]=$.readBytes(D0);if(Q!==0)return z(Q);let[Z,J]=$.readBytes(_0);if(J!==0)return z(J);let[W,Y]=$.readVarBytes();if(Y!==0)return z(Y);return O({sig:V,kdm:Z,headCph:W})}};var S$={encode($,V){if($.writeVarInt(V.idx),$.writeBytes(new Uint8Array([V.status])),V.status===0)$.writeVarInt(V.seq);return 0},decode($){let[V,Q]=$.readVarInt();if(Q!==0)return z(Q);let[Z,J]=$.readBytes(1);if(J!==0)return z(J);let W=Z[0];if(W!==0)return O({idx:V,status:W});let[Y,X]=$.readVarInt();if(X!==0)return z(X);return O({idx:V,status:W,seq:Y})}};var jQ={async encodeReq($,V,Q,Z,J){let W=J.writeStruct(Y0,Q);if(W!==0)return W;let Y=J.writeStructs(NV,Z);if(Y!==0)return Y;return 0},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W,notifier:Y}=$,[X,G]=V.readStruct(Y0);if(G!==0)return G;let K=await j0(X,J,Z);if(K!==0)return K;let{pubKey:R}=X,[I,N]=await W.hasUser(R);if(N!==0)return N;if(!I)return 5;let[U,M]=V.readStructs(NV);if(M!==0)return M;console.info(`PUSH: ${U.length} bags`);let F=[],q=[];for(let H=0;H<U.length;H++){let D=U[H];if(!await wQ(D,R,J)){let B={idx:H,status:3},m=Q.writeStruct(S$,B);if(m!==0)return m;continue}F.push(H),q.push(D)}let[C,P]=await W.setBags(R,q);if(P!==0)return P;if(!C||C.length!==q.length)return 17;let T=[];for(let H=0;H<q.length;H++){let D=q[H],S=F[H],B=C[H],m=new g,f=m.writeStruct(x$,D);if(f!==0)return f;let i=m.result(),w={seq:B,headCph:i};if(U.length===1&&D.bodyCph.length<=CQ)w.bodyCph=D.bodyCph;T.push(w);let b={idx:S,status:0,seq:B},l=Q.writeStruct(S$,b);if(l!==0)return l}if(T.length>0){let H=new g,D=H.writeStructs(L$,T);if(D!==0)return D;let S=H.result();await Promise.resolve(Y.push(R,S))}return 0},decodeResp($){return $.readStructs(S$)}};var LQ={async encodeReq($,V,Q,Z,J){return J.writeStruct(Y0,Q)},async handleReq($,V,Q){let{clock:Z,crypto:J,storage:W}=$,[Y,X]=V.readStruct(Y0);if(X!==0)return X;let G=await j0(Y,J,Z);if(G!==0)return G;let{pubKey:K}=Y;if(!V.done())return 8;let[R,I]=await W.addUser(K);if(I!==0)return I;return 0},decodeResp($){return O(void 0)}};class UV{url;websocket;constructor($){this.url=$}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect($,V,Q=()=>{},Z=()=>{}){let{url:J}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let W=new g;W.writeStruct(Y0,$);let Y=W.result(),X=t(Y);return J.searchParams.set("t",X),this.websocket=new WebSocket(J),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),Z()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Q()},this.websocket.onmessage=(G)=>{let K=new Uint8Array(G.data);V(K)},this.websocket.onerror=(G)=>{console.log(`ERROR: ${JSON.stringify(G)}`),this.websocket=void 0,Q()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var a={user:{path:"/user",endpoint:LQ,name:0},push:{path:"/push",endpoint:jQ,name:2},peek:{path:"/peek",endpoint:DQ,name:1},pull:{path:"/pull",endpoint:_Q,name:3}},GJ={0:a.user,2:a.push,1:a.peek,3:a.pull},P8={[a.user.path]:a.user,[a.push.path]:a.push,[a.peek.path]:a.peek,[a.pull.path]:a.pull};class OV{url;listener;constructor($){this.url=$;this.listener=new UV($)}async call($,V){let{path:Q}=GJ[$],Z=new URL(Q,this.url);try{return await KJ(Z,V)}catch{return z(25)}}}var f$=($)=>{return new OV($.handle)};async function KJ($,V){let Q=await fetch($,{method:"POST",body:V.result().slice()});if(!Q.ok)return z(24);let Z=await k.fromResponse(Q);return O(Z)}class E${enclave;crypto;host;clock;transport;updateHostMeta;constructor($,V,Q,Z,J,W){this.enclave=$;this.crypto=V;this.host=Q;this.clock=Z;this.transport=J;this.updateHostMeta=W}async call($,V){let{clock:Q,transport:Z}=this,{endpoint:J,name:W}=$,Y=await this.identity(),X=Q.now(),[G,K]=await GV(Y,X);if(K!==0)return z(K);let R=new g,I=await J.encodeReq(this,Y,G,V,R);if(I!==0)return z(I);let N=Q.now(),[U,M]=await Z.call(W,R),F=Q.now();if(M!==0)return z(M);let[q,C]=U.readStruct(zV);if(C!==0)return z(C);if(q.status!==0)return z(q.status);let T={clockOffset:AQ(N,q.timeRcvd,q.timeSent,F),subscription:q.subscription},H=await this.updateHostMeta(T);if(H!==0)return z(H);return J.decodeResp(U)}identity=()=>{let{host:$,enclave:V}=this;return V.deriveIdentity($.label,$.idx??0)};seal=async($)=>{let{crypto:V,enclave:Q}=this,Z=await this.identity();return TQ($,Z,V,Q)};register=()=>this.call(a.user,[]);peek=($)=>this.call(a.peek,[$]);push=($)=>this.call(a.push,$);pull=($)=>this.call(a.pull,$);listen=async($,V,Q)=>{let{clock:Z,transport:J}=this,{listener:W}=J,Y=await this.identity(),X=Z.now(),[G,K]=await GV(Y,X);if(K!==0)return K;return await W.connect(G,$,V,Q)};isConnected(){let $=this.transport?.listener;if($&&typeof $.connected==="function")return $.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var FV={encode($,V){let Q=$.writeVarString(V.lbl);if(Q!==0)return Q;let Z=$.writeVarInt(V.idx);if(Z!==0)return Z;let J=$.writeVarInt(V.num);if(J!==0)return J;return $.writeBytes(V.hsh),$.writeBytes(V.sig),0},decode($){let[V,Q]=$.readVarString();if(Q!==0)return z(Q);let[Z,J]=$.readVarInt();if(J!==0)return z(J);let[W,Y]=$.readVarInt();if(Y!==0)return z(Y);let[X,G]=$.readBytes(_$);if(G!==0)return z(G);let[K,R]=$.readBytes(D0);if(R!==0)return z(R);return O({lbl:V,idx:Z,num:W,hsh:X,sig:K})}};var MV={encode($,V){let Q=$.writeStruct(FV,V.head);if(Q!==0)return Q;let Z=$.writeVarBytes(V.indexEnc);if(Z!==0)return Z;let J=$.writeVarBytes(V.bodyEnc);if(J!==0)return J;return 0},decode($){let[V,Q]=$.readStruct(FV);if(Q!==0)return z(Q);let[Z,J]=$.readVarBytes();if(J!==0)return z(J);let[W,Y]=$.readVarBytes();if(Y!==0)return z(Y);return O({head:V,indexEnc:Z,bodyEnc:W})}};var qV={encode($,V){$.writeBytes(V.kdm);let Q=$.writeVarBytes(V.headCph);if(Q!==0)return Q;let Z=$.writeVarInt(V.lenBody);if(Z!==0)return Z;if(V.lenBody>0&&V.offBody!==void 0){let J=$.writeVarInt(V.offBody);if(J!==0)return J}return 0},decode($){let[V,Q]=$.readBytes(_0);if(Q!==0)return z(Q);let[Z,J]=$.readVarBytes();if(J!==0)return z(J);let[W,Y]=$.readVarInt();if(Y!==0)return z(Y);let X;if(W>0){let[G,K]=$.readVarInt();if(K!==0)return z(K);X=G}return O({kdm:V,headCph:Z,lenBody:W,offBody:X})}};async function xQ($,V,Q,Z,J){let W=await J.deriveIdentity($,V),Y=new g,X=new g,G=0,K=0;for(let C of Q){let P=new g,T=P.writeStruct(X0,C.head);if(T!==0)return z(T);let H=P.result(),D=await W.kdmFor(H),S=J.deriveCipher(D,"encrypt"),B=await S.encrypt(H),m=C.body?await S.encrypt(C.body):new Uint8Array(0),f=C.head.len>0&&C.head.hsh!==void 0?m.length:0,i={kdm:D,headCph:B,lenBody:f,offBody:f>0?K:void 0},w=Y.writeStruct(qV,i);if(w!==0)return z(w);if(C.body)X.writeBytes(m),K+=m.length;G++}let R=X.result(),I=Y.result(),N=await Z.blake3(I),U=await W.sign(N),M={lbl:$,idx:V,num:G,hsh:N,sig:U},F=new g;F.writeStruct(MV,{head:M,indexEnc:I,bodyEnc:R});let q=F.result();return O(q)}async function SQ($,V,Q){let[Z,J]=MV.decode(new k($));if(J!==0)return z(J);let{head:W,indexEnc:Y,bodyEnc:X}=Z,G=await Q.deriveIdentity(W.lbl,W.idx);if(!await V.checkSigEd25519(W.sig,W.hsh,G.publicKey))return z(3);let R=await V.blake3(Y);if(!e(R,W.hsh))return z(19);let I=new k(Y),N=[];for(let M=0;M<W.num;M++){let[F,q]=I.readStruct(qV);if(q!==0)return z(q);N.push(F)}if(N.length!==W.num)return z(14);let U=[];for(let M of N){let F=Q.deriveCipher(M.kdm,"decrypt"),q;try{q=await F.decrypt(M.headCph)}catch{return z(20)}let[C,P]=X0.decode(new k(q));if(P!==0)return z(P);let T;if(M.lenBody>0&&M.offBody!==void 0){if(C.hsh===void 0)return z(14);let H=X.slice(M.offBody,M.offBody+M.lenBody);try{T=await F.decrypt(H)}catch{return z(20)}let D=await V.blake3(T);if(!e(D,C.hsh))return z(19)}U.push({head:C,body:T})}return O(U)}async function fQ({now:$,bod:V,crypto:Q}){let Z=await Q.genRandomBytes(8),J=new g,W=J.writeStruct(o,{id:Z,ts:$});if(W!==0)return z(W);let Y=J.result();return m$({now:$,eid:Y,ctr:0,bod:V,crypto:Q})}async function m$({now:$,eid:V,ctr:Q,bod:Z,crypto:J}){let W=new k(V),[Y,X]=o.decode(W);if(X!==0)return z(X);let G=$.getTime()-Y.ts.getTime(),K,R=Z?.length??0;if(Z&&R>0)K=await J.blake3(Z);return O({eid:V,off:G,ctr:Q,len:R,hsh:K})}function EQ($,V){let Q=$.length<V.length?$.length:V.length;for(let Z=0;Z<Q;Z++)if($[Z]!==V[Z])return $[Z]-V[Z];return $.length-V.length}async function d0($,V){let Q=Array.from($);Q.sort(EQ);let Z=0;for(let Y of Q)Z+=Y.length;let J=new Uint8Array(Z),W=0;for(let Y of Q)J.set(Y,W),W+=Y.length;return V.blake3(J)}function mQ($){let V=new g,Q=V.writeVarBytes($.eid);if(Q!==0)return z(Q);let Z=V.writeDate($.updatedAt);if(Z!==0)return z(Z);let J=V.writeVarInt($.ctr);if(J!==0)return z(J);return O(V.result())}async function K$($,V){let Q=[];for(let Z of $){let[J,W]=mQ(Z);if(W!==0||!J)return z(W);Q.push(J)}return O(await d0(Q,V))}var RG=Symbol("EntityID");function BQ($){return"type"in $}var IG=Symbol("MasterSeed"),NG=Symbol("DerivationSeed"),UG=Symbol("PublicKey"),OG=Symbol("PrivateKey"),FG=Symbol("HostSpecificKeyPair"),MG=Symbol("Hash");function zJ($){if(!$)return!1;if(typeof $!=="object")return!1;if("body"in $===!1)return!1;if("type"in $===!1)return!1;return!0}function RJ($){if(!$.bod||$.bod.length===0){let Z={off:$.off,ctr:$.ctr,eid:$.eid};return O(Z)}let V=XV($.bod);if(zJ(V)===!1)return console.warn("msg body invalid",V),z(14);let Q={off:$.off,ctr:$.ctr,eid:$.eid,gid:V.gid,pid:V.pid,tags:V.tags,type:V.type,body:V.body};return O(Q)}class z${applier;emitter=new A0;clearer;onDirtyEids;cacheDriven;peerIngest;constructor($,V,Q,Z){this.applier=$;this.clearer=V,this.onDirtyEids=Q,this.cacheDriven=Z?.cacheDriven??!1,this.peerIngest=Z?.peerIngest}apply=async($)=>{let V=[],Q=[];for(let X of $){let[G,K]=RJ(X);if(Q.push(K),K!==0)continue;V.push(G)}let{stats:Z,types:J,eids:W}=await this.applier(V),Y=[];for(let X=0;X<$.length;X++){let G=Q[X],K=Z[X];if(G!==0){Y.push(G);continue}if(K!==0){Y.push(K);continue}Y.push(0)}if(!this.cacheDriven)for(let X of J)this.emitter.emit(X,null);if(W.length>0)this.onDirtyEids?.(W);return Y};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 HV={apply:async function($){return $.map(()=>0)},clear:async function(){return 0},notify:function($){},refresh:async function($){},on:function($,V){},off:function($,V){}};var n="entities",B$="entity_type_created_at",CV="entity_type_updated_at",wV="entity_type_group_id",TV="entity_type_parent_id",r0="entity_tags",kQ="db",gQ=13;function IJ($){return"typ"in $}function NJ($){let V={bod:$.body,crd:$.createdAt,...$.ctr!==0?{ctr:$.ctr}:{},eid:L($.eid),gid:$.gid,pid:$.pid?L($.pid):void 0,tgs:$.tags,typ:$.type,upd:$.updatedAt};if(V.gid===void 0)delete V.gid;if(V.pid===void 0)delete V.pid;if(V.tgs===void 0)delete V.tgs;if(V.ctr===void 0)delete V.ctr;return V}function UJ($){if(!u($))return{eid:L($.eid),upd:$.updatedAt,...$.ctr!==0?{ctr:$.ctr}:{}};return NJ($)}function o0($){return{body:$.bod,createdAt:$.crd,updatedAt:$.upd,ctr:$.ctr??0,type:$.typ,eid:Q0($.eid),gid:$.gid,pid:$.pid?Q0($.pid):void 0,...$.tgs!==void 0?{tags:$.tgs}:{}}}function PV($){if(IJ($))return o0($);return{eid:Q0($.eid),updatedAt:$.upd,ctr:$.ctr??0}}class AV{db;opening;async init(){await this.ensureDb()}async ensureDb(){if(this.db)return this.db;if(this.opening)return this.opening;return this.opening=FJ().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,Q=[],Z;try{Z=await this.ensureDb()}catch{return{stats:$.map(()=>16),types:V,eids:Q}}let J=Z.transaction(n,"readwrite"),W=J.objectStore(n);return new Promise((Y)=>{let X=Array($.length).fill(0);if($.length<1){Y({stats:[],types:V,eids:Q});return}J.oncomplete=()=>{Y({stats:X,types:V,eids:Q})},J.onerror=()=>{for(let K=0;K<X.length;K++)if(X[K]===void 0)X[K]=18;Y({stats:X,types:V,eids:Q})};let G=new Map;for(let K=0;K<$.length;K++){let R=$[K],I=L(R.eid),N={op:R,index:K},U=G.get(I);if(U)U.push(N);else G.set(I,[N])}for(let[K,R]of G){if(R.length<1)continue;let I=W.get(K);I.onsuccess=()=>{let N=I.result,U=N?PV(N):void 0,M=!1;for(let{op:F,index:q}of R){let[C,P]=a0(U,F);if(P!==0){X[q]=P;continue}if(C===void 0){X[q]=12;continue}M=!0;for(let T of s0(U,C))V.add(T);U=C}if(M)Q.push(R[0].op.eid);if(U){let F=W.put(UJ(U));F.onerror=(q)=>{q.preventDefault();for(let{index:C}of R)X[C]=18}}},I.onerror=()=>{for(let{index:N}of R)X[N]=18}}})};async clear(){let $;try{$=await this.ensureDb()}catch{return 16}let V=$.transaction(n,"readwrite"),Q=V.objectStore(n);return new Promise((Z)=>{V.oncomplete=()=>Z(0),V.onerror=()=>Z(18),Q.clear()})}async getRow($){let V;try{V=await this.ensureDb()}catch{return z(16)}let Q=L($),J=V.transaction(n,"readonly").objectStore(n);return new Promise((W)=>{let Y=J.get(Q);Y.onsuccess=()=>{let X=Y.result;if(!X)W(O(void 0));else W(O(PV(X)))},Y.onerror=()=>W(z(18))})}async getEnt($){let[V,Q]=await this.getRow($);if(Q!==0)return z(Q);if(V===void 0||!u(V))return O(void 0);return O(V)}async getAllOfTypeUpdatedBetween($,V,Q){let Z;try{Z=await this.ensureDb()}catch{return z(16)}let W=Z.transaction(n,"readonly").objectStore(n).index(CV);return new Promise((Y)=>{let X=W.getAll(IDBKeyRange.bound([$,V],[$,Q]));X.onsuccess=()=>{let G=X.result;Y(O(G.map(o0)))},X.onerror=()=>Y(z(18))})}async getGroupMembers($,V){let Q;try{Q=await this.ensureDb()}catch{return z(16)}let J=Q.transaction(n,"readonly").objectStore(n).index(wV);return new Promise((W)=>{let Y=J.getAll(IDBKeyRange.only([$,V]));Y.onsuccess=()=>{let X=Y.result;W(O(X.map(o0)))},Y.onerror=()=>W(z(18))})}async getAllOfType($){let V;try{V=await this.ensureDb()}catch{return z(16)}let Z=V.transaction(n,"readonly").objectStore(n).index(B$);return new Promise((J)=>{let W=Z.getAll(IDBKeyRange.bound([$],[$,[]]));W.onsuccess=()=>{let Y=W.result;J(O(Y.map(o0)))},W.onerror=()=>J(z(18))})}async getByTag($,V){let Q;try{Q=await this.ensureDb()}catch{return z(16)}let J=Q.transaction(n,"readonly").objectStore(n).index(r0);return new Promise((W)=>{let Y=J.getAll(IDBKeyRange.only(V));Y.onsuccess=()=>{let G=Y.result.filter((K)=>K.typ===$).map(o0);W(O(G))},Y.onerror=()=>W(z(18))})}async getAllEntities($){if("pid"in $){let V;try{V=await this.ensureDb()}catch{return z(16)}let Q=L($.pid),J=V.transaction(n,"readonly").objectStore(n).index(TV);return new Promise((W)=>{let Y=J.getAll(IDBKeyRange.only([$.type,Q]));Y.onsuccess=()=>{let G=Y.result.map(o0);W(O(G))},Y.onerror=()=>W(z(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,Q]=await this.getAllEntities($);if(Q!==0)return z(Q);return O(V)}async countEntities({type:$}){let V;try{V=await this.ensureDb()}catch{return z(16)}let Z=V.transaction(n,"readonly").objectStore(n).index(B$);return new Promise((J)=>{let W=IDBKeyRange.bound([$],[$,[]]),Y=Z.count(W);Y.onsuccess=()=>J(O(Y.result)),Y.onerror=()=>J(z(18))})}async checksum($){let V;try{V=await this.ensureDb()}catch{return z(16)}let Z=V.transaction(n,"readonly").objectStore(n),J=[];return new Promise((W)=>{let Y=Z.openCursor();Y.onsuccess=()=>{let X=Y.result;if(X){let G=X.value;J.push(R$(PV(G))),X.continue()}else K$(J,$).then(W)},Y.onerror=()=>W(z(18))})}}function OJ($,V){if(!$.objectStoreNames.contains(n))$.createObjectStore(n,{keyPath:"eid",autoIncrement:!1});let Q=V.objectStore(n);if(!Q.indexNames.contains(B$))Q.createIndex(B$,["typ","crd"],{unique:!1});if(!Q.indexNames.contains(CV))Q.createIndex(CV,["typ","upd"],{unique:!1});if(!Q.indexNames.contains(wV))Q.createIndex(wV,["typ","gid"],{unique:!1});if(!Q.indexNames.contains(TV))Q.createIndex(TV,["typ","pid"],{unique:!1});if(Q.indexNames.contains(r0)){if(Q.index(r0).keyPath!=="tgs")Q.deleteIndex(r0)}if(!Q.indexNames.contains(r0))Q.createIndex(r0,"tgs",{unique:!1,multiEntry:!0})}function FJ(){return new Promise(($,V)=>{let Q=indexedDB.open(kQ,gQ);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!J){V(Error("Transaction is null during EntDB upgrade"));return}try{OJ(Z,J)}catch(W){V(W instanceof Error?W:Error(String(W)))}},Q.onblocked=()=>{console.warn(`[DIPLOMATIC] EntDB IDB upgrade blocked (${kQ} → v${gQ}); waiting for other connections to close`)},Q.onsuccess=()=>$(Q.result),Q.onerror=()=>V(Q.error??Error("EntDB IndexedDB open failed"))})}async function vQ(){let $=new AV;return await $.init(),$}class k${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 Q of $)this.put(Q)}put($){let V=L($.eid),Q=this.ents.get(V);if(Q!==void 0&&u(Q))this.unindex(V,Q);if(this.ents.set(V,$),u($))this.index(V,$)}del($){let V=this.ents.get($);if(V===void 0)return;if(u(V))this.unindex($,V);this.ents.delete($)}index($,V){if(!this.useIndex)return;let Q=this.byType.get(V.type);if(!Q)Q=new Map,this.byType.set(V.type,Q);if(Q.set($,V),V.pid){let Z=L(V.pid),J=this.byTypePid.get(V.type);if(!J)J=new Map,this.byTypePid.set(V.type,J);let W=J.get(Z);if(!W)W=new Map,J.set(Z,W);W.set($,V)}if(typeof V.gid==="string"){let Z=this.byTypeGid.get(V.type);if(!Z)Z=new Map,this.byTypeGid.set(V.type,Z);let J=Z.get(V.gid);if(!J)J=new Map,Z.set(V.gid,J);J.set($,V)}if(V.tags){let Z=this.byTypeTag.get(V.type);if(!Z)Z=new Map,this.byTypeTag.set(V.type,Z);for(let J of V.tags){let W=Z.get(J);if(!W)W=new Map,Z.set(J,W);W.set($,V)}}}unindex($,V){if(!this.useIndex)return;let Q=this.byType.get(V.type);if(Q){if(Q.delete($),Q.size===0)this.byType.delete(V.type)}if(V.pid){let Z=L(V.pid),J=this.byTypePid.get(V.type),W=J?.get(Z);if(W){if(W.delete($),W.size===0)J?.delete(Z)}if(J&&J.size===0)this.byTypePid.delete(V.type)}if(typeof V.gid==="string"){let Z=this.byTypeGid.get(V.type),J=Z?.get(V.gid);if(J){if(J.delete($),J.size===0)Z?.delete(V.gid)}if(Z&&Z.size===0)this.byTypeGid.delete(V.type)}if(V.tags){let Z=this.byTypeTag.get(V.type);if(Z){for(let J of V.tags){let W=Z.get(J);if(W){if(W.delete($),W.size===0)Z.delete(J)}}if(Z.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 Q of $.values())V.push(Q);return V}async apply($){let V=new Set,Q=[],Z=[];for(let J of $){let W=L(J.eid),Y=this.ents.get(W),[X,G]=a0(Y,J);if(G!==0){Z.push(G);continue}if(X===void 0){Z.push(12);continue}for(let K of s0(Y,X))V.add(K);this.put(X),Q.push(J.eid),Z.push(0)}return{stats:Z,types:V,eids:Q}}async clear(){return this.ents.clear(),this.clearIndexes(),0}async getRow($){let V=L($),Q=this.ents.get(V);return O(Q)}async getEnt($){let[V,Q]=await this.getRow($);if(Q!==0)return z(Q);if(V===void 0||!u(V))return O(void 0);return O(V)}async getAllEntities({type:$,gid:V,pid:Q,tag:Z,updatedBetween:J}){if(this.useIndex){if(Q!==void 0){let Y=L(Q);return O(this.bucketList(this.byTypePid.get($)?.get(Y)))}if(V!==void 0)return O(this.bucketList(this.byTypeGid.get($)?.get(V)));if(Z!==void 0)return O(this.bucketList(this.byTypeTag.get($)?.get(Z)));if(J!==void 0){let Y=[],X=this.byType.get($);if(X){for(let G of X.values())if(G.updatedAt>=J.start&&G.updatedAt<=J.end)Y.push(G)}return O(Y)}return O(this.bucketList(this.byType.get($)))}let W=[];if(Q!==void 0){for(let Y of this.ents.values())if(u(Y)&&Y.type===$&&Y.pid&&e(Y.pid,Q))W.push(Y)}else if(V!==void 0){for(let Y of this.ents.values())if(u(Y)&&Y.type===$&&(typeof Y.gid==="string"&&Y.gid===V))W.push(Y)}else if(Z!==void 0){for(let Y of this.ents.values())if(u(Y)&&Y.type===$&&Y.tags&&Y.tags.includes(Z))W.push(Y)}else if(J!==void 0){for(let Y of this.ents.values())if(u(Y)&&Y.type===$&&Y.updatedAt>=J.start&&Y.updatedAt<=J.end)W.push(Y)}else for(let Y of this.ents.values())if(u(Y)&&Y.type===$)W.push(Y);return O(W)}async getEntities($){let[V,Q]=await this.getAllEntities($);if(Q!==0)return z(Q);return O(V)}async countEntities({type:$}){if(this.useIndex)return O(this.byType.get($)?.size??0);let V=0;for(let Q of this.ents.values())if(u(Q)&&Q.type===$)V+=1;return O(V)}async checksum($){let V=[];for(let Q of this.ents.values())V.push(R$(Q));return K$(V,$)}}async function DV($){let V=await vQ();if($?.cache===!1)return V;return new I$(V,void 0,{indexes:$?.indexes})}class I${mem;durable;warmed=new Set;listeners=new Set;chain=Promise.resolve();constructor($,V,Q){if(this.durable=$,this.mem=new k$(V??[],{indexes:Q?.indexes}),V)for(let Z of V)this.warmed.add(Z.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()=>{await this.pullEids($.map((W)=>W.eid));let V=wJ(this.mem,$);this.emit(V.types);let Q=await this.durable.apply($),{changed:Z,status:J}=await this.pullEids($.map((W)=>W.eid));if(this.emit(Z),J!==0)return{stats:$.map(()=>J),types:Q.types,eids:Q.eids};return Q})}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:Q}=await this.pullEids($);return this.emit(V),Q})}async pullEids($){let V=new Set,Q=new Set;for(let Z of $){let J=L(Z);if(Q.has(J))continue;Q.add(J);let W=this.mem.ents.get(J),[Y,X]=await this.durable.getRow(Z);if(X!==0)return{changed:V,status:X};if(Y){if(this.mem.put(Y),!W||!MJ(W,Y)){if(u(Y))V.add(Y.type);if(W!==void 0&&u(W))V.add(W.type)}}else if(W!==void 0){if(this.mem.del(J),u(W))V.add(W.type)}}return{changed:V,status:0}}async warmType($){if(this.warmed.has($))return 0;let[V,Q]=await this.durable.getEntities({type:$});if(Q!==0)return Q;if(V)for(let Z of V){let J=L(Z.eid),W=this.mem.ents.get(J);if(!W||CJ(Z,W))this.mem.put(Z)}return this.warmed.add($),0}async getRow($){let V=L($);if(this.mem.ents.has(V))return this.mem.getRow($);return this.run(async()=>{if(this.mem.ents.has(V))return this.mem.getRow($);let[Q,Z]=await this.durable.getRow($);if(Z!==0)return z(Z);if(Q)this.mem.put(Q);return O(Q)})}async getEnt($){let[V,Q]=await this.getRow($);if(Q!==0)return z(Q);if(V===void 0||!u(V))return O(void 0);return O(V)}async getEntities($){if(!this.warmed.has($.type)){let V=await this.run(()=>this.warmType($.type));if(V!==0)return z(V)}return this.mem.getEntities($)}async countEntities({type:$}){if(!this.warmed.has($)){let V=await this.run(()=>this.warmType($));if(V!==0)return z(V)}return this.mem.countEntities({type:$})}async checksum($){return this.durable.checksum($)}}function MJ($,V){if(u($)!==u(V))return!1;if($.ctr!==V.ctr)return!1;if($.updatedAt.getTime()!==V.updatedAt.getTime())return!1;if(!e($.eid,V.eid))return!1;if(!u($)||!u(V))return!0;if($.createdAt.getTime()!==V.createdAt.getTime())return!1;if($.type!==V.type)return!1;if($.gid!==V.gid)return!1;if(!HJ($.pid,V.pid))return!1;if(!qJ($.tags,V.tags))return!1;return PJ($.body,V.body)}function qJ($,V){if($===V)return!0;if($===void 0||V===void 0)return!1;if($.length!==V.length)return!1;for(let Q=0;Q<$.length;Q++)if($[Q]!==V[Q])return!1;return!0}function HJ($,V){if($===void 0&&V===void 0)return!0;if($===void 0||V===void 0)return!1;return e($,V)}function PJ($,V){if(Object.is($,V))return!0;if($ instanceof Uint8Array&&V instanceof Uint8Array)return e($,V);if($ instanceof Date&&V instanceof Date)return $.getTime()===V.getTime();try{return e(f0($),f0(V))}catch{return!1}}function CJ($,V){let Q=$.updatedAt.getTime(),Z=V.updatedAt.getTime();if(Q!==Z)return Q>Z;return $.ctr>V.ctr}function wJ($,V){let Q=new Set,Z=[];for(let J of V){let W=L(J.eid),Y=$.ents.get(W),[X,G]=a0(Y,J);if(G!==0){Z.push(G);continue}if(X===void 0){Z.push(12);continue}for(let K of s0(Y,X))Q.add(K);$.put(X),Z.push(0)}return{stats:Z,types:Q}}function g$($){if($ instanceof I$){let V=new z$((Q)=>$.apply(Q),()=>$.clear(),void 0,{cacheDriven:!0,peerIngest:async(Q)=>{await $.ingestFromDurable(Q)}});return $.subscribe((Q)=>V.notify(Q)),V}return new z$((V)=>$.apply(V),()=>$.clear())}function u($){return"type"in $}function TJ($){return!u($)}function iQ($){if(!Array.isArray($)||$.length===0)return;let V=new Set,Q=[];for(let Z of $){if(typeof Z!=="string"||Z.length===0)continue;if(V.has(Z))continue;V.add(Z),Q.push(Z)}return Q.length>0?Q:void 0}function R$($){return{eid:$.eid,ctr:$.ctr,updatedAt:$.updatedAt}}function _V($){let V=new k($.eid),[Q,Z]=V.readStruct(o);if(Z!==0)return z(Z);return O({eid:$.eid,ctr:$.ctr,updatedAt:new Date(Q.ts.getTime()+$.off)})}function a0($,V){let Q=new k(V.eid),[Z,J]=Q.readStruct(o);if(J!==0)return z(J);let W=new Date(Z.ts.getTime()+V.off);if($!==void 0&&W<=$.updatedAt)return z(15);if(BQ(V)){let Y=iQ(V.tags);return O({eid:V.eid,gid:V.gid,pid:V.pid,...Y!==void 0?{tags:Y}:{},type:V.type,createdAt:Z.ts,updatedAt:W,ctr:V.ctr,body:V.body})}return O({eid:V.eid,updatedAt:W,ctr:V.ctr})}function s0($,V){let Q=new Set;if($!==void 0&&u($))Q.add($.type);if(u(V))Q.add(V.type);return[...Q]}var AJ={getEnt:async()=>z(21),getRow:async()=>z(21),getEntities:async($)=>z(21),countEntities:async()=>z(21),checksum:async()=>z(21),apply:async($)=>({stats:$.map(()=>21),types:new Set,eids:[]}),clear:async()=>21};class v${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 i$=100;class N${timer=null;delayMs;work;tail=new v$;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 yQ($){let V=new k($.eid),[Q,Z]=o.decode(V);if(Z!==0)return;return Q.ts.getTime()+$.off}function DJ($,V){let Q=yQ($),Z=yQ(V);if(Q===void 0&&Z===void 0)return 0;if(Q===void 0)return 1;if(Z===void 0)return-1;if(Z!==Q)return Z-Q;return V.ctr-$.ctr}function t0($,V){return $.slice().sort((Q,Z)=>DJ(V(Q),V(Z)))}var E0={phase:"idle"},e0=50;function y$($,V,Q){if($<=0||V<=0)return!1;if($===1||$===V)return!0;return $%Q===0}function u$($,V){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob($,V);return}let Q=URL.createObjectURL($),Z=document.createElement("a");Z.href=Q,Z.download=V,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(Q)}function uQ($,V,Q){let Z=[],J=[],W=0;for(let Y of $){let X=V(Y);if(J.length>0&&W+X>Q)Z.push(J),J=[],W=0;if(J.push(Y),W+=X,W>=Q)Z.push(J),J=[],W=0}if(J.length>0)Z.push(J);return Z}async function jV($,V,Q){let Z=$.length;if(Z<1)return[];let J=Array(Z),W=0,Y=Math.min(Math.max(1,V),Z),X=async()=>{while(!0){let K=W;if(W+=1,K>=Z)return;J[K]=await Q($[K],K)}},G=[];for(let K=0;K<Y;K++)G.push(X());return await Promise.all(G),J}async function b$($,V,Q,Z){let J=new k($.headCph),[W,Y]=J.readStruct(x$);if(Y!==0)return z(Y);let{sig:X,kdm:G,headCph:K}=W;if(!await Z.checkSigEd25519(X,K,V))return z(3);let I=Q.deriveCipher(G,"decrypt"),N;try{N=await I.decrypt(K)}catch{return z(20)}return O({kdm:G,headEnc:N})}var q0="f",x0="t",N0="e";function _J($){return $===q0||$===x0||$===N0}function $$($){if($===!0||$===x0)return x0;if($===N0)return N0;return q0}function jJ($){return $$($.apld)===q0}function LV($){return $!==0&&$!==15&&$!==18&&$!==17}function m0($,V,Q){if($.apld=V,V===N0&&Q!==void 0)$.err=Q;else delete $.err}async function S0($,V,Q,Z){let J=Z?.body!==!1,W=$$(V.apld),Y=V.body,X=Y?.length??0,G;if(J&&Y&&X>0)G=await Q.blake3(Y);let K={eid:V.eid,off:V.off??0,ctr:V.ctr??0,len:X,hsh:G},R={hash:$,head:K,apld:W};if(J&&Y!==void 0)R.body=Y;if(W===N0&&V.err!==void 0)R.err=V.err;return R}var xV=1048576,SV=1048576,hQ=64;function LJ($){return $.sig.length+$.kdm.length+$.headCph.length+$.bodyCph.length}async function xJ($,V,Q,Z,J){if(Z.length<1)return 0;let[W,Y]=await $.push(Z);if(Y!==0)return Y;if(!W)return 27;for(let G of W){if(G.status!==0){console.error("push err",G);continue}let K=J[G.idx];if(!K){console.error("no hash",G);continue}await V.uploads.deq(Q,[K])}let X=await V.hosts.get(Q);if(X){let G=X.lastSeq,K=G,R=[];for(let I of W)if(I.status===0)R.push(I.seq);R.sort((I,N)=>I-N);for(let I of R)if(I===G+1)G=I;if(G>K)await V.hosts.touch(Q,G)}return 0}async function bQ($,V){if(V.length<1)return O([]);let Q=new Map,Z=[];for(let X of V)Q.set(X.seq,X),Z.push(X.seq);let[J,W]=await $.pull(Z);if(W!==0)return z(W);if(!J)return z(27);let Y=[];for(let{seq:X,bodyCph:G}of J){let K=Q.get(X);if(!K)continue;Y.push({dl:K,bodyCph:G})}return O(Y)}async function SJ($,V,Q,Z){if(Z.length<1)return O({parts:[],hashes:[]});let J=[],W=[],Y=[],X=new Map;for(let{dl:K,bodyCph:R}of Z){let{head:I,kdm:N,seq:U,host:M}=K,[F,q]=await lQ(K,Q);if(q!==0||!F){let f=X.get(M)??[];f.push(U),X.set(M,f);continue}let{headEnc:C,headEncHash:P}=F,T=V.deriveCipher(N,"decrypt"),[H,D]=await KV(C,R,T,Q,P);if(D!==0||!H){let f=X.get(M)??[];f.push(U),X.set(M,f);continue}let S={head:I,body:H.bod},B=H.headHash;Y.push({key:B,data:cQ(S)}),J.push(S),W.push(B);let m=X.get(M)??[];m.push(U),X.set(M,m)}let G=await $.messages.add(Y);for(let[K,R]of X)await $.downloads.deq(K,R);for(let K=0;K<G.length;K++){let R=G[K];if(R!==0&&R!==15)console.error("ERR storing",_[R],"for message",K)}return O({parts:J,hashes:W})}async function lQ($,V){let Q=$.headEnc;if(!Q){let J=new g,W=J.writeStruct(X0,$.head);if(W!==0)return z(W);Q=J.result()}if($.headEncHash)return O({headEnc:Q,headEncHash:$.headEncHash});let Z=await V.blake3(Q);return O({headEnc:Q,headEncHash:Z})}async function pQ($,V,Q){let Z=new Set;for(let Y of V)Z.add(L(Y));if(Z.size<1)return;let J=Array.from(await $.downloads.list());if(J.length<1)return;let W=new Map;for(let Y of J){let X;if(Y.headEncHash)X=L(Y.headEncHash);else{let[K,R]=await lQ(Y,Q);if(R!==0||!K)continue;X=L(K.headEncHash)}if(!Z.has(X))continue;let G=W.get(Y.host)??[];G.push(Y.seq),W.set(Y.host,G)}for(let[Y,X]of W)await $.downloads.deq(Y,X)}async function fV({conn:$,store:V,enclave:Q,host:Z,crypto:J,onProgress:W,peekProgressEvery:Y,peekConcurrency:X}){let G=await $.identity(),K=[],[R,I]=await $.peek(Z.lastSeq);if(I!==0)return I;let N=R.length,U=Y??e0,M=X??hQ;if(W&&N>0)W({phase:"peek",host:Z.label,done:0,total:N});let F=0,q=await jV(R,M,async(P)=>{let[T,H]=await b$(P,G.publicKey,Q,J),D;if(H!==0||!T)D={ok:!1,seq:P.seq,stat:H};else{let S=await J.blake3(T.headEnc);D={ok:!0,seq:P.seq,kdm:T.kdm,headEnc:T.headEnc,headEncHash:S}}if(F+=1,W&&y$(F,N,U))W({phase:"peek",host:Z.label,done:F,total:N});return D}),C=new Set;for(let P of q){if(!P.ok){console.error("peek: decrypting item head",P.stat);continue}let T=L(P.headEncHash);if(await V.messages.has(P.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await V.uploads.deq(Z.label,[P.headEncHash]),await V.downloads.deq(Z.label,[P.seq]);continue}if(C.has(T)){await V.downloads.deq(Z.label,[P.seq]);continue}let D=new k(P.headEnc),[S,B]=D.readStruct(X0);if(B!==0){console.error("peek: reading item head",B);continue}C.add(T),K.push({kdm:P.kdm,head:S,seq:P.seq,host:Z.label,headEnc:P.headEnc,headEncHash:P.headEncHash})}if(await V.downloads.enq(K),R.length>0){let P=Math.max(...R.map((T)=>T.seq));await V.hosts.recordStats(Z.label,{lastSeq:P})}if(W)W({phase:"peek",host:Z.label,done:N,total:N});return 0}async function nQ({conn:$,store:V,host:Q,maxPushBytes:Z,onProgress:J}){let W=Z??xV,Y=await V.uploads.list(Q.label),X=Y.length,G=0;if(J&&X>0)J({phase:"push",host:Q.label,done:0,total:X});let K=[],R=[],I=0,N=async()=>{if(K.length<1)return 0;let U=K.length,M=await xJ($,V,Q.label,K,R);if(K=[],R=[],I=0,M===0){if(G+=U,J)J({phase:"push",host:Q.label,done:G,total:X})}return M};for(let U of Y){let M=await V.messages.get(U);if(!M){G+=1;continue}let F={...M.head,bod:M.body},[q,C]=await $.seal(F);if(C!==0)return C;if(!q)return 12;let P=LJ(q);if(K.length>0&&I+P>W){let T=await N();if(T!==0)return T}if(K.push(q),R.push(U),I+=P,I>=W){let T=await N();if(T!==0)return T}}return N()}async function EV({conn:$,store:V,enclave:Q,host:Z,crypto:J,maxPullBytes:W,onProgress:Y},X){let G=W??SV,K=await V.downloads.list(),R=Array.from(K).filter((q)=>q.host===Z.label);if(R.length<1)return 15;let I=t0(R,(q)=>q.head),N=uQ(I,(q)=>q.head.len,G),U=I.length,M=0;if(Y)Y({phase:"pull",host:Z.label,done:0,total:U});let F=bQ($,N[0]);for(let q=0;q<N.length;q++){let[C,P]=await F;if(P!==0||!C)return P;if(M+=N[q].length,Y)Y({phase:"pull",host:Z.label,done:M,total:U});let T=N[q+1];if(T)F=bQ($,T);if(Y)Y({phase:"open",host:Z.label,done:M,total:U});let H=t0(C,(S)=>S.dl.head),[,D]=await SJ(V,Q,J,H);if(D!==0)return D;if(X){if(Y)Y({phase:"exec",host:Z.label,done:M,total:U});await X()}}return 0}function cQ({head:$,body:V}){let Q={eid:$.eid,body:V,apld:q0};if($.off!==0)Q.off=$.off;if($.ctr!==0)Q.ctr=$.ctr;return Q}async function dQ($,{conn:V,store:Q,enclave:Z,host:J,crypto:W,onProgress:Y},X){let G=J.label,K=await V.identity(),R=new k($),[I,N]=R.readStructs(L$);if(N!==0){console.error("Failed decoding notif",_[N]);return}let U=!1,F=(await Q.hosts.get(G))?.lastSeq,q=[],C=!1;for(let H of I){let[D,S]=await b$({seq:H.seq,headCph:H.headCph},K.publicKey,Z,W);if(S!==0){console.error("Failed decrypting notif",_[S]);continue}let B=await W.blake3(D.headEnc);if(await Q.messages.has(B))continue;let m=new k(D.headEnc),[f,i]=m.readStruct(X0);if(i!==0){console.error("Failed to parse head",_[i]);continue}if(!H.bodyCph&&f.len>0)C=!0,await Q.downloads.enq([{seq:H.seq,host:G,kdm:D.kdm,head:f,headEnc:D.headEnc,headEncHash:B}]);else q.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 Q.hosts.touch(J.label,F);let P=[];for(let H of q){let D=Z.deriveCipher(H.kdm,"decrypt"),[S,B]=await KV(H.headEnc,H.bodyCph,D,W);if(B!==0){console.error("Failed to open body",_[B]);continue}P.push({key:H.headEncHash,data:cQ({head:H.head,body:S.bod})})}let T=await Q.messages.add(P);for(let H=0;H<T.length;H++){let D=T[H];if(D!==0&&D!==15)console.error("ERR storing",_[D],"for message",H)}if(Y&&P.length>0)Y({phase:"open",host:J.label,done:P.length,total:P.length});if(U||C||P.length>0)X()}async function mV($,V={}){let Q=V.pull!==!1,Z=V.push===!0,{conn:J,store:W,enclave:Y,host:X,crypto:G,onProgress:K,peekProgressEvery:R,peekConcurrency:I}=$,N=await J.identity(),[U,M]=await J.peek(0);if(M!==0)return z(M);let F=U.length,q=R??e0,C=I??hQ;if(K&&F>0)K({phase:"peek",host:X.label,done:0,total:F});let P=0,T=await jV(U,C,async(x)=>{let[v,E]=await b$(x,N.publicKey,Y,G),y;if(E!==0||!v)y={ok:!1,seq:x.seq,stat:E};else{let j=await G.blake3(v.headEnc);y={ok:!0,seq:x.seq,kdm:v.kdm,headEnc:v.headEnc,headEncHash:j}}if(P+=1,K&&y$(P,F,q))K({phase:"peek",host:X.label,done:P,total:F});return y}),H=new Map;for(let x of T){if(!x.ok)continue;let v=L(x.headEncHash),E=H.get(v);if(E)E.count+=1;else H.set(v,{hash:x.headEncHash,count:1,sample:x})}let D=0,S=[];for(let x of H.values()){if(x.count>1)D+=x.count-1;S.push(x.hash)}let B=U.length,m=H.size,f=await d0(S,G),i=[],w=0;for(let x of H.values()){if(await W.messages.has(x.hash)){await W.uploads.deq(X.label,[x.hash]);continue}if(w+=1,!Q)continue;let E=x.sample,y=new k(E.headEnc),[j,c]=y.readStruct(X0);if(c!==0){console.error("reconcile: reading msg header",c);continue}i.push({kdm:E.kdm,head:j,seq:E.seq,host:X.label,headEnc:E.headEnc,headEncHash:E.headEncHash})}if(i.length>0)await W.downloads.enq(i);let b=0;if(Z){let x=await W.messages.listKeys(),v=new Set(H.keys()),E=[];for(let y of x)if(!v.has(L(y)))b+=1,E.push(y);if(E.length>0)await W.uploads.enq(X.label,E)}else{let x=await W.messages.listKeys(),v=new Set(H.keys());for(let E of x)if(!v.has(L(E)))b+=1}let l=U.length>0?Math.max(...U.map((x)=>x.seq)):0;if(await W.hosts.recordStats(X.label,{setLastSeq:l}),K)K({phase:"peek",host:X.label,done:F,total:F});return O({msgcheck:f,numBags:B,uniqueMsgs:m,numDupes:D,missingLocal:w,missingHost:b})}class B0{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new v$;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=e0;lastProgress=E0;scheduledSync;constructor($,V,Q,Z,J,W=!0,Y=xV,X=SV,G){this.clock=$;this.state=V;this.store=Q;this.transport=Z;this.crypto=J;this.forceSkewHandlingByDefault=W;this.onScheduleSync=G;this.maxPushBytes=Y,this.maxPullBytes=X,this.clientState=new I0(()=>this.getClientState()),this.xferState=new I0(()=>this.getXferState()),this.scheduledSync=new N$(i$,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($,V){await this.store.seed.save($,V),this.clientState.emit()}async getClientState(){let{store:$,connections:V}=this,Q=await $.seed.load(),Z=await $.hosts.list(),J=!1;for(let W of V.values())if(W.isConnected()){J=!0;break}return{hasSeed:Q!==void 0,hasHost:Array.from(Z).length>0,connected:J}}async getXferState(){let{uploads:$,downloads:V}=this.store,Q=await $.count();return{numDownloads:await V.count(),numUploads:Q,progress:this.lastProgress}}apply=($,V)=>{return this.enqueueApplyJob(()=>this.doApply($,V))};async doApply($,V={enqueueUpload:!0,triggerUpload:!0}){let Q=[],Z=[];for(let{head:W,body:Y}of $){let X=new g;X.writeStruct(X0,W);let G=X.result(),K=await this.crypto.blake3(G),R={eid:W.eid,body:Y,apld:q0};if(W.off!==0)R.off=W.off;if(W.ctr!==0)R.ctr=W.ctr;Q.push(K),Z.push({key:K,data:R})}await this.store.messages.add(Z),await pQ(this.store,Q,this.crypto);let J=await this.doApplyHashes(Q);if(V.enqueueUpload){let W=[];for(let Y=0;Y<Q.length;Y++){let X=J[Y];if(X===0||X===15)W.push(Q[Y])}if(W.length>0){let Y=await this.store.hosts.list();for(let X of Y)await this.store.uploads.enq(X.label,W);this.xferState.emit()}}if(V.triggerUpload)this.scheduleSync();return J}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:q0});if($.length<1)return[];let V=t0($,(Q)=>Q.head);return this.applyStored(V)}applyHashes=($)=>{return this.enqueueApplyJob(()=>this.doApplyHashes($))};async doApplyHashes($){let V=[];for(let J of $){let W=await this.store.messages.get(J);if(W)V.push(W)}let Q=await this.applyStored(V),Z=new Map;for(let J=0;J<V.length;J++)Z.set(L(V[J].hash),Q[J]??12);return $.map((J)=>Z.get(L(J))??13)}async applyStored($){if($.length<1)return[];let V=$.map((W)=>({...W.head,bod:W.body})),Q=await this.state.apply(V),Z=[],J=[];for(let W=0;W<$.length;W++){let Y=Q[W];if(Y===0||Y===15)Z.push($[W].hash);else if(Y!==void 0&&LV(Y))J.push({key:$[W].hash,err:Y})}if(Z.length>0)await this.store.messages.markApplied(Z);if(J.length>0)await this.store.messages.markFailed(J);return Q}async insertRaw($){let{clock:V,crypto:Q}=this,[Z,J]=await fQ({now:V.now(),bod:$,crypto:Q});if(J!==0)return z(J);let Y=(await this.apply([{head:Z,body:$}]))[0];if(Y!==0&&Y!==15)return z(Y??12);return O(Z)}async makeUpdate($,V){let{clock:Q,crypto:Z}=this,J=Q.now();if($.updatedAt.getTime()>J.getTime())return z(4);let W=$.ctr+1,[Y,X]=await m$({now:J,eid:$.eid,ctr:W,bod:V,crypto:Z});if(X!==0)return z(X);return O({head:Y,body:V})}async updateWithSkew($,V,Q){if(Q===!1)return z(4);let{clock:Z,crypto:J}=this,W=Z.now(),Y=new k($.eid),[X,G]=Y.readStruct(o);if(G!==0)return z(G);let K=$.updatedAt.getTime()-X.ts.getTime(),R={eid:$.eid,off:K+1,ctr:$.ctr+1,len:0},N=(await this.apply([{head:R,body:void 0}]))[0];if(N!==0&&N!==15)return z(N??12);if(V===void 0)return O(R);let[U,M]=c0({id:X.id,ts:W});if(M!==0)return z(M);let[F,q]=await m$({now:W,eid:U,ctr:0,bod:V,crypto:J});if(q!==0)return z(q);let P=(await this.apply([{head:F,body:V}]))[0];if(P!==0&&P!==15)return z(P??12);return O(F)}async updateRaw($,V,Q=this.forceSkewHandlingByDefault){if($.updatedAt.getTime()>this.clock.now().getTime())return this.updateWithSkew($,V,Q);return this.enqueueApplyJob(async()=>{let[Z,J]=await this.makeUpdate($,V);if(J!==0)return z(J);let Y=(await this.doApply([Z]))[0];if(Y!==0&&Y!==15)return z(Y??12);return O(Z.head)})}async insert($){let{body:V,type:Q,gid:Z,pid:J,tags:W}=$,X=f0({body:V,type:Q,gid:Z,pid:J,tags:W});return this.insertRaw(X)}async update($){let{prior:V,body:Q,type:Z,gid:J,pid:W,tags:Y,force:X}=$,K=f0({body:Q,type:Z,gid:J,pid:W,tags:Y});return this.updateRaw(V,K,X??this.forceSkewHandlingByDefault)}async delete($){let V=$.force??!0;if("prior"in $)return this.updateRaw($.prior,void 0,V);let[Q,Z]=await this.revFromArchive($.eid);if(Z!==0)return z(Z);return this.updateRaw(Q,void 0,V)}async revFromArchive($){let V=await this.store.messages.last($);if(V)return _V(V.head);let Q=new k($),[Z,J]=Q.readStruct(o);if(J!==0)return z(J);return O({eid:$,ctr:-1,updatedAt:Z.ts})}async genEID($){let{clock:V,crypto:Q}=this,Z=V.now();if($!==void 0)return c0({id:$,ts:Z});let J=await Q.genRandomBytes(8);return c0({id:J,ts:Z})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:$,crypto:V,store:Q}=this,Z=await Q.seed.load();if(!Z)return 22;await this.drainApplyQueue();for(let[J,W]of $){let Y=await Q.hosts.get(J);if(!Y)continue;let X={conn:W,store:Q,enclave:Z,host:Y,crypto:V,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},G=await fV(X);if(G!==0)return console.error(`Failed to peek: ${G}`),this.emitProgress({phase:"idle"}),G;this.xferState.emit();let K=await nQ(X);if(K!==0)return console.error(`Failed to push: ${K}`),this.emitProgress({phase:"idle"}),K;this.xferState.emit();let R=await EV(X,async()=>{await this.drainApplyQueue()});if(R!==0&&R!==15)return console.error(`Failed to pull: ${R}`),this.emitProgress({phase:"idle"}),R;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async rebuild($){if(this.scheduledSync.cancel(),await this.syncRuns.flush(),$?.checkHost??!0){let Q=await this.repull();if(Q!==0)return Q}return this.enqueueApplyJob(()=>this.replay())}async msgcheck(){let $=await this.store.messages.listKeys();return d0($,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:Q,crypto:Z,store:J}=this,W=await J.seed.load();if(!W)return z(22);let Y=await J.hosts.get($);if(!Y)return z(13);let X=Q.get($);if(!X||!X.isConnected()){if(await this.connectToHost(Y,!1,!1),Y=await J.hosts.get($),!Y)return z(13);X=Q.get($)}if(!X)return z(12);let G={conn:X,store:J,enclave:W,crypto:Z,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},[K,R]=await mV({...G,host:Y},V);if(this.xferState.emit(),R!==0)return this.emitProgress({phase:"idle"}),z(R);if(!K)return this.emitProgress({phase:"idle"}),z(12);if(V?.sync===!1)return this.emitProgress({phase:"idle"}),O(K);let I=await this.sync();if(I!==0)return z(I);let N=await J.hosts.get($);if(!N)return z(13);let[U,M]=await mV({...G,host:N},{pull:!1,push:!1});if(this.xferState.emit(),this.emitProgress({phase:"idle"}),M!==0)return z(M);if(!U)return z(12);return O(U)}async repull(){let{connections:$,crypto:V,store:Q}=this,Z=await Q.seed.load();if(!Z)return 22;let J=Array.from(await Q.hosts.list());if(J.length<1)return 0;for(let W of J){let Y=$.get(W.label);if(!Y||!Y.isConnected())await this.connectToHost(W,!1,!1)}for(let[W,Y]of $){let X=await Q.hosts.get(W);if(!X)continue;let G={conn:Y,store:Q,enclave:Z,host:{...X,lastSeq:0},crypto:V,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},K=await fV(G);if(K!==0)return console.error(`rebuild: failed to peek: ${K}`),this.emitProgress({phase:"idle"}),K;this.xferState.emit();let R=await EV(G);if(R!==0&&R!==15)return console.error(`rebuild: failed to pull: ${R}`),this.emitProgress({phase:"idle"}),R;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(),Q=t0(V,(W)=>W.head),Z=Q.length;if(Z<1)return this.emitProgress({phase:"idle"}),0;let J=0;while(J<Q.length){let W=0,Y=0,X=J;for(let K=J;K<Q.length&&Y<100&&W<102400;K++)W+=Q[K].head.len,Y++,X=K+1;let G=Q.slice(J,X);await this.applyStored(G),this.emitProgress({phase:"exec",done:X,total:Z}),J=X}return this.emitProgress({phase:"idle"}),0}async wipe($){let V=$?.msgs!==!1,Q=$?.ents!==!1,Z=$?.meta!==!1,J=$?.seed===!0;this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush();let{store:W}=this;if(Z)await W.hosts.wipe(),await W.uploads.wipe(),await W.downloads.wipe();if(V)await W.messages.wipe();if(J)await W.seed.wipe();if(Q)await this.state.clear();this.lastProgress=E0,this.clientState.emit(),this.xferState.emit()}import=async($,V)=>{let{crypto:Q,store:Z}=this,J=V?.onProgress,W=await Z.seed.load();if(!W)return 22;console.time("import: decoding file...");let Y=await $.bytes(),[X,G]=await SQ(Y,Q,W);if(G!==0)return G;console.timeEnd("import: decoding file...");let K=0;while(K<X.length){let R=0,I=0,N=K;for(let F=K;F<X.length&&I<100&&R<102400;F++)R+=X[F].head.len,I++,N=F+1;let U=X.slice(K,N);console.time(`import: applying [${K}, ${N}]`);let M=await this.apply(U,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${K}, ${N}]`);for(let F=0;F<U.length;F++){let q=M[F];if(q!==0&&q!==15)console.warn(`failed to import msg ${K+F}: ${_[q]}`)}if(J)queueMicrotask(()=>J(N,X.length,0));this.emitProgress({phase:"import",done:N,total:X.length}),K=N}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,Q=await V.seed.load();if(!Q)return z(22);let Z=await V.messages.list();return xQ("export",0,Z,$,Q)}async export($){let[V,Q]=await this.exportBytes();if(Q!==0)return Q;if(!V)return 12;let Z=new Blob([V.slice()]);return u$(Z,$),0}async link($,V=!0){if(await this.store.hosts.add($),this.clientState.emit(),V){let Q=await this.store.hosts.get($.label);if(Q)await this.connectToHost(Q)}}async unlink($){await this.store.hosts.del($),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async($,V=!0,Q=!0)=>{let{clock:Z,connections:J,crypto:W,store:Y,transport:X}=this,G=J.get($.label);if(G){if(G.isConnected())return;try{G.closeListener()}catch{}J.delete($.label)}let K=await Y.seed.load();if(!K)return;console.info(`Connecting to ${$.handle} (${$.label})`);let R=new E$(K,W,$,Z,X($),(I)=>Y.hosts.set($.label,I));if(await R.register(),V)await R.listen(async(I)=>{let N={conn:R,store:Y,enclave:K,host:$,crypto:W,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return dQ(I,N,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(J.set($.label,R),this.clientState.emit(),Q)this.scheduleSync()};async connect($=!0,V=!0){let{connectToHost:Q,scheduleSync:Z,store:J}=this;if(!await J.seed.load())return;await this.drainApplyQueue();let Y=await J.hosts.list();for(let X of Y)await Q(X,$,!1);if(V)Z()}disconnect=async()=>{for(let $ of this.connections.values())try{$.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var k0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function h$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function BV($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function d($,...V){if(!BV($))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 rQ($,V){d($);let Q=V.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function gV($){if(typeof $!=="boolean")throw Error(`boolean expected, not ${$}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var H0=($)=>new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4));var fJ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!fJ)throw Error("Non little-endian hardware is not supported");function EJ($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function l$($){if(typeof $==="string")$=EJ($);else if(BV($))$=p$($);else throw Error("Uint8Array expected, got "+typeof $);return $}function oQ($,V){if(V==null||typeof V!=="object")throw Error("options must be defined");return Object.assign($,V)}function aQ($,V){if($.length!==V.length)return!1;let Q=0;for(let Z=0;Z<$.length;Z++)Q|=$[Z]^V[Z];return Q===0}var sQ=($,V)=>{function Q(Z,...J){if(d(Z),$.nonceLength!==void 0){let R=J[0];if(!R)throw Error("nonce / iv required");if($.varSizeNonce)d(R);else d(R,$.nonceLength)}let W=$.tagLength;if(W&&J[1]!==void 0)d(J[1]);let Y=V(Z,...J),X=(R,I)=>{if(I!==void 0){if(R!==2)throw Error("cipher output not supported");d(I)}},G=!1;return{encrypt(R,I){if(G)throw Error("cannot encrypt() twice with same key + nonce");return G=!0,d(R),X(Y.encrypt.length,I),Y.encrypt(R,I)},decrypt(R,I){if(d(R),W&&R.length<W)throw Error("invalid ciphertext length: smaller than tagLength="+W);return X(Y.decrypt.length,I),Y.decrypt(R,I)}}}return Object.assign(Q,$),Q};function vV($,V,Q=!0){if(V===void 0)return new Uint8Array($);if(V.length!==$)throw Error("invalid output length, expected "+$+", got: "+V.length);if(Q&&!mJ(V))throw Error("invalid output, must be aligned");return V}function mJ($){return $.byteOffset%4===0}function p$($){return Uint8Array.from($)}function U0(...$){for(let V=0;V<$.length;V++)$[V].fill(0)}function n$($=32){if(k0&&typeof k0.getRandomValues==="function")return k0.getRandomValues(new Uint8Array($));if(k0&&typeof k0.randomBytes==="function")return k0.randomBytes($);throw Error("crypto.getRandomValues must be defined")}var eQ=($)=>Uint8Array.from($.split("").map((V)=>V.charCodeAt(0))),BJ=eQ("expand 16-byte k"),kJ=eQ("expand 32-byte k"),gJ=H0(BJ),vJ=H0(kJ);function A($,V){return $<<V|$>>>32-V}function iV($){return $.byteOffset%4===0}var c$=64,iJ=16,$Z=4294967295,tQ=new Uint32Array;function yJ($,V,Q,Z,J,W,Y,X){let G=J.length,K=new Uint8Array(c$),R=H0(K),I=iV(J)&&iV(W),N=I?H0(J):tQ,U=I?H0(W):tQ;for(let M=0;M<G;Y++){if($(V,Q,Z,R,Y,X),Y>=$Z)throw Error("arx: counter overflow");let F=Math.min(c$,G-M);if(I&&F===c$){let q=M/4;if(M%4!==0)throw Error("arx: invalid block position");for(let C=0,P;C<iJ;C++)P=q+C,U[P]=N[P]^R[C];M+=c$;continue}for(let q=0,C;q<F;q++)C=M+q,W[C]=J[C]^K[q];M+=F}}function VZ($,V){let{allowShortKeys:Q,extendNonceFn:Z,counterLength:J,counterRight:W,rounds:Y}=oQ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},V);if(typeof $!=="function")throw Error("core must be a function");return h$(J),h$(Y),gV(W),gV(Q),(X,G,K,R,I=0)=>{d(X),d(G),d(K);let N=K.length;if(R===void 0)R=new Uint8Array(N);if(d(R),h$(I),I<0||I>=$Z)throw Error("arx: counter overflow");if(R.length<N)throw Error(`arx: output (${R.length}) is shorter than data (${N})`);let U=[],M=X.length,F,q;if(M===32)U.push(F=p$(X)),q=vJ;else if(M===16&&Q)F=new Uint8Array(32),F.set(X),F.set(X,16),q=gJ,U.push(F);else throw Error(`arx: invalid 32-byte key, got length=${M}`);if(!iV(G))U.push(G=p$(G));let C=H0(F);if(Z){if(G.length!==24)throw Error("arx: extended nonce must be 24 bytes");Z(q,C,H0(G.subarray(0,16)),C),G=G.subarray(16)}let P=16-J;if(P!==G.length)throw Error(`arx: nonce must be ${P} or 16 bytes`);if(P!==12){let H=new Uint8Array(12);H.set(G,W?0:12-G.length),G=H,U.push(G)}let T=H0(G);return yJ($,q,C,T,K,R,I,Y),U0(...U),R}}var s=($,V)=>$[V++]&255|($[V++]&255)<<8;class QZ{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,$=l$($),d($,32);let V=s($,0),Q=s($,2),Z=s($,4),J=s($,6),W=s($,8),Y=s($,10),X=s($,12),G=s($,14);this.r[0]=V&8191,this.r[1]=(V>>>13|Q<<3)&8191,this.r[2]=(Q>>>10|Z<<6)&7939,this.r[3]=(Z>>>7|J<<9)&8191,this.r[4]=(J>>>4|W<<12)&255,this.r[5]=W>>>1&8190,this.r[6]=(W>>>14|Y<<2)&8191,this.r[7]=(Y>>>11|X<<5)&8065,this.r[8]=(X>>>8|G<<8)&8191,this.r[9]=G>>>5&127;for(let K=0;K<8;K++)this.pad[K]=s($,16+2*K)}process($,V,Q=!1){let Z=Q?0:2048,{h:J,r:W}=this,Y=W[0],X=W[1],G=W[2],K=W[3],R=W[4],I=W[5],N=W[6],U=W[7],M=W[8],F=W[9],q=s($,V+0),C=s($,V+2),P=s($,V+4),T=s($,V+6),H=s($,V+8),D=s($,V+10),S=s($,V+12),B=s($,V+14),m=J[0]+(q&8191),f=J[1]+((q>>>13|C<<3)&8191),i=J[2]+((C>>>10|P<<6)&8191),w=J[3]+((P>>>7|T<<9)&8191),b=J[4]+((T>>>4|H<<12)&8191),l=J[5]+(H>>>1&8191),x=J[6]+((H>>>14|D<<2)&8191),v=J[7]+((D>>>11|S<<5)&8191),E=J[8]+((S>>>8|B<<8)&8191),y=J[9]+(B>>>5|Z),j=0,c=j+m*Y+f*(5*F)+i*(5*M)+w*(5*U)+b*(5*N);j=c>>>13,c&=8191,c+=l*(5*I)+x*(5*R)+v*(5*K)+E*(5*G)+y*(5*X),j+=c>>>13,c&=8191;let $0=j+m*X+f*Y+i*(5*F)+w*(5*M)+b*(5*U);j=$0>>>13,$0&=8191,$0+=l*(5*N)+x*(5*I)+v*(5*R)+E*(5*K)+y*(5*G),j+=$0>>>13,$0&=8191;let W0=j+m*G+f*X+i*Y+w*(5*F)+b*(5*M);j=W0>>>13,W0&=8191,W0+=l*(5*U)+x*(5*N)+v*(5*I)+E*(5*R)+y*(5*K),j+=W0>>>13,W0&=8191;let p=j+m*K+f*G+i*X+w*Y+b*(5*F);j=p>>>13,p&=8191,p+=l*(5*M)+x*(5*U)+v*(5*N)+E*(5*I)+y*(5*R),j+=p>>>13,p&=8191;let F0=j+m*R+f*K+i*G+w*X+b*Y;j=F0>>>13,F0&=8191,F0+=l*(5*F)+x*(5*M)+v*(5*U)+E*(5*N)+y*(5*I),j+=F0>>>13,F0&=8191;let i0=j+m*I+f*R+i*K+w*G+b*X;j=i0>>>13,i0&=8191,i0+=l*Y+x*(5*F)+v*(5*M)+E*(5*U)+y*(5*N),j+=i0>>>13,i0&=8191;let y0=j+m*N+f*I+i*R+w*K+b*G;j=y0>>>13,y0&=8191,y0+=l*X+x*Y+v*(5*F)+E*(5*M)+y*(5*U),j+=y0>>>13,y0&=8191;let u0=j+m*U+f*N+i*I+w*R+b*K;j=u0>>>13,u0&=8191,u0+=l*G+x*X+v*Y+E*(5*F)+y*(5*M),j+=u0>>>13,u0&=8191;let b0=j+m*M+f*U+i*N+w*I+b*R;j=b0>>>13,b0&=8191,b0+=l*K+x*G+v*X+E*Y+y*(5*F),j+=b0>>>13,b0&=8191;let h0=j+m*F+f*M+i*U+w*N+b*I;j=h0>>>13,h0&=8191,h0+=l*R+x*K+v*G+E*X+y*Y,j+=h0>>>13,h0&=8191,j=(j<<2)+j|0,j=j+c|0,c=j&8191,j=j>>>13,$0+=j,J[0]=c,J[1]=$0,J[2]=W0,J[3]=p,J[4]=F0,J[5]=i0,J[6]=y0,J[7]=u0,J[8]=b0,J[9]=h0}finalize(){let{h:$,pad:V}=this,Q=new Uint16Array(10),Z=$[1]>>>13;$[1]&=8191;for(let Y=2;Y<10;Y++)$[Y]+=Z,Z=$[Y]>>>13,$[Y]&=8191;$[0]+=Z*5,Z=$[0]>>>13,$[0]&=8191,$[1]+=Z,Z=$[1]>>>13,$[1]&=8191,$[2]+=Z,Q[0]=$[0]+5,Z=Q[0]>>>13,Q[0]&=8191;for(let Y=1;Y<10;Y++)Q[Y]=$[Y]+Z,Z=Q[Y]>>>13,Q[Y]&=8191;Q[9]-=8192;let J=(Z^1)-1;for(let Y=0;Y<10;Y++)Q[Y]&=J;J=~J;for(let Y=0;Y<10;Y++)$[Y]=$[Y]&J|Q[Y];$[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 W=$[0]+V[0];$[0]=W&65535;for(let Y=1;Y<8;Y++)W=($[Y]+V[Y]|0)+(W>>>16)|0,$[Y]=W&65535;U0(Q)}update($){kV(this);let{buffer:V,blockLen:Q}=this;$=l$($);let Z=$.length;for(let J=0;J<Z;){let W=Math.min(Q-this.pos,Z-J);if(W===Q){for(;Q<=Z-J;J+=Q)this.process($,J);continue}if(V.set($.subarray(J,J+W),this.pos),this.pos+=W,J+=W,this.pos===Q)this.process(V,0,!1),this.pos=0}return this}destroy(){U0(this.h,this.r,this.buffer,this.pad)}digestInto($){kV(this),rQ($,this),this.finished=!0;let{buffer:V,h:Q}=this,{pos:Z}=this;if(Z){V[Z++]=1;for(;Z<16;Z++)V[Z]=0;this.process(V,0,!0)}this.finalize();let J=0;for(let W=0;W<8;W++)$[J++]=Q[W]>>>0,$[J++]=Q[W]>>>8;return $}digest(){let{buffer:$,outputLen:V}=this;this.digestInto($);let Q=$.slice(0,V);return this.destroy(),Q}}function uJ($){let V=(Z,J)=>$(J).update(l$(Z)).digest(),Q=$(new Uint8Array(32));return V.outputLen=Q.outputLen,V.blockLen=Q.blockLen,V.create=(Z)=>$(Z),V}var yV=uJ(($)=>new QZ($));function bJ($,V,Q,Z,J,W=20){let Y=$[0],X=V[0],G=V[1],K=V[2],R=V[3],I=$[1],N=Q[0],U=Q[1],M=J,F=0,q=$[2],C=V[4],P=V[5],T=V[6],H=V[7],D=$[3],S=Y,B=X,m=G,f=K,i=R,w=I,b=N,l=U,x=M,v=F,E=q,y=C,j=P,c=T,$0=H,W0=D;for(let F0=0;F0<W;F0+=2)i^=A(S+j|0,7),x^=A(i+S|0,9),j^=A(x+i|0,13),S^=A(j+x|0,18),v^=A(w+B|0,7),c^=A(v+w|0,9),B^=A(c+v|0,13),w^=A(B+c|0,18),$0^=A(E+b|0,7),m^=A($0+E|0,9),b^=A(m+$0|0,13),E^=A(b+m|0,18),f^=A(W0+y|0,7),l^=A(f+W0|0,9),y^=A(l+f|0,13),W0^=A(y+l|0,18),B^=A(S+f|0,7),m^=A(B+S|0,9),f^=A(m+B|0,13),S^=A(f+m|0,18),b^=A(w+i|0,7),l^=A(b+w|0,9),i^=A(l+b|0,13),w^=A(i+l|0,18),y^=A(E+v|0,7),x^=A(y+E|0,9),v^=A(x+y|0,13),E^=A(v+x|0,18),j^=A(W0+$0|0,7),c^=A(j+W0|0,9),$0^=A(c+j|0,13),W0^=A($0+c|0,18);let p=0;Z[p++]=Y+S|0,Z[p++]=X+B|0,Z[p++]=G+m|0,Z[p++]=K+f|0,Z[p++]=R+i|0,Z[p++]=I+w|0,Z[p++]=N+b|0,Z[p++]=U+l|0,Z[p++]=M+x|0,Z[p++]=F+v|0,Z[p++]=q+E|0,Z[p++]=C+y|0,Z[p++]=P+j|0,Z[p++]=T+c|0,Z[p++]=H+$0|0,Z[p++]=D+W0|0}function hJ($,V,Q,Z){let J=$[0],W=V[0],Y=V[1],X=V[2],G=V[3],K=$[1],R=Q[0],I=Q[1],N=Q[2],U=Q[3],M=$[2],F=V[4],q=V[5],C=V[6],P=V[7],T=$[3];for(let D=0;D<20;D+=2)G^=A(J+q|0,7),N^=A(G+J|0,9),q^=A(N+G|0,13),J^=A(q+N|0,18),U^=A(K+W|0,7),C^=A(U+K|0,9),W^=A(C+U|0,13),K^=A(W+C|0,18),P^=A(M+R|0,7),Y^=A(P+M|0,9),R^=A(Y+P|0,13),M^=A(R+Y|0,18),X^=A(T+F|0,7),I^=A(X+T|0,9),F^=A(I+X|0,13),T^=A(F+I|0,18),W^=A(J+X|0,7),Y^=A(W+J|0,9),X^=A(Y+W|0,13),J^=A(X+Y|0,18),R^=A(K+G|0,7),I^=A(R+K|0,9),G^=A(I+R|0,13),K^=A(G+I|0,18),F^=A(M+U|0,7),N^=A(F+M|0,9),U^=A(N+F|0,13),M^=A(U+N|0,18),q^=A(T+P|0,7),C^=A(q+T|0,9),P^=A(C+q|0,13),T^=A(P+C|0,18);let H=0;Z[H++]=J,Z[H++]=K,Z[H++]=M,Z[H++]=T,Z[H++]=R,Z[H++]=I,Z[H++]=N,Z[H++]=U}var uV=VZ(bJ,{counterRight:!0,extendNonceFn:hJ}),bV=sQ({blockSize:64,nonceLength:24,tagLength:16},($,V)=>{return{encrypt(Q,Z){Z=vV(Q.length+32,Z,!1);let J=Z.subarray(0,32),W=Z.subarray(32);Z.set(Q,32),U0(J),uV($,V,Z,Z);let Y=yV(W,J);return Z.set(Y,16),U0(Z.subarray(0,16),Y),Z.subarray(16)},decrypt(Q,Z){d(Q),Z=vV(Q.length+32,Z,!1);let J=Z.subarray(0,32),W=Z.subarray(32,48),Y=Z.subarray(48);Z.set(Q,32),U0(J);let X=uV($,V,J,J),G=yV(Y,X);if(!aQ(W,G))throw Error("invalid tag");return uV($,V,Z.subarray(16),Z.subarray(16)),U0(J,W,G),Y}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function lJ($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function U$($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function g0($,...V){if(!lJ($))throw Error("Uint8Array expected");if(V.length>0&&!V.includes($.length))throw Error("Uint8Array expected of length "+V+", got length="+$.length)}function O$($,V=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(V&&$.finished)throw Error("Hash#digest() has already been called")}function d$($,V){g0($);let Q=V.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function ZZ($){return new Uint8Array($.buffer,$.byteOffset,$.byteLength)}function V$($){return new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4))}function Q$(...$){for(let V=0;V<$.length;V++)$[V].fill(0)}function F$($,V){return $<<32-V|$>>>V}var JZ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function WZ($){return $<<24&4278190080|$<<8&16711680|$>>>8&65280|$>>>24&255}var YZ=JZ?($)=>$:($)=>WZ($);function pJ($){for(let V=0;V<$.length;V++)$[V]=WZ($[V]);return $}var Z0=JZ?($)=>$:pJ;function nJ($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function Z$($){if(typeof $==="string")$=nJ($);return g0($),$}class hV{}function XZ($){let V=(Z,J)=>$(J).update(Z$(Z)).digest(),Q=$({});return V.outputLen=Q.outputLen,V.blockLen=Q.blockLen,V.create=(Z)=>$(Z),V}var GZ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var r$=BigInt(4294967295),KZ=BigInt(32);function lV($,V=!1){if(V)return{h:Number($&r$),l:Number($>>KZ&r$)};return{h:Number($>>KZ&r$)|0,l:Number($&r$)|0}}function P0($,V,Q,Z,J){return $=$+V+J|0,Z=F$(Z^$,16),Q=Q+Z|0,V=F$(V^Q,12),{a:$,b:V,c:Q,d:Z}}function C0($,V,Q,Z,J){return $=$+V+J|0,Z=F$(Z^$,8),Q=Q+Z|0,V=F$(V^Q,7),{a:$,b:V,c:Q,d:Z}}class pV extends hV{constructor($,V){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,U$($),U$(V),this.blockLen=$,this.outputLen=V,this.buffer=new Uint8Array($),this.buffer32=V$(this.buffer)}update($){O$(this),$=Z$($),g0($);let{blockLen:V,buffer:Q,buffer32:Z}=this,J=$.length,W=$.byteOffset,Y=$.buffer;for(let X=0;X<J;){if(this.pos===V)Z0(Z),this.compress(Z,0,!1),Z0(Z),this.pos=0;let G=Math.min(V-this.pos,J-X),K=W+X;if(G===V&&!(K%4)&&X+G<J){let R=new Uint32Array(Y,K,Math.floor((J-X)/4));Z0(R);for(let I=0;X+V<J;I+=Z.length,X+=V)this.length+=V,this.compress(R,I,!1);Z0(R);continue}Q.set($.subarray(X,X+G),this.pos),this.pos+=G,this.length+=G,X+=G}return this}digestInto($){O$(this),d$($,this);let{pos:V,buffer32:Q}=this;this.finished=!0,Q$(this.buffer.subarray(V)),Z0(Q),this.compress(Q,0,!0),Z0(Q);let Z=V$($);this.get().forEach((J,W)=>Z[W]=YZ(J))}digest(){let{buffer:$,outputLen:V}=this;this.digestInto($);let Q=$.slice(0,V);return this.destroy(),Q}_cloneInto($){let{buffer:V,length:Q,finished:Z,destroyed:J,outputLen:W,pos:Y}=this;return $||($=new this.constructor({dkLen:W})),$.set(...this.get()),$.buffer.set(V),$.destroyed=J,$.finished=Z,$.length=Q,$.pos=Y,$.outputLen=W,$}clone(){return this._cloneInto()}}function nV($,V,Q,Z,J,W,Y,X,G,K,R,I,N,U,M,F,q,C,P,T){let H=0;for(let D=0;D<Z;D++)({a:J,b:G,c:N,d:q}=P0(J,G,N,q,Q[V+$[H++]])),{a:J,b:G,c:N,d:q}=C0(J,G,N,q,Q[V+$[H++]]),{a:W,b:K,c:U,d:C}=P0(W,K,U,C,Q[V+$[H++]]),{a:W,b:K,c:U,d:C}=C0(W,K,U,C,Q[V+$[H++]]),{a:Y,b:R,c:M,d:P}=P0(Y,R,M,P,Q[V+$[H++]]),{a:Y,b:R,c:M,d:P}=C0(Y,R,M,P,Q[V+$[H++]]),{a:X,b:I,c:F,d:T}=P0(X,I,F,T,Q[V+$[H++]]),{a:X,b:I,c:F,d:T}=C0(X,I,F,T,Q[V+$[H++]]),{a:J,b:K,c:M,d:T}=P0(J,K,M,T,Q[V+$[H++]]),{a:J,b:K,c:M,d:T}=C0(J,K,M,T,Q[V+$[H++]]),{a:W,b:R,c:F,d:q}=P0(W,R,F,q,Q[V+$[H++]]),{a:W,b:R,c:F,d:q}=C0(W,R,F,q,Q[V+$[H++]]),{a:Y,b:I,c:N,d:C}=P0(Y,I,N,C,Q[V+$[H++]]),{a:Y,b:I,c:N,d:C}=C0(Y,I,N,C,Q[V+$[H++]]),{a:X,b:G,c:U,d:P}=P0(X,G,U,P,Q[V+$[H++]]),{a:X,b:G,c:U,d:P}=C0(X,G,U,P,Q[V+$[H++]]);return{v0:J,v1:W,v2:Y,v3:X,v4:G,v5:K,v6:R,v7:I,v8:N,v9:U,v10:M,v11:F,v12:q,v13:C,v14:P,v15:T}}var O0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},w0=GZ.slice(),zZ=(()=>{let $=Array.from({length:16},(Z,J)=>J),V=(Z)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((J)=>Z[J]),Q=[];for(let Z=0,J=$;Z<7;Z++,J=V(J))Q.push(...J);return Uint8Array.from(Q)})();class cV extends pV{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:Q,context:Z}=$,J=Z!==void 0;if(Q!==void 0){if(J)throw Error('Only "key" or "context" can be specified at same time');let W=Z$(Q).slice();g0(W,32),this.IV=V$(W),Z0(this.IV),this.flags=V|O0.KEYED_HASH}else if(J){let W=Z$(Z),Y=new cV({dkLen:32},O0.DERIVE_KEY_CONTEXT).update(W).digest();this.IV=V$(Y),Z0(this.IV),this.flags=V|O0.DERIVE_KEY_MATERIAL}else this.IV=w0.slice(),this.flags=V;this.state=this.IV.slice(),this.bufferOut=ZZ(this.bufferOut32)}get(){return[]}set(){}b2Compress($,V,Q,Z=0){let{state:J,pos:W}=this,{h:Y,l:X}=lV(BigInt($),!0),{v0:G,v1:K,v2:R,v3:I,v4:N,v5:U,v6:M,v7:F,v8:q,v9:C,v10:P,v11:T,v12:H,v13:D,v14:S,v15:B}=nV(zZ,Z,Q,7,J[0],J[1],J[2],J[3],J[4],J[5],J[6],J[7],w0[0],w0[1],w0[2],w0[3],Y,X,W,V);J[0]=G^q,J[1]=K^C,J[2]=R^P,J[3]=I^T,J[4]=N^H,J[5]=U^D,J[6]=M^S,J[7]=F^B}compress($,V=0,Q=!1){let Z=this.flags;if(!this.chunkPos)Z|=O0.CHUNK_START;if(this.chunkPos===15||Q)Z|=O0.CHUNK_END;if(!Q)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,Z,$,V),this.chunkPos+=1,this.chunkPos===16||Q){let J=this.state;this.state=this.IV.slice();for(let W,Y=this.chunksDone+1;Q||!(Y&1);Y>>=1){if(!(W=this.stack.pop()))break;this.buffer32.set(W,0),this.buffer32.set(J,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|O0.PARENT,this.buffer32,0),J=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(J)}this.pos=0}_cloneInto($){$=super._cloneInto($);let{IV:V,flags:Q,state:Z,chunkPos:J,posOut:W,chunkOut:Y,stack:X,chunksDone:G}=this;return $.state.set(Z.slice()),$.stack=X.map((K)=>Uint32Array.from(K)),$.IV.set(V),$.flags=Q,$.chunkPos=J,$.chunksDone=G,$.posOut=W,$.chunkOut=Y,$.enableXOF=this.enableXOF,$.bufferOut32.set(this.bufferOut32),$}destroy(){this.destroyed=!0,Q$(this.state,this.buffer32,this.IV,this.bufferOut32),Q$(...this.stack)}b2CompressOut(){let{state:$,pos:V,flags:Q,buffer32:Z,bufferOut32:J}=this,{h:W,l:Y}=lV(BigInt(this.chunkOut++));Z0(Z);let{v0:X,v1:G,v2:K,v3:R,v4:I,v5:N,v6:U,v7:M,v8:F,v9:q,v10:C,v11:P,v12:T,v13:H,v14:D,v15:S}=nV(zZ,0,Z,7,$[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],w0[0],w0[1],w0[2],w0[3],Y,W,V,Q);J[0]=X^F,J[1]=G^q,J[2]=K^C,J[3]=R^P,J[4]=I^T,J[5]=N^H,J[6]=U^D,J[7]=M^S,J[8]=$[0]^F,J[9]=$[1]^q,J[10]=$[2]^C,J[11]=$[3]^P,J[12]=$[4]^T,J[13]=$[5]^H,J[14]=$[6]^D,J[15]=$[7]^S,Z0(Z),Z0(J),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,Q$(this.buffer.subarray(this.pos));let $=this.flags|O0.ROOT;if(this.stack.length)$|=O0.PARENT,Z0(this.buffer32),this.compress(this.buffer32,0,!0),Z0(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else $|=(!this.chunkPos?O0.CHUNK_START:0)|O0.CHUNK_END;this.flags=$,this.b2CompressOut()}writeInto($){O$(this,!1),g0($),this.finish();let{blockLen:V,bufferOut:Q}=this;for(let Z=0,J=$.length;Z<J;){if(this.posOut>=V)this.b2CompressOut();let W=Math.min(V-this.posOut,J-Z);$.set(Q.subarray(this.posOut,this.posOut+W),Z),this.posOut+=W,Z+=W}return $}xofInto($){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto($)}xof($){return U$($),this.xofInto(new Uint8Array($))}digestInto($){if(d$($,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 RZ=XZ(($)=>new cV($));var dV=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function IZ($){let V=new Uint8Array(dV.length+32);return V.set(dV),V.set($.subarray(0,32),dV.length),V}function NZ($){return typeof $==="string"?new TextEncoder().encode($):$}function J$($){let V=new ArrayBuffer($.byteLength);return new Uint8Array(V).set($),V}class rV{verifyKeys=new Map;signKeys=new Map;async genRandomBytes($){return n$($)}async gen256BitSecureRandomSeed(){return n$(32)}async encryptXSalsa20Poly1305Combined($,V){let Q=n$(24),J=bV(V,Q).encrypt($);return new Uint8Array([...Q,...J])}async decryptXSalsa20Poly1305Combined($,V){let Q=$.slice(0,24),Z=$.slice(24);return bV(V,Q).decrypt(Z)}async deriveEd25519KeyPair($){let V=$,Q=IZ(V),Z=await globalThis.crypto.subtle.importKey("pkcs8",J$(Q),{name:"Ed25519"},!0,["sign"]),J=await globalThis.crypto.subtle.exportKey("jwk",Z);if(typeof J.x!=="string")throw Error("Ed25519 JWK missing x");let W=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:J.x},{name:"Ed25519"},!0,["verify"]),Y=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",W)),X=new Uint8Array(64);return X.set(V,0),X.set(Y,32),this.signKeys.set(t(V),Z),this.verifyKeys.set(t(Y),W),{keyType:"ed25519",privateKey:X,publicKey:Y}}async importSignKey($){let V=$.subarray(0,32),Q=t(V),Z=this.signKeys.get(Q);if(Z)return Z;let J=IZ(V),W=await globalThis.crypto.subtle.importKey("pkcs8",J$(J),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Q,W),W}async importVerifyKey($){let V=t($),Q=this.verifyKeys.get(V);if(Q)return Q;let Z=await globalThis.crypto.subtle.importKey("raw",J$($),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set(V,Z),Z}async signEd25519($,V){let Q=NZ($),Z=await this.importSignKey(V),J=await globalThis.crypto.subtle.sign({name:"Ed25519"},Z,J$(Q));return new Uint8Array(J)}async checkSigEd25519($,V,Q){let Z=NZ(V);try{let J=await this.importVerifyKey(Q);return await globalThis.crypto.subtle.verify({name:"Ed25519"},J,J$($),J$(Z))}catch{return!1}}async blake3($){return RZ($)}}var cJ=new rV,r=cJ;import{useEffect as s$,useState as VQ}from"react";class oV{db;constructor($){this.db=$}async enq($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(G0,"readwrite"),Z=Q.objectStore(G0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let Y of V){let X=`${Y.host}:${Y.seq}`;Z.put(Y,X)}})}async deq($,V){let Q=[...V];if(Q.length===0)return;let Z=this.db.transaction(G0,"readwrite"),J=Z.objectStore(G0);return new Promise((W,Y)=>{Z.oncomplete=()=>W(),Z.onerror=()=>Y(Z.error);for(let X of Q){let G=`${$}:${X}`;J.delete(G)}})}async list(){let V=this.db.transaction(G0,"readonly").objectStore(G0);return new Promise((Q,Z)=>{let J=V.getAll();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async count(){let V=this.db.transaction(G0,"readonly").objectStore(G0);return new Promise((Q,Z)=>{let J=V.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let $=this.db.transaction(G0,"readwrite"),V=$.objectStore(G0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}function UZ($){return{label:$.label,handle:new URL($.handle),idx:$.idx,lastSeq:$.lastSeq||0,clockOffset:$.clockOffset,subscription:$.subscription}}function dJ($,V){let Q={...$};if(V.setLastSeq!==void 0)Q.lastSeq=V.setLastSeq;else if(V.lastSeq!==void 0){let Z=Q.lastSeq||0;if(V.lastSeq>Z)Q.lastSeq=V.lastSeq}return delete Q.numBags,delete Q.numDupes,Q}class aV{db;constructor($){this.db=$}async add($){return this.put({...$,lastSeq:0})}async put($){let V={...$,handle:$.handle.toString(),lastSeq:$.lastSeq??0},Q=this.db.transaction(J0,"readwrite"),Z=Q.objectStore(J0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error),Z.put(V)})}async touch($,V){return this.recordStats($,{lastSeq:V})}async recordStats($,V){let Q=this.db.transaction(J0,"readwrite"),Z=Q.objectStore(J0);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);let Y=Z.get($);Y.onsuccess=()=>{let X=Y.result;if(!X)return;Z.put(dJ(X,V))}})}async get($){let Q=this.db.transaction(J0,"readonly").objectStore(J0);return new Promise((Z,J)=>{let W=Q.get($);W.onsuccess=()=>{let Y=W.result;if(!Y)Z(void 0);else Z(UZ(Y))},W.onerror=()=>J(W.error)})}async set($,V){let Q=await this.get($);if(!Q)return 13;try{return await this.put({...Q,...V}),0}catch{return 18}}async del($){let V=this.db.transaction(J0,"readwrite"),Q=V.objectStore(J0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),Q.delete($)})}async list(){let V=this.db.transaction(J0,"readonly").objectStore(J0);return new Promise((Q,Z)=>{let J=V.getAll();J.onsuccess=()=>{let W=J.result;Q(W.map(UZ))},J.onerror=()=>Z(J.error)})}async wipe(){let $=this.db.transaction(J0,"readwrite"),V=$.objectStore(J0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}class sV{crypto;db;constructor($,V){this.crypto=V;this.db=$}async add($){let V=this.db.transaction(h,"readwrite"),Q=V.objectStore(h);return new Promise((Z)=>{if($.length===0){Z([]);return}let J=Array($.length).fill(0);V.oncomplete=()=>Z(J),V.onerror=()=>{for(let W=0;W<J.length;W++)J[W]=18;Z(J)};for(let W=0;W<$.length;W++){let{key:Y,data:X}=$[W],G=L(Y),K=Q.put(X,G);K.onerror=(R)=>{R.preventDefault(),J[W]=18}}})}async del($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(h,"readwrite"),Z=Q.objectStore(h);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let Y of V){let X=L(Y);Z.delete(X)}})}async get($){let Q=this.db.transaction(h,"readonly").objectStore(h);return new Promise((Z,J)=>{let W=L($),Y=Q.get(W);Y.onsuccess=async()=>{let X=Y.result;if(X)Z(await S0($,X,this.crypto));else Z(void 0)},Y.onerror=()=>J(Y.error)})}async has($){return await this.get($)!==void 0}async list($){let V=$?.apld,Q=$?.body!==!1,J=this.db.transaction(h,"readonly").objectStore(h);return new Promise((W,Y)=>{let X=[],G=V===void 0?J.openCursor():J.index(M$).openCursor(IDBKeyRange.only(V));G.onsuccess=(K)=>{let R=K.target.result;if(R){let I=V===void 0?R.key:R.primaryKey,N=R.value;X.push({hash:Q0(I),data:N}),R.continue()}else Promise.all(X.map(({hash:I,data:N})=>S0(I,N,this.crypto,{body:Q}))).then(W).catch(Y)},G.onerror=()=>Y(G.error)})}async count($){let Q=this.db.transaction(h,"readonly").objectStore(h);return new Promise((Z,J)=>{let W=$===void 0?Q.count():Q.index(M$).count(IDBKeyRange.only($));W.onsuccess=()=>Z(W.result),W.onerror=()=>J(W.error)})}async listKeys(){let V=this.db.transaction(h,"readonly").objectStore(h);return new Promise((Q,Z)=>{let J=[],W=V.openKeyCursor();W.onsuccess=(Y)=>{let X=Y.target.result;if(X)J.push(Q0(X.key)),X.continue();else Q(J)},W.onerror=()=>Z(W.error)})}async last($){let Q=this.db.transaction(h,"readonly").objectStore(h);return new Promise((Z,J)=>{let W,Y=Q.openCursor();Y.onsuccess=async(X)=>{let G=X.target.result;if(G){let{key:K,value:R}=G;if(e($,R.eid)){if(!W||(R.ctr??0)>(W.data.ctr??0)||(R.ctr??0)===(W.data.ctr??0)&&(R.off??0)>(W.data.off??0))W={key:K,data:R}}G.continue()}else if(W){let K=Q0(W.key);Z(await S0(K,W.data,this.crypto))}else Z(void 0)},Y.onerror=()=>J(Y.error)})}async markApplied($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(h,"readwrite"),Z=Q.objectStore(h);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let Y of V){let X=L(Y),G=Z.get(X);G.onsuccess=()=>{let K=G.result;if(!K)return;m0(K,x0),Z.put(K,X)},G.onerror=(K)=>{K.preventDefault()}}})}async markFailed($){let V=[...$];if(V.length===0)return;let Q=this.db.transaction(h,"readwrite"),Z=Q.objectStore(h);return new Promise((J,W)=>{Q.oncomplete=()=>J(),Q.onerror=()=>W(Q.error);for(let{key:Y,err:X}of V){let G=L(Y),K=Z.get(G);K.onsuccess=()=>{let R=K.result;if(!R)return;m0(R,N0,X),Z.put(R,G)},K.onerror=(R)=>{R.preventDefault()}}})}async wipe(){let $=this.db.transaction(h,"readwrite"),V=$.objectStore(h);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}class R0{#V;#$;constructor($,V){this.#V=$,this.#$=V}deriveCipher($,V){let Q=$.slice(),Z=(Y)=>this.#Q(Q,Y),J=(Y)=>this.#Z(Q,Y);return{encrypt:Object.freeze({encrypt:Z}),decrypt:Object.freeze({decrypt:J}),both:Object.freeze({encrypt:Z,decrypt:J})}[V]}async deriveIdentity($,V=0){let Q=$,Z=V,J=await this.#W(Q,Z);return Object.freeze({publicKey:J.publicKey,sign:(W)=>this.#X(Q,Z,W),kdmFor:(W)=>this.#G(Q,Z,W)})}async#Q($,V){let Q=await this.#J($);return this.#$.encryptXSalsa20Poly1305Combined(V,Q)}async#Z($,V){let Q=await this.#J($);return this.#$.decryptXSalsa20Poly1305Combined(V,Q)}async#J($){return this.#$.blake3(j$(this.#V,$))}async#Y($,V){let Q=new TextEncoder().encode($),Z=new Uint8Array(8);return new DataView(Z.buffer).setBigUint64(0,BigInt(V),!1),await this.#J(j$(Q,Z))}async#W($,V){let Q=await this.#Y($,V);return this.#$.deriveEd25519KeyPair(Q)}async#X($,V,Q){let Z=await this.#W($,V);return this.#$.signEd25519(Q,Z.privateKey)}async#G($,V,Q){let Z=await this.#W($,V),J=j$(Z.privateKey,Q);return(await this.#$.blake3(J)).slice(0,_0)}}class tV{enclave;db;constructor($){this.db=$}async save($,V){if(V?.persist!==!0)return this.enclave=new R0($,r),this.enclave;let Q=t($),Z=this.db.transaction(T0,"readwrite"),J=Z.objectStore(T0);return new Promise((W,Y)=>{Z.oncomplete=()=>{this.enclave=new R0($,r),W(this.enclave)},Z.onerror=()=>Y(Z.error),J.put(Q,"seed")})}async load(){if(this.enclave)return this.enclave;let V=this.db.transaction(T0,"readonly").objectStore(T0);return new Promise((Q,Z)=>{let J=V.get("seed");J.onsuccess=()=>{let W=J.result;if(!W)Q(void 0);else{let Y=L0(W);this.enclave=new R0(Y,r),Q(this.enclave)}},J.onerror=()=>Z(J.error)})}async wipe(){this.enclave=void 0;let $=this.db.transaction(T0,"readwrite"),V=$.objectStore(T0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.put("","seed"),V.delete("seed")})}}class eV{db;constructor($){this.db=$}async enq($,V){let Q=[...V];if(Q.length===0)return;let Z=this.db.transaction(K0,"readwrite"),J=Z.objectStore(K0);return new Promise((W,Y)=>{Z.oncomplete=()=>W(),Z.onerror=()=>Y(Z.error);for(let X of Q){let G=t(X);J.put({host:$,hash:G})}})}async deq($,V){let Q=[...V];if(Q.length===0)return;let Z=this.db.transaction(K0,"readwrite"),J=Z.objectStore(K0);return new Promise((W,Y)=>{Z.oncomplete=()=>W(),Z.onerror=()=>Y(Z.error);for(let X of Q){let G=t(X);J.delete([$,G])}})}async list($){let Q=this.db.transaction(K0,"readonly").objectStore(K0);return new Promise((Z,J)=>{let W=Q.getAll();W.onsuccess=()=>{let X=W.result.filter((G)=>G.host===$).map((G)=>G.hash);Z(X.map((G)=>L0(G)))},W.onerror=()=>J(W.error)})}async count(){let V=this.db.transaction(K0,"readonly").objectStore(K0);return new Promise((Q,Z)=>{let J=V.count();J.onsuccess=()=>Q(J.result),J.onerror=()=>Z(J.error)})}async wipe(){let $=this.db.transaction(K0,"readwrite"),V=$.objectStore(K0);return new Promise((Q,Z)=>{$.oncomplete=()=>Q(),$.onerror=()=>Z($.error),V.clear()})}}var T0="seedMeta",J0="hosts",K0="uploadQueue",G0="downloadQueue",h="messages",M$="apld",OZ=3,FZ="diplomatic-store-db";class $Q{seed;hosts;uploads;downloads;messages;db;constructor($,V){this.db=$,this.seed=new tV($),this.hosts=new aV($),this.uploads=new eV($),this.downloads=new oV($),this.messages=new sV($,V)}async wipe(){await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function rJ(){return new Promise(($,V)=>{let Q=indexedDB.open(FZ,OZ);Q.onupgradeneeded=()=>{let{result:Z,transaction:J}=Q;if(!Z.objectStoreNames.contains(T0))Z.createObjectStore(T0);if(!Z.objectStoreNames.contains(J0))Z.createObjectStore(J0,{keyPath:"label"});if(!Z.objectStoreNames.contains(K0))Z.createObjectStore(K0,{keyPath:["host","hash"]});if(!Z.objectStoreNames.contains(G0))Z.createObjectStore(G0);let W;if(!Z.objectStoreNames.contains(h))W=Z.createObjectStore(h);else{if(!J)throw Error("missing upgrade transaction for messages store");W=J.objectStore(h)}if(!W.indexNames.contains(M$))W.createIndex(M$,"apld",{unique:!1})},Q.onblocked=()=>{console.warn(`[DIPLOMATIC] protocol store IDB upgrade blocked (${FZ} → v${OZ}); waiting for other connections to close`)},Q.onsuccess=()=>{let Z=Q.result;Z.onversionchange=()=>{Z.close()},$(Z)},Q.onerror=()=>V(Q.error??Error("protocol store IndexedDB open failed"))})}async function o$($){let V=await rJ();if(typeof navigator<"u"&&navigator.storage?.persist)try{await Promise.race([navigator.storage.persist(),new Promise((Q)=>{setTimeout(()=>Q(!1),2000)})])}catch{}return new $Q(V,$)}function MZ($){if(!$||typeof $!=="object")return!1;if(!("kind"in $))return!1;return typeof $.kind==="string"}function qZ($){if(typeof $!=="number")return;return $}function HZ($){if(!$||typeof $!=="object")return;if(!("hasSeed"in $)||!("hasHost"in $)||!("connected"in $))return;if(typeof $.hasSeed!=="boolean"||typeof $.hasHost!=="boolean"||typeof $.connected!=="boolean")return;return{hasSeed:$.hasSeed,hasHost:$.hasHost,connected:$.connected}}function oJ($){if(!$||typeof $!=="object")return;if(!("phase"in $))return;let V=aJ($.phase);if(V===void 0)return;let Q={phase:V};if("host"in $&&typeof $.host==="string")Q.host=$.host;if("done"in $&&typeof $.done==="number")Q.done=$.done;if("total"in $&&typeof $.total==="number")Q.total=$.total;if("bytesDone"in $&&typeof $.bytesDone==="number")Q.bytesDone=$.bytesDone;if("bytesTotal"in $&&typeof $.bytesTotal==="number")Q.bytesTotal=$.bytesTotal;return Q}function aJ($){if($==="peek"||$==="pull"||$==="open"||$==="exec"||$==="push"||$==="import"||$==="idle"||$==="apply")return $==="apply"?"exec":$;return}function PZ($){if(!$||typeof $!=="object")return;if(!("numUploads"in $)||!("numDownloads"in $))return;if(typeof $.numUploads!=="number"||typeof $.numDownloads!=="number")return;let V={phase:"idle"};if("progress"in $){let Q=oJ($.progress);if(Q===void 0)return;V=Q}return{numUploads:$.numUploads,numDownloads:$.numDownloads,progress:V}}var z0="[DIPLOMATIC]";class H${worker;state;store;local;nextId=1;pending=new Map;ready;resolveReady;rejectReady;scheduledSync;cachedClientState={hasSeed:!1,hasHost:!1,connected:!1};cachedXferState={numUploads:0,numDownloads:0,progress:E0};clientState;xferState;constructor($,V,Q,Z,J){this.worker=$,this.state=V,this.store=Q,this.clientState=new I0(async()=>this.cachedClientState),this.xferState=new I0(async()=>this.cachedXferState),this.scheduledSync=new N$(J,async()=>{try{await this.request({id:this.allocId(),op:"sync"})}catch(W){console.error(`${z0} worker sync after local write failed`,W)}}),this.local=new B0(Z,V,Q,()=>{throw Error(`${z0} local writer has no transport (use worker for network)`)},r,!0,void 0,void 0,()=>{this.scheduledSync.schedule()}),this.local.xferState.listen((W)=>{this.cachedXferState={numUploads:W.numUploads,numDownloads:W.numDownloads,progress:this.cachedXferState.progress},this.xferState.emit()}),this.ready=new Promise((W,Y)=>{this.resolveReady=W,this.rejectReady=Y}),this.worker.onmessage=(W)=>{this.onMessage(W.data)},this.worker.onerror=(W)=>{console.error(`${z0} worker error`,W),this.failReady(Error(`${z0} worker failed to load`))},this.worker.onmessageerror=()=>{this.failReady(Error(`${z0} worker message error`))}}failReady($){let V=this.rejectReady;if(this.rejectReady=void 0,this.resolveReady=void 0,V)V($)}async flushScheduledSync(){await this.scheduledSync.flush()}static async connect($,V,Q){let Z=Q.clock??new M0,J=Q.syncDebounceMs??i$,W=new H$(Q.worker,$,V,Z,J),Y=Q.readyTimeoutMs??15000,X;try{let G=W.probeReady();if(await Promise.race([W.ready,G,new Promise((K,R)=>{X=setTimeout(()=>{R(Error(`${z0} worker ready timeout after ${Y}ms`))},Y)})]),X!==void 0)clearTimeout(X),X=void 0;G.catch(()=>{}),await W.hydrateStateFromStore(V),await W.pullRemoteState()}catch(G){throw W.terminate(),G}finally{if(X!==void 0)clearTimeout(X)}return W}async hydrateStateFromStore($){let V=await $.seed.load(),Q=await $.hosts.list();this.cachedClientState={hasSeed:V!==void 0,hasHost:Array.from(Q).length>0,connected:!1};let Z=await $.uploads.count(),J=await $.downloads.count();this.cachedXferState={numUploads:Z,numDownloads:J,progress:E0}}async pullRemoteState(){let $=await this.request({id:this.allocId(),op:"getClientState"}),V=HZ($);if(V!==void 0)this.cachedClientState=V;let Q=await this.request({id:this.allocId(),op:"getXferState"}),Z=PZ(Q);if(Z!==void 0)this.cachedXferState=Z}markReady(){let $=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,$)$()}probeReady(){return new Promise(($,V)=>{let Q=this.allocId();this.pending.set(Q,{resolve:(Z)=>{if(Z==="pong"){this.markReady(),$();return}V(Error(`${z0} worker probe ping failed`))},reject:V}),this.worker.postMessage({id:Q,op:"ping"})})}async ping(){if(await this.ready,await this.request({id:this.allocId(),op:"ping"})!=="pong")throw Error(`${z0} worker ping failed`)}terminate(){this.scheduledSync.cancel(),this.worker.terminate();for(let[,$]of this.pending)$.reject(Error(`${z0} worker terminated`));this.pending.clear()}onMessage($){if(!MZ($))return;let V=$;switch(V.kind){case"ready":{this.markReady();return}case"initError":{this.failReady(Error(`${z0} worker init failed: ${V.message}`));return}case"clientState":{this.cachedClientState=V.state,this.clientState.emit();return}case"xferState":{this.cachedXferState=V.state,this.xferState.emit();return}case"dirty":{this.state.refresh(V.eids.map(tJ));return}case"wiped":{this.state.clear();return}case"reply":{let Q=this.pending.get(V.id);if(!Q)return;if(this.pending.delete(V.id),V.ok)Q.resolve(V.result);else Q.reject(new q$(V.status));return}default:return}}allocId(){let $=this.nextId;return this.nextId+=1,$}request($,V){return new Promise((Q,Z)=>{if(this.pending.set($.id,{resolve:Q,reject:Z}),V&&V.length>0)this.worker.postMessage($,V);else this.worker.postMessage($)})}async requestStatus($,V){try{let Q=await this.request($,V),Z=qZ(Q);if(Z!==void 0)return Z;return 0}catch(Q){if(Q instanceof q$)return Q.status;return 12}}serializeHost($){return{handle:$.handle.href,label:$.label,idx:$.idx??0}}async setSeed($,V){await this.ready,await this.local.setSeed($,V),this.cachedClientState={...this.cachedClientState,hasSeed:!0},this.clientState.emit();let Q=$.slice();await this.request({id:this.allocId(),op:"setSeed",seed:Q,persist:V?.persist},[Q.buffer])}async link($,V=!0){await this.ready,await this.local.link($,!1),await this.request({id:this.allocId(),op:"link",host:this.serializeHost($),connect:V})}async unlink($){await this.ready,await this.local.unlink($),await this.request({id:this.allocId(),op:"unlink",label:$})}async hosts(){return await this.ready,this.local.hosts()}async connect($=!0,V=!0){await this.ready,await this.request({id:this.allocId(),op:"connect",listen:$,sync:V})}async disconnect(){await this.ready,await this.request({id:this.allocId(),op:"disconnect"})}async insertRaw($){return await this.ready,this.local.insertRaw($)}async updateRaw($,V,Q){return await this.ready,this.local.updateRaw($,V,Q)}async insert($){return await this.ready,this.local.insert($)}async update($){return await this.ready,this.local.update($)}async delete($){return await this.ready,this.local.delete($)}async genEID($){return await this.ready,this.local.genEID($)}async sync(){return await this.ready,this.requestStatus({id:this.allocId(),op:"sync"})}async rebuild($){return await this.ready,this.scheduledSync.cancel(),await this.scheduledSync.flush(),this.requestStatus({id:this.allocId(),op:"rebuild",checkHost:$?.checkHost})}async listMsgs($){return await this.ready,this.local.listMsgs($)}async countMsgs($){return await this.ready,this.local.countMsgs($)}async reconcile($,V){await this.ready;try{let Q=await this.request({id:this.allocId(),op:"reconcile",hostLabel:$,pull:V?.pull,push:V?.push,sync:V?.sync});if(!sJ(Q))return z(12);return O(Q)}catch(Q){if(Q instanceof q$&&Q.status!==0)return z(Q.status);return z(12)}}async msgcheck(){await this.ready;let $=await this.request({id:this.allocId(),op:"msgcheck"});if(!($ instanceof Uint8Array))throw Error(`${z0} msgcheck: expected Uint8Array`);return $}async entcheck(){await this.ready;let $=await this.request({id:this.allocId(),op:"entcheck"});if(!($ instanceof Uint8Array))throw Error(`${z0} entcheck: expected Uint8Array`);return $}async wipe($){await this.ready,await this.local.wipe($),await this.request({id:this.allocId(),op:"wipe",msgs:$?.msgs,ents:$?.ents,meta:$?.meta,seed:$?.seed}),await this.hydrateStateFromStore(this.store),this.clientState.emit(),this.xferState.emit()}async import($){await this.ready;let V=new Uint8Array(await $.arrayBuffer());return this.requestStatus({id:this.allocId(),op:"import",bytes:V},[V.buffer])}async export($,V){await this.ready;try{let Q=await this.request({id:this.allocId(),op:"export"});if(!(Q instanceof Uint8Array))return 12;let Z=new Blob([Q.slice()]);return u$(Z,$),0}catch(Q){if(Q instanceof q$)return Q.status;return 12}}}class q$ extends Error{status;constructor($){super(`WorkerReplyError: ${_[$]}`);this.status=$;this.name="WorkerReplyError"}}function sJ($){if(!$||typeof $!=="object")return!1;let V=$;return V.msgcheck instanceof Uint8Array&&V.msgcheck.length===32&&typeof V.numBags==="number"&&typeof V.numDupes==="number"}function tJ($){return $}var v0="[DIPLOMATIC]";async function a$($){let V=$.clock??new M0;if($.worker!==void 0&&eJ($)!==void 0)throw Error(`${v0} worker path requires IndexedDB on both sides; do not pass store (got a custom store)`);if($.worker===void 0){console.info(`${v0} sync on main thread `+"(no worker — app did not request a worker)");let J=await CZ($.store);return $W(V,$.state,J)}if(typeof Worker>"u")throw Error(`${v0} worker was provided but Worker API is unavailable`);let Q=await CZ(void 0);console.info(`${v0} attaching app-provided sync worker…`);let Z=await H$.connect($.state,Q,{worker:$.worker,readyTimeoutMs:$.readyTimeoutMs,clock:V,syncDebounceMs:$.syncDebounceMs});return await Z.ping(),console.info(`${v0} sync worker active (network + EntDB writes off main; local mutates on main; dirty signals only)`),{client:Z,mode:"worker",dispose:()=>{console.info(`${v0} terminating sync worker`),Z.terminate()}}}function eJ($){if("store"in $)return $.store;return}async function $W($,V,Q){let Z=new B0($,V,Q,f$,r);return{client:Z,mode:"main",dispose:()=>{Z.disconnect()}}}async function CZ($){if($!==void 0)return $;if(typeof indexedDB>"u")throw Error(`${v0} IndexedDB is unavailable; pass store explicitly (e.g. new MemoryStore(crypto))`);return o$(r)}function VW($){let[V,Q]=VQ();return s$(()=>{async function Z(){let W=await $.clientState.get();Q(W)}let J=$.clientState.listen(Z);return Z(),()=>{J()}},[$]),V}function QW($){let[V,Q]=VQ();return s$(()=>{async function Z(){let W=await $.xferState.get();Q(W)}let J=$.xferState.listen(Z);return Z(),()=>{J()}},[$]),V}function ZW($){s$(()=>{async function V(){try{await $.connect(),await $.sync()}catch(W){console.error("reconnectAndSync failed",W)}}function Q(){V()}function Z(){if(typeof document<"u"&&document.visibilityState==="visible")V()}function J(){V()}if(globalThis.addEventListener("online",Q),typeof document<"u")document.addEventListener("visibilitychange",Z);return globalThis.addEventListener("focus",J),globalThis.addEventListener("pageshow",J),()=>{if(globalThis.removeEventListener("online",Q),typeof document<"u")document.removeEventListener("visibilitychange",Z);globalThis.removeEventListener("focus",J),globalThis.removeEventListener("pageshow",J)}},[$])}function JW($={}){let V=$.clock??new M0,{seed:Q,host:Z,readyTimeoutMs:J}=$,W=$.worker,Y="store"in $?$.store:void 0,[X,G]=VQ({stateMgr:HV});return s$(()=>{let K=!1,R;return(async()=>{let I=await DV();if(K)return;let N=g$(I),U=W!==void 0?await a$({state:N,clock:V,worker:W,readyTimeoutMs:J}):await a$({state:N,clock:V,store:Y,readyTimeoutMs:J});if(K){U.dispose();return}R=U.dispose;let{client:M,mode:F}=U;if(Q)await M.setSeed(Q);if(Z)await M.link(Z);if(K){R();return}G({client:M,entDB:I,stateMgr:N,mode:F,error:void 0})})().catch((I)=>{let N=I instanceof Error?I:Error(String(I));if(console.error("[DIPLOMATIC] useClient init failed",N),!K)G((U)=>({...U,client:void 0,error:N}))}),()=>{K=!0,R?.()}},[V,Q,Z,W,Y,J]),X}import{use as WW,useEffect as wZ,useRef as YW,useState as XW}from"react";function TZ($,V,Q){let[Z,J]=XW();return wZ(()=>{async function W(){let Y=await Q();J(Y)}return W(),$.on(V,W),()=>{$.off(V,W)}},[$,V,Q]),Z}function GW($,V,Q){let Z=YW(Q());return wZ(()=>{async function J(){Z.current=Q()}return $.on(V,J),()=>{$.off(V,J)}},[$,V,Q]),WW(Z.current)}function AZ($,V){return`${$}:${V}`}class QQ{queue=new Map;async enq($){for(let V of $){let Q=AZ(V.host,V.seq);this.queue.set(Q,V)}}async deq($,V){for(let Q of V){let Z=AZ($,Q);this.queue.delete(Z)}}async list(){let $=[];for(let V of this.queue.values())$.push(V);return $}async count(){return this.queue.size}async wipe(){this.queue.clear()}}function KW($,V){if(V.setLastSeq!==void 0)$.lastSeq=V.setLastSeq;else if(V.lastSeq!==void 0&&V.lastSeq>$.lastSeq)$.lastSeq=V.lastSeq}class ZQ{hosts=new Map;async add($){let V={...$,lastSeq:0};this.hosts.set($.label,V)}async touch($,V){await this.recordStats($,{lastSeq:V})}async recordStats($,V){let Q=this.hosts.get($);if(!Q)return;KW(Q,V),this.hosts.set($,{...Q})}async get($){return this.hosts.get($)}async set($,V){let Q=this.hosts.get($);if(!Q)return 13;return this.hosts.set($,{...Q,...V}),0}async del($){this.hosts.delete($)}async list(){return this.hosts.values()}async wipe(){this.hosts.clear()}}class JQ{crypto;messages=new Map;constructor($){this.crypto=$}async add($){let V=[];for(let{key:Q,data:Z}of $)this.messages.set(L(Q),Z),V.push(0);return V}async del($){for(let V of $)this.messages.delete(L(V))}async get($){let V=this.messages.get(L($));if(V)return await S0($,V,this.crypto);return}async has($){return this.messages.has(L($))}async list($){let V=$?.apld,Q=$?.body!==!1,Z=[];for(let[J,W]of this.messages){if(V!==void 0&&$$(W.apld)!==V)continue;let Y=Q0(J);Z.push(await S0(Y,W,this.crypto,{body:Q}))}return Z}async count($){if($===void 0)return this.messages.size;let V=0;for(let Q of this.messages.values())if($$(Q.apld)===$)V++;return V}async listKeys(){let $=[];for(let V of this.messages.keys())$.push(Q0(V));return $}async last($){let V;for(let[Q,Z]of this.messages){if(e($,Z.eid)===!1)continue;let J=Q0(Q);if(V===void 0)V={hash:J,data:Z};else if((Z.ctr??0)>(V.data.ctr??0)||(Z.ctr??0)===(V.data.ctr??0)&&(Z.off??0)>(V.data.off??0))V={hash:J,data:Z}}if(V)return await S0(V.hash,V.data,this.crypto);return}async markApplied($){for(let V of $){let Q=this.messages.get(L(V));if(!Q)continue;m0(Q,x0)}}async markFailed($){for(let{key:V,err:Q}of $){let Z=this.messages.get(L(V));if(!Z)continue;m0(Z,N0,Q)}}async wipe(){this.messages.clear()}}class WQ{enclave;async save($,V){return this.enclave=new R0($,r),this.enclave}async load(){return this.enclave}async wipe(){this.enclave=void 0}}class YQ{queue=new Map;async enq($,V){let Q=this.queue.get($)||new Set;this.queue.set($,Q);for(let Z of V)Q.add(t(Z))}async deq($,V){let Q=this.queue.get($);if(Q)for(let Z of V)Q.delete(t(Z))}async list($){let V=this.queue.get($);if(!V)return[];let Q=[];for(let Z of V)Q.push(L0(Z));return Q}async count(){let $=0;for(let V of this.queue.values())$+=V.size;return $}async wipe(){this.queue.clear()}}class DZ{seed=new WQ;hosts=new ZQ;uploads=new YQ;downloads=new QQ;messages;constructor($){this.messages=new JQ($)}async wipe(){await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}class _Z{singletonType;latest;latestOff=-1;emitter=new A0;constructor($){this.singletonType=$}async apply($){for(let V of $){let Q=new k(V.eid),[Z,J]=Q.readStruct(o);if(J!==0)continue;let W=new g;W.writeVarString(this.singletonType);let Y=W.result();if(Z.id.length===Y.length&&Z.id.every((X,G)=>X===Y[G])){if(this.latest===void 0||V.off>this.latestOff)this.latestOff=V.off,this.latest=V.bod,this.emitter.emit(this.singletonType,null)}}return $.map(()=>0)}clear=async()=>{return this.latest=void 0,this.latestOff=-1,this.emitter.emit(this.singletonType,null),0};notify=($)=>{for(let V of $)if(V===this.singletonType)this.emitter.emit(this.singletonType,null)};refresh=async($)=>{this.notify([this.singletonType])};on=($,V)=>{this.emitter.addEventListener($,V)};off=($,V)=>{this.emitter.removeEventListener($,V)}}var XQ=32,t$=32,zW=new Set(["co.uk","org.uk","ac.uk","gov.uk","com.au","net.au","org.au","co.nz","co.jp","com.br","com.mx","co.kr","com.sg","co.in","com.hk","github.io","pages.dev","workers.dev","web.app","firebaseapp.com","azurewebsites.net"]);function RW($){if(/^\d{1,3}(\.\d{1,3}){3}$/.test($))return!0;if($.includes(":"))return!0;return!1}function jZ($){let V=$.trim().toLowerCase().replace(/\.$/,"");if(V===""||V==="localhost"||V.endsWith(".localhost"))return V||"localhost";if(RW(V))return V;let Q=V.split(".").filter(Boolean);if(Q.length<=2)return V;let Z=`${Q[Q.length-2]}.${Q[Q.length-1]}`;if(zW.has(Z)&&Q.length>=3)return Q.slice(-3).join(".");return Z}function P$($){let V=new Uint8Array($);return crypto.getRandomValues(V),V}function IW($){let V=new Uint8Array($.byteLength);return V.set($),V}function GQ($){return IW($).buffer}function LZ($){if($.byteLength!==XQ)throw Error(`largeBlob: seed must be ${XQ} bytes`);return $}function e$($){if($?.rpId!==void 0)return $.rpId;if(typeof location>"u")throw Error("largeBlob: rpId required outside browser");return jZ(location.hostname)}function $V(){if(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")throw Error("largeBlob: WebAuthn unavailable")}function VV($){if($===null||$.type!=="public-key"||!("rawId"in $)||typeof $.getClientExtensionResults!=="function")throw Error("largeBlob: expected public-key credential");return $}function xZ(){if(typeof navigator>"u")return!1;let $=navigator.userAgent;if(/Chrom(e|ium)|Edg\/|EdgiOS|OPR\/|Firefox|FxiOS|CriOS|Android/.test($))return!1;if(/Safari\//.test($))return!0;return navigator.vendor==="Apple Computer, Inc."&&/AppleWebKit/.test($)}async function NW(){if(typeof PublicKeyCredential>"u")return!1;if(xZ())return!0;let $=PublicKeyCredential.getClientCapabilities;if(typeof $!=="function")return!0;let V=await $.call(PublicKeyCredential),Q="extension:largeBlob";if(Q in V)return V[Q]===!0;return!0}async function KQ($){$V();let V=$?.userName??"diplomatic-seed",Q={residentKey:"required",requireResidentKey:!0,userVerification:"required"};if($?.authenticatorAttachment!==void 0)Q.authenticatorAttachment=$.authenticatorAttachment;else if(xZ())Q.authenticatorAttachment="platform";let Z=await navigator.credentials.create({publicKey:{challenge:P$(t$),rp:{id:e$($),name:$?.rpName??"DIPLOMATIC"},user:{id:P$(16),name:V,displayName:V},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-8},{type:"public-key",alg:-257}],authenticatorSelection:Q,extensions:{largeBlob:{support:"preferred"}}}}),J=VV(Z);if(J.getClientExtensionResults().largeBlob?.supported!==!0)throw Error("largeBlob: unsupported by authenticator. Use Apple Passwords / iCloud Keychain (Safari platform) or a largeBlob-capable security key in Chrome. "+"An empty passkey may have been created — remove it in Passwords if listed.");return new Uint8Array(J.rawId)}async function QV($,V,Q){$V(),LZ(V);let Z=await navigator.credentials.get({publicKey:{challenge:P$(t$),rpId:e$(Q),allowCredentials:[{type:"public-key",id:GQ($)}],userVerification:"required",extensions:{largeBlob:{write:GQ(V)}}}});if(VV(Z).getClientExtensionResults().largeBlob?.written!==!0)throw Error("largeBlob: write not accepted. On Safari, create and write must be two separate button clicks. Confirm the passkey is iCloud Keychain / platform, not a manager without largeBlob.")}async function SZ($,V){let Q=new Uint8Array(XQ);await QV($,Q,V)}async function fZ($,V){return(await EZ($,V)).seed}async function EZ($,V){$V();let Q=await navigator.credentials.get({publicKey:{challenge:P$(t$),rpId:e$(V),allowCredentials:[{type:"public-key",id:GQ($)}],userVerification:"required",extensions:{largeBlob:{read:!0}}}});return mZ(VV(Q))}async function UW($){$V();let V=await navigator.credentials.get({publicKey:{challenge:P$(t$),rpId:e$($),userVerification:"required",extensions:{largeBlob:{read:!0}}}});return mZ(VV(V))}function mZ($){let V=$.getClientExtensionResults().largeBlob?.blob;if(V===void 0)throw Error("largeBlob: missing blob (credential has no seed storage, or largeBlob did not sync)");let Q=new Uint8Array(V);if(Q.every((Z)=>Z===0))throw Error("largeBlob: seed was cleared");return{seed:LZ(Q),credId:new Uint8Array($.rawId)}}async function OW($,V){let Q=await KQ(V);return await QV(Q,$,V),Q}class BZ{#V;#$;#Q;#Z;constructor($){if(this.#Q=$?.rpId,this.#Z=$?.rpName,$?.credId!==void 0)this.#$=$.credId.slice()}get credId(){if(this.#$===void 0)return;return this.#$.slice()}setCredId($){this.#$=$===void 0?void 0:$.slice()}async save($,V){if(V?.persist!==!0)return this.#V=new R0($,r),this.#V;let Q={rpId:this.#Q,rpName:this.#Z},Z=this.#$;if(Z===void 0)Z=await KQ(Q),this.#$=Z;return await QV(Z,$,Q),this.#V=new R0($,r),this.#V}async load(){return this.#V}async unlock(){let $=this.#$;if($===void 0)throw Error("largeBlob: no credential id");let V=await fZ($,{rpId:this.#Q});return this.#V=new R0(V,r),this.#V}async wipe(){let $=this.#$;if($!==void 0)await SZ($,{rpId:this.#Q});this.#V=void 0,this.#$=void 0}}async function H9($,V){let Q=await o$(r),Z=new B0(new M0,$,Q,f$,r);return{client:Z,setSeed:async(W)=>{let Y=L0(W);await Q.seed.save(Y),await Q.hosts.add({handle:V,label:"host",idx:0}),await Z.connect()}}}export{QV as writeLargeBlobSeed,ZW as useSyncOnResume,GW as useStateWatcherSuspense,TZ as useStateWatcher,QW as useClientXferState,VW as useClientState,JW as useClient,OW as storeSeedLargeBlob,y$ as shouldEmitItemProgress,m0 as setApld,_V as revFromHead,R$ as revFromEntity,EZ as readLargeBlobUnlock,fZ as readLargeBlobSeed,o$ as openIDBStore,DV as openEntDB,a$ as openDiplomaticClient,HV as nullStateManager,AJ as nullEntDB,iQ as normalizeTags,NW as largeBlobCapable,TJ as isTombstone,LV as isTerminalApplyFailure,jJ as isPendingApply,u as isLiveEnt,_J as isApldState,E0 as idleProgress,L0 as htob,f$ as hostHTTPTransport,H9 as genWebClient,XJ as genSingletonEID,g$ as entStateManager,mQ as encodeEntRev,o as eidCodec,UW as discoverLargeBlobSeed,jZ as defaultWebAuthnRpId,e0 as defaultPeekProgressEvery,r as crypto,KQ as createLargeBlobCred,EQ as cmpBytes,SZ as clearLargeBlobSeed,d0 as checksumSet,K$ as checksumEntRevs,t as btoh,L as btob64,Q0 as b64tob,$$ as apldFromStored,H$ as WorkerClient,A0 as TypedEventEmitter,B0 as SyncClient,_ as Status,z$ as StateManager,_Z as SingletonStateManager,BZ as PasskeySeedStore,DZ as MemoryStore,$Q as IDBStore,OV as HTTPTransport,AV as EntIDB,k$ as EntDBMemory,g as Encoder,k as Decoder,M0 as Clock,I$ as CachedEntDB,q0 as APLD_PENDING,N0 as APLD_ERROR,x0 as APLD_APPLIED};
@@ -5,6 +5,19 @@ export type LargeBlobRp = {
5
5
  rpId?: string;
6
6
  rpName?: string;
7
7
  };
8
+ /**
9
+ * Stable WebAuthn RP ID for a hostname: registrable domain (eTLD+1) when
10
+ * possible, else the hostname itself.
11
+ *
12
+ * Using the full hostname (e.g. life.example.com) scopes credentials to that
13
+ * host only. Safari/Apple Passwords often present the site as the apex domain;
14
+ * Chrome + security keys tend to store whatever rpId we pass. Defaulting to
15
+ * eTLD+1 keeps platform + roaming authenticators on the same RP ID across
16
+ * subdomains and browsers.
17
+ *
18
+ * localhost / IPs are returned unchanged (valid only for those origins).
19
+ */
20
+ export declare function defaultWebAuthnRpId(hostname: string): string;
8
21
  /**
9
22
  * Best-effort capability probe (not all UAs expose this accurately).
10
23
  *
@@ -24,13 +37,23 @@ export type LargeBlobCreateOpts = LargeBlobRp & {
24
37
  };
25
38
  /**
26
39
  * Create a discoverable credential with largeBlob support.
27
- * Does not write the seed — call {@link writeLargeBlobSeed} next (second gesture).
40
+ * Does **not** write the seed — call {@link writeLargeBlobSeed} from a
41
+ * **separate user gesture** (second click). Safari / WebKit will not reliably
42
+ * run two WebAuthn ceremonies from one button press; chaining create→write
43
+ * leaves empty passkeys (see blobviem / nsatragno largeBlob demos).
28
44
  *
29
- * Default allows platform *and* cross-platform authenticators. Forcing
30
- * `authenticatorAttachment: "platform"` excludes YubiKeys and similar.
45
+ * On Apple Safari, defaults to `authenticatorAttachment: "platform"` so
46
+ * iCloud Keychain is preferred (Apple largeBlob is platform-oriented).
47
+ * Pass `authenticatorAttachment: "cross-platform"` for security keys.
31
48
  */
32
49
  export declare function createLargeBlobCred(opts?: LargeBlobCreateOpts): Promise<Uint8Array>;
33
- /** Persist seed on an existing largeBlob-capable credential. */
50
+ /**
51
+ * Persist seed on an existing largeBlob-capable credential.
52
+ * Must be invoked from its **own** user gesture (not chained after create
53
+ * in the same click handler on Safari).
54
+ *
55
+ * Spec: allowCredentials must contain exactly one credential for write.
56
+ */
34
57
  export declare function writeLargeBlobSeed(credId: Uint8Array, seed: MasterSeed, opts?: LargeBlobRp): Promise<void>;
35
58
  /** Overwrite largeBlob with 32 zero bytes (destroys stored seed material). UV required. */
36
59
  export declare function clearLargeBlobSeed(credId: Uint8Array, opts?: LargeBlobRp): Promise<void>;
@@ -56,8 +79,13 @@ export declare function readLargeBlobUnlock(credId: Uint8Array, opts?: LargeBlob
56
79
  */
57
80
  export declare function discoverLargeBlobSeed(opts?: LargeBlobRp): Promise<LargeBlobUnlock>;
58
81
  /**
59
- * Create credential and write seed (two user gestures).
60
- * Returns credential id — persist it (e.g. IDB); the seed lives on the authenticator.
82
+ * Create credential then write seed in one call.
83
+ *
84
+ * **Safari/WebKit:** prefer {@link createLargeBlobCred} + {@link writeLargeBlobSeed}
85
+ * from **two separate clicks**. Chaining both after one gesture often creates a
86
+ * passkey without a blob (`written` false / later `missing blob` on read).
87
+ *
88
+ * Returns credential id — persist it; the seed lives on the authenticator.
61
89
  */
62
90
  export declare function storeSeedLargeBlob(seed: MasterSeed, opts?: LargeBlobCreateOpts): Promise<Uint8Array>;
63
91
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@interncom/diplomatic",
3
- "version": "0.11.2",
3
+ "version": "0.11.4",
4
4
  "type": "module",
5
5
  "description": "Secure sync layer and CLI utilities for DIPLOMATIC",
6
6
  "files": [