@interncom/diplomatic 0.4.2 → 0.4.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.
@@ -55,14 +55,28 @@ export type IOpened = {
55
55
  * Does not exec or push.
56
56
  */
57
57
  export declare function openPulled<Handle extends HostHandle>(store: IStore<Handle>, enclave: Enclave, crypto: ICrypto, items: IPulled[]): Promise<ValStat<IOpened>>;
58
+ /**
59
+ * Drop download-queue rows whose head matches archive keys we just stored
60
+ * (import / local apply). One list() + batched deq — not per-row messages.has.
61
+ */
62
+ export declare function deqDownloadsForHeadHashes<Handle extends HostHandle>(store: Pick<IStore<Handle>, "downloads">, hashes: Iterable<Hash>, crypto: ICrypto): Promise<void>;
58
63
  /** Discover unseen bags and enqueue download work; advance host lastSeq. */
59
64
  export declare function syncPeek<Handle extends HostHandle>({ conn, store, enclave, host, crypto, onProgress, peekProgressEvery, peekConcurrency, }: ISyncParams<Handle>): Promise<Status>;
65
+ /**
66
+ * Soft max plaintext body bytes per messages.getMany (IDB load bound).
67
+ * Sealed bags are larger; push still uses maxPushBytes on bag size.
68
+ */
69
+ export declare const defaultMaxGetBodyBytes: number;
60
70
  /** Seal and upload pending msgs; list once so concurrent enqs wait for next sync. */
61
- export declare function syncPush<Handle extends HostHandle>({ conn, store, host, maxPushBytes, onProgress }: ISyncParams<Handle>): Promise<Status>;
71
+ export declare function syncPush<Handle extends HostHandle>({ conn, store, host, maxPushBytes, onProgress, }: ISyncParams<Handle>): Promise<Status>;
62
72
  /**
63
73
  * Pull + open for one host, depth-1 pipelined:
64
74
  * await pull(i); start pull(i+1); open(i); afterOpen? (exec)
65
75
  * Ciphertext only in the in-flight Promise, never IDB.
76
+ *
77
+ * Download work is ordered newest→oldest by message HLC (not host seq).
78
+ * All bags are still pulled/opened; EntDB LWW already ignores obsolete ops.
79
+ * Newest-first exec reaches final app state early in a large catch-up.
66
80
  */
67
81
  export declare function syncPull<Handle extends HostHandle>({ conn, store, enclave, host, crypto, maxPullBytes, onProgress, }: ISyncParams<Handle>,
68
82
  /** After each opened pull batch (e.g. drainApplyQueue / exec). */
@@ -45,10 +45,16 @@ export interface IHostStore<Handle extends HostHandle> {
45
45
  wipe: () => Promise<void>;
46
46
  touch: (label: string, seq: number) => Promise<void>;
47
47
  }
48
+ /** Pending upload: archive key + plaintext body size for IDB get batching. */
49
+ export interface IUploadEntry {
50
+ hash: Hash;
51
+ /** Body byte length (0 if unknown / empty). */
52
+ bodyLen: number;
53
+ }
48
54
  export interface IUploadQueue {
49
- enq: (host: string, hshs: Iterable<Hash>) => Promise<void>;
55
+ enq: (host: string, entries: Iterable<IUploadEntry>) => Promise<void>;
50
56
  deq: (host: string, hshs: Iterable<Hash>) => Promise<void>;
51
- list: (host: string) => Promise<Hash[]>;
57
+ list: (host: string) => Promise<IUploadEntry[]>;
52
58
  count: () => Promise<number>;
53
59
  wipe(): Promise<void>;
54
60
  }
@@ -57,6 +63,15 @@ export interface IDownloadMessage {
57
63
  seq: number;
58
64
  head: IMessageHead;
59
65
  host: string;
66
+ /**
67
+ * Encoded message head from peek (or notif). When set, open skips re-encode.
68
+ * Prefer always setting this on the peek path.
69
+ */
70
+ headEnc?: Uint8Array;
71
+ /**
72
+ * blake3(headEnc). When set with headEnc, open skips re-hashing the head.
73
+ */
74
+ headEncHash?: Hash;
60
75
  }
61
76
  export interface IDownloadQueue {
62
77
  enq: (msgs: Iterable<IDownloadMessage>) => Promise<void>;
@@ -115,6 +130,11 @@ export declare function toStoredMessage(hash: Hash, data: IStoredMessageData, cr
115
130
  export interface IMessageStore {
116
131
  add: (messages: IStorableMessage[]) => Promise<Status[]>;
117
132
  get: (key: Hash) => Promise<IStoredMessage | undefined>;
133
+ /**
134
+ * Batch load by archive keys (one store round-trip when possible).
135
+ * Result aligned with input order; missing keys are undefined.
136
+ */
137
+ getMany: (keys: Iterable<Hash>) => Promise<(IStoredMessage | undefined)[]>;
118
138
  has: (key: Hash) => Promise<boolean>;
119
139
  del: (keys: Iterable<Hash>) => Promise<void>;
120
140
  list: () => Promise<Iterable<IStoredMessage>>;
@@ -1 +1 @@
1
- var F0=64;var q$=32,P0=8;var o0=32;var O$=30000,H$=512,j;((C)=>{C[C.Success=0]="Success";C[C.InvalidSignature=3]="InvalidSignature";C[C.ClockOutOfSync=4]="ClockOutOfSync";C[C.UserNotRegistered=5]="UserNotRegistered";C[C.ServerMisconfigured=6]="ServerMisconfigured";C[C.MissingBody=7]="MissingBody";C[C.ExtraBodyContent=8]="ExtraBodyContent";C[C.MissingParam=9]="MissingParam";C[C.InvalidParam=10]="InvalidParam";C[C.InvalidRequest=11]="InvalidRequest";C[C.InternalError=12]="InternalError";C[C.NotFound=13]="NotFound";C[C.InvalidMessage=14]="InvalidMessage";C[C.NoChange=15]="NoChange";C[C.DatabaseClosed=16]="DatabaseClosed";C[C.StorageError=17]="StorageError";C[C.DatabaseError=18]="DatabaseError";C[C.HashMismatch=19]="HashMismatch";C[C.DecryptionError=20]="DecryptionError";C[C.NotImplemented=21]="NotImplemented";C[C.MissingSeed=22]="MissingSeed";C[C.OutOfBounds=23]="OutOfBounds";C[C.HostError=24]="HostError";C[C.CommunicationError=25]="CommunicationError";C[C.VarLimitExceeded=26]="VarLimitExceeded";C[C.InvalidResponse=27]="InvalidResponse";C[C.ConnectionClosed=28]="ConnectionClosed"})(j||={});function C$(V){if(!V||typeof V!=="object")return!1;if(!("op"in V)||!("id"in V))return!1;return typeof V.op==="string"&&typeof V.id==="number"}function T$(V){let $=V.length,Z=0,J=0;while(J<$){let Q=V.charCodeAt(J++);if((Q&4294967168)===0){Z++;continue}else if((Q&4294965248)===0)Z+=2;else{if(Q>=55296&&Q<=56319){if(J<$){let W=V.charCodeAt(J);if((W&64512)===56320)++J,Q=((Q&1023)<<10)+(W&1023)+65536}}if((Q&4294901760)===0)Z+=3;else Z+=4}}return Z}function SZ(V,$,Z){let J=V.length,Q=Z,W=0;while(W<J){let Y=V.charCodeAt(W++);if((Y&4294967168)===0){$[Q++]=Y;continue}else if((Y&4294965248)===0)$[Q++]=Y>>6&31|192;else{if(Y>=55296&&Y<=56319){if(W<J){let X=V.charCodeAt(W);if((X&64512)===56320)++W,Y=((Y&1023)<<10)+(X&1023)+65536}}if((Y&4294901760)===0)$[Q++]=Y>>12&15|224,$[Q++]=Y>>6&63|128;else $[Q++]=Y>>18&7|240,$[Q++]=Y>>12&63|128,$[Q++]=Y>>6&63|128}$[Q++]=Y&63|128}}var xZ=new TextEncoder,BZ=50;function fZ(V,$,Z){xZ.encodeInto(V,$.subarray(Z))}function A$(V,$,Z){if(V.length>BZ)fZ(V,$,Z);else SZ(V,$,Z)}var mZ=4096;function CV(V,$,Z){let J=$,Q=J+Z,W=[],Y="";while(J<Q){let X=V[J++];if((X&128)===0)W.push(X);else if((X&224)===192){let G=V[J++]&63;W.push((X&31)<<6|G)}else if((X&240)===224){let G=V[J++]&63,K=V[J++]&63;W.push((X&31)<<12|G<<6|K)}else if((X&248)===240){let G=V[J++]&63,K=V[J++]&63,R=V[J++]&63,I=(X&7)<<18|G<<12|K<<6|R;if(I>65535)I-=65536,W.push(I>>>10&1023|55296),I=56320|I&1023;W.push(I)}else W.push(X);if(W.length>=mZ)Y+=String.fromCharCode(...W),W.length=0}if(W.length>0)Y+=String.fromCharCode(...W);return Y}var gZ=new TextDecoder,vZ=200;function iZ(V,$,Z){let J=V.subarray($,$+Z);return gZ.decode(J)}function D$(V,$,Z){if(Z>vZ)return iZ(V,$,Z);else return CV(V,$,Z)}class k0{type;data;constructor(V,$){this.type=V,this.data=$}}class a extends Error{constructor(V){super(V);let $=Object.create(a.prototype);Object.setPrototypeOf(this,$),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:a.name})}}var E0=4294967295;function _$(V,$,Z){let J=Z/4294967296,Q=Z;V.setUint32($,J),V.setUint32($+4,Q)}function a0(V,$,Z){let J=Math.floor(Z/4294967296),Q=Z;V.setUint32($,J),V.setUint32($+4,Q)}function s0(V,$){let Z=V.getInt32($),J=V.getUint32($+4);return Z*4294967296+J}function j$(V,$){let Z=V.getUint32($),J=V.getUint32($+4);return Z*4294967296+J}var bZ=-1,uZ=4294967295,yZ=17179869183;function nZ({sec:V,nsec:$}){if(V>=0&&$>=0&&V<=yZ)if($===0&&V<=uZ){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,V),Z}else{let Z=V/4294967296,J=V&4294967295,Q=new Uint8Array(8),W=new DataView(Q.buffer);return W.setUint32(0,$<<2|Z&3),W.setUint32(4,J),Q}else{let Z=new Uint8Array(12),J=new DataView(Z.buffer);return J.setUint32(0,$),a0(J,4,V),Z}}function pZ(V){let $=V.getTime(),Z=Math.floor($/1000),J=($-Z*1000)*1e6,Q=Math.floor(J/1e9);return{sec:Z+Q,nsec:J-Q*1e9}}function lZ(V){if(V instanceof Date){let $=pZ(V);return nZ($)}else return null}function hZ(V){let $=new DataView(V.buffer,V.byteOffset,V.byteLength);switch(V.byteLength){case 4:{let Z=$.getUint32(0),J=0;return{sec:Z,nsec:0}}case 8:{let Z=$.getUint32(0),J=$.getUint32(4),Q=(Z&3)*4294967296+J,W=Z>>>2;return{sec:Q,nsec:W}}case 12:{let Z=s0($,4),J=$.getUint32(0);return{sec:Z,nsec:J}}default:throw new a(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${V.length}`)}}function rZ(V){let $=hZ(V);return new Date($.sec*1000+$.nsec/1e6)}var L$={type:bZ,encode:lZ,decode:rZ};class S0{static defaultCodec=new S0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(L$)}register({type:V,encode:$,decode:Z}){if(V>=0)this.encoders[V]=$,this.decoders[V]=Z;else{let J=-1-V;this.builtInEncoders[J]=$,this.builtInDecoders[J]=Z}}tryToEncode(V,$){for(let Z=0;Z<this.builtInEncoders.length;Z++){let J=this.builtInEncoders[Z];if(J!=null){let Q=J(V,$);if(Q!=null){let W=-1-Z;return new k0(W,Q)}}}for(let Z=0;Z<this.encoders.length;Z++){let J=this.encoders[Z];if(J!=null){let Q=J(V,$);if(Q!=null)return new k0(Z,Q)}}if(V instanceof k0)return V;return null}decode(V,$,Z){let J=$<0?this.builtInDecoders[-1-$]:this.decoders[$];if(J)return J(V,$,Z);else return new k0($,V)}}function cZ(V){return V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer}function i0(V){if(V instanceof Uint8Array)return V;else if(ArrayBuffer.isView(V))return new Uint8Array(V.buffer,V.byteOffset,V.byteLength);else if(cZ(V))return new Uint8Array(V);else return Uint8Array.from(V)}var dZ=100,oZ=2048;class t0{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??S0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.maxDepth=V?.maxDepth??dZ,this.initialBufferSize=V?.initialBufferSize??oZ,this.sortKeys=V?.sortKeys??!1,this.forceFloat32=V?.forceFloat32??!1,this.ignoreUndefined=V?.ignoreUndefined??!1,this.forceIntegerToFloat=V?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new t0({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(V){if(this.entered)return this.clone().encodeSharedRef(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(V){if(this.entered)return this.clone().encode(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(V,$){if($>this.maxDepth)throw Error(`Too deep objects in depth ${$}`);if(V==null)this.encodeNil();else if(typeof V==="boolean")this.encodeBoolean(V);else if(typeof V==="number")if(!this.forceIntegerToFloat)this.encodeNumber(V);else this.encodeNumberAsFloat(V);else if(typeof V==="string")this.encodeString(V);else if(this.useBigInt64&&typeof V==="bigint")this.encodeBigInt64(V);else this.encodeObject(V,$)}ensureBufferSizeToWrite(V){let $=this.pos+V;if(this.view.byteLength<$)this.resizeBuffer($*2)}resizeBuffer(V){let $=new ArrayBuffer(V),Z=new Uint8Array($),J=new DataView($);Z.set(this.bytes),this.view=J,this.bytes=Z}encodeNil(){this.writeU8(192)}encodeBoolean(V){if(V===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber(V){if(!this.forceIntegerToFloat&&Number.isSafeInteger(V))if(V>=0)if(V<128)this.writeU8(V);else if(V<256)this.writeU8(204),this.writeU8(V);else if(V<65536)this.writeU8(205),this.writeU16(V);else if(V<4294967296)this.writeU8(206),this.writeU32(V);else if(!this.useBigInt64)this.writeU8(207),this.writeU64(V);else this.encodeNumberAsFloat(V);else if(V>=-32)this.writeU8(224|V+32);else if(V>=-128)this.writeU8(208),this.writeI8(V);else if(V>=-32768)this.writeU8(209),this.writeI16(V);else if(V>=-2147483648)this.writeU8(210),this.writeI32(V);else if(!this.useBigInt64)this.writeU8(211),this.writeI64(V);else this.encodeNumberAsFloat(V);else this.encodeNumberAsFloat(V)}encodeNumberAsFloat(V){if(this.forceFloat32)this.writeU8(202),this.writeF32(V);else this.writeU8(203),this.writeF64(V)}encodeBigInt64(V){if(V>=BigInt(0))this.writeU8(207),this.writeBigUint64(V);else this.writeU8(211),this.writeBigInt64(V)}writeStringHeader(V){if(V<32)this.writeU8(160+V);else if(V<256)this.writeU8(217),this.writeU8(V);else if(V<65536)this.writeU8(218),this.writeU16(V);else if(V<4294967296)this.writeU8(219),this.writeU32(V);else throw Error(`Too long string: ${V} bytes in UTF-8`)}encodeString(V){let Z=T$(V);this.ensureBufferSizeToWrite(5+Z),this.writeStringHeader(Z),A$(V,this.bytes,this.pos),this.pos+=Z}encodeObject(V,$){let Z=this.extensionCodec.tryToEncode(V,this.context);if(Z!=null)this.encodeExtension(Z);else if(Array.isArray(V))this.encodeArray(V,$);else if(ArrayBuffer.isView(V))this.encodeBinary(V);else if(typeof V==="object")this.encodeMap(V,$);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply(V)}`)}encodeBinary(V){let $=V.byteLength;if($<256)this.writeU8(196),this.writeU8($);else if($<65536)this.writeU8(197),this.writeU16($);else if($<4294967296)this.writeU8(198),this.writeU32($);else throw Error(`Too large binary: ${$}`);let Z=i0(V);this.writeU8a(Z)}encodeArray(V,$){let Z=V.length;if(Z<16)this.writeU8(144+Z);else if(Z<65536)this.writeU8(220),this.writeU16(Z);else if(Z<4294967296)this.writeU8(221),this.writeU32(Z);else throw Error(`Too large array: ${Z}`);for(let J of V)this.doEncode(J,$+1)}countWithoutUndefined(V,$){let Z=0;for(let J of $)if(V[J]!==void 0)Z++;return Z}encodeMap(V,$){let Z=Object.keys(V);if(this.sortKeys)Z.sort();let J=this.ignoreUndefined?this.countWithoutUndefined(V,Z):Z.length;if(J<16)this.writeU8(128+J);else if(J<65536)this.writeU8(222),this.writeU16(J);else if(J<4294967296)this.writeU8(223),this.writeU32(J);else throw Error(`Too large map object: ${J}`);for(let Q of Z){let W=V[Q];if(!(this.ignoreUndefined&&W===void 0))this.encodeString(Q),this.doEncode(W,$+1)}}encodeExtension(V){if(typeof V.data==="function"){let Z=V.data(this.pos+6),J=Z.length;if(J>=4294967296)throw Error(`Too large extension object: ${J}`);this.writeU8(201),this.writeU32(J),this.writeI8(V.type),this.writeU8a(Z);return}let $=V.data.length;if($===1)this.writeU8(212);else if($===2)this.writeU8(213);else if($===4)this.writeU8(214);else if($===8)this.writeU8(215);else if($===16)this.writeU8(216);else if($<256)this.writeU8(199),this.writeU8($);else if($<65536)this.writeU8(200),this.writeU16($);else if($<4294967296)this.writeU8(201),this.writeU32($);else throw Error(`Too large extension object: ${$}`);this.writeI8(V.type),this.writeU8a(V.data)}writeU8(V){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,V),this.pos++}writeU8a(V){let $=V.length;this.ensureBufferSizeToWrite($),this.bytes.set(V,this.pos),this.pos+=$}writeI8(V){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,V),this.pos++}writeU16(V){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,V),this.pos+=2}writeI16(V){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,V),this.pos+=2}writeU32(V){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,V),this.pos+=4}writeI32(V){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,V),this.pos+=4}writeF32(V){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,V),this.pos+=4}writeF64(V){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,V),this.pos+=8}writeU64(V){this.ensureBufferSizeToWrite(8),_$(this.view,this.pos,V),this.pos+=8}writeI64(V){this.ensureBufferSizeToWrite(8),a0(this.view,this.pos,V),this.pos+=8}writeBigUint64(V){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,V),this.pos+=8}writeBigInt64(V){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,V),this.pos+=8}}function e0(V,$){return new t0($).encodeSharedRef(V)}function VV(V){return`${V<0?"-":""}0x${Math.abs(V).toString(16).padStart(2,"0")}`}var aZ=16,sZ=16;class TV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(V=aZ,$=sZ){this.maxKeyLength=V,this.maxLengthPerKey=$,this.caches=[];for(let Z=0;Z<this.maxKeyLength;Z++)this.caches.push([])}canBeCached(V){return V>0&&V<=this.maxKeyLength}find(V,$,Z){let J=this.caches[Z-1];V:for(let Q of J){let W=Q.bytes;for(let Y=0;Y<Z;Y++)if(W[Y]!==V[$+Y])continue V;return Q.str}return null}store(V,$){let Z=this.caches[V.length-1],J={bytes:V,str:$};if(Z.length>=this.maxLengthPerKey)Z[Math.random()*Z.length|0]=J;else Z.push(J)}decode(V,$,Z){let J=this.find(V,$,Z);if(J!=null)return this.hit++,J;this.miss++;let Q=CV(V,$,Z),W=Uint8Array.prototype.slice.call(V,$,$+Z);return this.store(W,Q),Q}}var AV="array",u0="map_key",E$="map_value",tZ=(V)=>{if(typeof V==="string"||typeof V==="number")return V;throw new a("The type of key must be string or number but "+typeof V)};class S${stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(V){let $=this.getUninitializedStateFromPool();$.type=AV,$.position=0,$.size=V,$.array=Array(V)}pushMapState(V){let $=this.getUninitializedStateFromPool();$.type=u0,$.readCount=0,$.size=V,$.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let V={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(V)}return this.stack[this.stackHeadPosition]}release(V){if(this.stack[this.stackHeadPosition]!==V)throw Error("Invalid stack state. Released state is not on top of the stack.");if(V.type===AV){let Z=V;Z.size=0,Z.array=void 0,Z.position=0,Z.type=void 0}if(V.type===u0||V.type===E$){let Z=V;Z.size=0,Z.map=void 0,Z.readCount=0,Z.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var b0=-1,DV=new DataView(new ArrayBuffer(0)),eZ=new Uint8Array(DV.buffer);try{DV.getInt8(0)}catch(V){if(!(V instanceof RangeError))throw Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var k$=RangeError("Insufficient data"),VJ=new TV;class $V{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=DV;bytes=eZ;headByte=b0;stack=new S$;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??S0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.rawStrings=V?.rawStrings??!1,this.maxStrLength=V?.maxStrLength??E0,this.maxBinLength=V?.maxBinLength??E0,this.maxArrayLength=V?.maxArrayLength??E0,this.maxMapLength=V?.maxMapLength??E0,this.maxExtLength=V?.maxExtLength??E0,this.keyDecoder=V?.keyDecoder!==void 0?V.keyDecoder:VJ,this.mapKeyConverter=V?.mapKeyConverter??tZ}clone(){return new $V({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=b0,this.stack.reset()}setBuffer(V){let $=i0(V);this.bytes=$,this.view=new DataView($.buffer,$.byteOffset,$.byteLength),this.pos=0}appendBuffer(V){if(this.headByte===b0&&!this.hasRemaining(1))this.setBuffer(V);else{let $=this.bytes.subarray(this.pos),Z=i0(V),J=new Uint8Array($.length+Z.length);J.set($),J.set(Z,$.length),this.setBuffer(J)}}hasRemaining(V){return this.view.byteLength-this.pos>=V}createExtraByteError(V){let{view:$,pos:Z}=this;return RangeError(`Extra ${$.byteLength-Z} of ${$.byteLength} byte(s) found at buffer[${V}]`)}decode(V){if(this.entered)return this.clone().decode(V);try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);let $=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return $}finally{this.entered=!1}}*decodeMulti(V){if(this.entered){yield*this.clone().decodeMulti(V);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(V){if(this.entered)return this.clone().decodeAsync(V);try{this.entered=!0;let $=!1,Z;for await(let Y of V){if($)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(Y);try{Z=this.doDecodeSync(),$=!0}catch(X){if(!(X instanceof RangeError))throw X}this.totalPos+=this.pos}if($){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Z}let{headByte:J,pos:Q,totalPos:W}=this;throw RangeError(`Insufficient data in parsing ${VV(J)} at ${W} (${Q} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(V){return this.decodeMultiAsync(V,!0)}decodeStream(V){return this.decodeMultiAsync(V,!1)}async*decodeMultiAsync(V,$){if(this.entered){yield*this.clone().decodeMultiAsync(V,$);return}try{this.entered=!0;let Z=$,J=-1;for await(let Q of V){if($&&J===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(Q),Z)J=this.readArraySize(),Z=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--J===0)break}catch(W){if(!(W instanceof RangeError))throw W}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){V:while(!0){let V=this.readHeadByte(),$;if(V>=224)$=V-256;else if(V<192)if(V<128)$=V;else if(V<144){let J=V-128;if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V<160){let J=V-144;if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else{let J=V-160;$=this.decodeString(J,0)}else if(V===192)$=null;else if(V===194)$=!1;else if(V===195)$=!0;else if(V===202)$=this.readF32();else if(V===203)$=this.readF64();else if(V===204)$=this.readU8();else if(V===205)$=this.readU16();else if(V===206)$=this.readU32();else if(V===207)if(this.useBigInt64)$=this.readU64AsBigInt();else $=this.readU64();else if(V===208)$=this.readI8();else if(V===209)$=this.readI16();else if(V===210)$=this.readI32();else if(V===211)if(this.useBigInt64)$=this.readI64AsBigInt();else $=this.readI64();else if(V===217){let J=this.lookU8();$=this.decodeString(J,1)}else if(V===218){let J=this.lookU16();$=this.decodeString(J,2)}else if(V===219){let J=this.lookU32();$=this.decodeString(J,4)}else if(V===220){let J=this.readU16();if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else if(V===221){let J=this.readU32();if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else if(V===222){let J=this.readU16();if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V===223){let J=this.readU32();if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V===196){let J=this.lookU8();$=this.decodeBinary(J,1)}else if(V===197){let J=this.lookU16();$=this.decodeBinary(J,2)}else if(V===198){let J=this.lookU32();$=this.decodeBinary(J,4)}else if(V===212)$=this.decodeExtension(1,0);else if(V===213)$=this.decodeExtension(2,0);else if(V===214)$=this.decodeExtension(4,0);else if(V===215)$=this.decodeExtension(8,0);else if(V===216)$=this.decodeExtension(16,0);else if(V===199){let J=this.lookU8();$=this.decodeExtension(J,1)}else if(V===200){let J=this.lookU16();$=this.decodeExtension(J,2)}else if(V===201){let J=this.lookU32();$=this.decodeExtension(J,4)}else throw new a(`Unrecognized type byte: ${VV(V)}`);this.complete();let Z=this.stack;while(Z.length>0){let J=Z.top();if(J.type===AV)if(J.array[J.position]=$,J.position++,J.position===J.size)$=J.array,Z.release(J);else continue V;else if(J.type===u0){if($==="__proto__")throw new a("The key __proto__ is not allowed");J.key=this.mapKeyConverter($),J.type=E$;continue V}else if(J.map[J.key]=$,J.readCount++,J.readCount===J.size)$=J.map,Z.release(J);else{J.key=null,J.type=u0;continue V}}return $}}readHeadByte(){if(this.headByte===b0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=b0}readArraySize(){let V=this.readHeadByte();switch(V){case 220:return this.readU16();case 221:return this.readU32();default:if(V<160)return V-144;else throw new a(`Unrecognized array type byte: ${VV(V)}`)}}pushMapState(V){if(V>this.maxMapLength)throw new a(`Max length exceeded: map length (${V}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(V)}pushArrayState(V){if(V>this.maxArrayLength)throw new a(`Max length exceeded: array length (${V}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(V)}decodeString(V,$){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String(V,$);return this.decodeBinary(V,$)}decodeUtf8String(V,$){if(V>this.maxStrLength)throw new a(`Max length exceeded: UTF-8 byte length (${V}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+$+V)throw k$;let Z=this.pos+$,J;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached(V))J=this.keyDecoder.decode(this.bytes,Z,V);else J=D$(this.bytes,Z,V);return this.pos+=$+V,J}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===u0;return!1}decodeBinary(V,$){if(V>this.maxBinLength)throw new a(`Max length exceeded: bin length (${V}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(V+$))throw k$;let Z=this.pos+$,J=this.bytes.subarray(Z,Z+V);return this.pos+=$+V,J}decodeExtension(V,$){if(V>this.maxExtLength)throw new a(`Max length exceeded: ext length (${V}) > maxExtLength (${this.maxExtLength})`);let Z=this.view.getInt8(this.pos+$),J=this.decodeBinary(V,$+1);return this.extensionCodec.decode(J,Z,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let V=this.view.getUint8(this.pos);return this.pos++,V}readI8(){let V=this.view.getInt8(this.pos);return this.pos++,V}readU16(){let V=this.view.getUint16(this.pos);return this.pos+=2,V}readI16(){let V=this.view.getInt16(this.pos);return this.pos+=2,V}readU32(){let V=this.view.getUint32(this.pos);return this.pos+=4,V}readI32(){let V=this.view.getInt32(this.pos);return this.pos+=4,V}readU64(){let V=j$(this.view,this.pos);return this.pos+=8,V}readI64(){let V=s0(this.view,this.pos);return this.pos+=8,V}readU64AsBigInt(){let V=this.view.getBigUint64(this.pos);return this.pos+=8,V}readI64AsBigInt(){let V=this.view.getBigInt64(this.pos);return this.pos+=8,V}readF32(){let V=this.view.getFloat32(this.pos);return this.pos+=4,V}readF64(){let V=this.view.getFloat64(this.pos);return this.pos+=8,V}}function _V(V,$){return new $V($).decode(V)}class y0{listeners=new Map;addEventListener(V,$){let Z=this.listeners.get(V);if(!Z)Z=new Set,this.listeners.set(V,Z);return Z.add($),()=>{this.removeEventListener(V,$)}}removeEventListener(V,$){let Z=this.listeners.get(V);if(Z){if(Z.delete($),Z.size===0)this.listeners.delete(V)}}emit(V,$){let Z=this.listeners.get(V);if(Z){let J=Array.from(Z);for(let Q of J)Q($)}}emitAll(V){let $=Array.from(this.listeners.keys());for(let Z of $)this.emit(Z,V)}}class q0{getter;static eventName="update";emitter;constructor(V){this.getter=V;this.emitter=new y0}get=()=>this.getter();async emit(){let V=await this.getter();queueMicrotask(()=>this.emitter.emit(q0.eventName,V))}listen(V){return this.emitter.addEventListener(q0.eventName,V),()=>{this.emitter.removeEventListener(q0.eventName,V)}}}function O(V){return[V,0]}function N(V){return[void 0,V]}function $J(V){if(V<0)console.info("N",V),console.trace();if(typeof V!=="bigint")V=BigInt(V);if(V<0n)return N(10);let $=[];while(V>0n){let Z=Number(V&0x7fn);if(V>>=7n,V>0n)$.push(Z|128);else $.push(Z)}if($.length===0)return O(new Uint8Array([0]));if($.length>8)return N(26);return O(new Uint8Array($))}function ZJ(V,$=0){let Z=0n,J=0,Q=$;while(!0){if(Q>=V.length)return N(14);let W=V[Q++];if(W===void 0)return N(14);if(Z|=BigInt(W&127)<<BigInt(J),(W&128)===0){if(Q-$>8)return N(26);return O({value:Z>0x1fffffffffffffn?Z:Number(Z),bytesRead:Q-$})}if(J+=7,J>=56)return N(26)}}class m{data;pos=0;constructor(V){this.data=V}static async fromResponse(V){let $=await V.arrayBuffer(),Z=new Uint8Array($);return new m(Z)}readBigInt(){if(this.pos+8>this.data.length)return N(7);let V=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,O(V)}readDate(){let[V,$]=this.readVarInt();if($!==0)return N($);return O(new Date(V))}readVarInt(){let[V,$]=ZJ(this.data,this.pos);if($!==0)return N($);this.pos+=V.bytesRead;let Z=V.value;return O(typeof Z==="bigint"?Number(Z):Z)}readVarString(){let[V,$]=this.readVarInt();if($!==0)return N($);let[Z,J]=this.readBytes(V);if(J!==0)return N(J);let Q=new TextDecoder().decode(Z);return O(Q)}readBytes(V){if(V<0)return N(10);if(this.pos+V>this.data.length)return N(23);let $=this.data.slice(this.pos,this.pos+V);return this.pos+=V,O($)}readVarBytes(){let[V,$]=this.readVarInt();if($!==0)return N($);return this.readBytes(V)}readStruct(V){return V.decode(this)}readStructs(V){let $=[];while(!this.done()){let[Z,J]=this.readStruct(V);if(J!==0)return N(J);$.push(Z)}return O($)}readBytesSeq(V){let $=[];while(!this.done()){let[Z,J]=this.readBytes(V);if(J!==0)return N(J);$.push(Z)}return O($)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class B{parts=[];writeBigInt(V){let $=new Uint8Array(8);new DataView($.buffer).setBigUint64(0,V,!1),this.parts.push($)}writeDate(V){let $=V.getTime();return this.writeVarInt($)}writeVarInt(V){let[$,Z]=$J(V);if(Z!==0)return Z;return this.parts.push($),0}writeVarString(V){let $=new TextEncoder().encode(V),Z=this.writeVarInt($.length);if(Z!==0)return Z;return this.writeBytes($),0}prependBytes(V){this.parts.unshift(V)}writeBytes(V){this.parts.push(V)}writeVarBytes(V){let $=this.writeVarInt(V.length);if($!==0)return $;return this.writeBytes(V),0}writeStruct(V,$){return V.encode(this,$)}writeStructs(V,$){for(let Z of $){let J=this.writeStruct(V,Z);if(J!==0)return J}return 0}writeBytesSeq(V){for(let $ of V)this.writeBytes($)}result(){let V=this.parts.reduce((J,Q)=>J+Q.length,0),$=new Uint8Array(V),Z=0;for(let J of this.parts)$.set(J,Z),Z+=J.length;return $}*scan(){for(let V of this.parts)yield V}}async function jV(V,$,Z){let J=new B,Q=J.writeDate($);if(Q!==0)return N(Q);let W=J.result(),Y=await Z.signEd25519(W,V.privateKey);return O({pubKey:V.publicKey,sig:Y,timestamp:$})}async function U0(V,$,Z){let J=Z.now().getTime(),Q=V.timestamp.getTime();if(Math.abs(J-Q)>O$)return 4;let Y=new B;Y.writeDate(V.timestamp);let X=Y.result();if(!await $.checkSigEd25519(V.sig,X,V.pubKey))return 3;return 0}var Y0={encode(V,$){let Z=V.writeVarBytes($.id);if(Z!==0)return Z;let J=V.writeDate($.ts);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return N(Z);let[J,Q]=V.readDate();if(Q!==0)return N(Q);return O({id:$,ts:J})}};function ZV(V){let $=new B,Z=$.writeStruct(Y0,V);if(Z!==0)return N(Z);let J=$.result();return O(J)}var J0={encode(V,$){let Z=V.writeVarBytes($.eid);if(Z!==0)return Z;let J=V.writeVarInt($.off);if(J!==0)return J;let Q=V.writeVarInt($.ctr);if(Q!==0)return Q;let W=V.writeVarInt($.len);if(W!==0)return W;if($.hsh)V.writeBytes($.hsh);return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return N(Z);let J=new m($),[,Q]=Y0.decode(J);if(Q!==0)return N(Q);let[W,Y]=V.readVarInt();if(Y!==0)return N(Y);let[X,G]=V.readVarInt();if(G!==0)return N(G);let[K,R]=V.readVarInt();if(R!==0)return N(R);let I;if(K>0){let[z,M]=V.readBytes(o0);if(M!==0)return N(M);I=z}return O({eid:$,off:W,ctr:X,len:K,hsh:I})}};function Q0(V){return Array.from(V).map((Z)=>Z.toString(16).padStart(2,"0")).join("")}function JV(V){if(V.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(V.length/2);for(let Z=0;Z<V.length;Z+=2)$[Z/2]=Number.parseInt(V.substr(Z,2),16);return $}function O0(V,$){if(V===$)return!0;if(V.byteLength!==$.byteLength)return!1;return V.every((Z,J)=>Z===$[J])}var d;if(typeof Uint8Array.prototype.toBase64==="function")d=(V)=>V.toBase64();else d=(V)=>btoa(String.fromCharCode(...V));var R0;if(typeof Uint8Array.fromBase64==="function")R0=(V)=>Uint8Array.fromBase64(V);else R0=(V)=>Uint8Array.from(atob(V),($)=>$.charCodeAt(0));function n0(V,$){let Z=new Uint8Array(V.length+$.length);return Z.set(V,0),Z.set($,V.length),Z}function x$(V,$,Z){return Z.checkSigEd25519(V.sig,V.headCph,$)}async function LV(V,$,Z){let J=n0($.privateKey,V);return(await Z.blake3(J)).slice(0,P0)}async function B$(V,$,Z,J){let Q;if(V.bod&&V.len>0)Q=await Z.blake3(V.bod);let W=new B,Y=J0.encode(W,{...V,hsh:Q});if(Y!==0)return N(Y);let X=W.result(),G=await LV(X,$,Z),K=await J.deriveFromKDM(G),R=await Z.encryptXSalsa20Poly1305Combined(X,K),I=V.bod?await Z.encryptXSalsa20Poly1305Combined(V.bod,K):new Uint8Array(0),z=await Z.signEd25519(R,$.privateKey);return O({sig:z,kdm:G,headCph:R,bodyCph:I})}async function kV(V,$,Z,J){let Q=new m(V),[W,Y]=J0.decode(Q);if(Y!==0)return N(14);let X;try{X=$&&$.length>0?await J.decryptXSalsa20Poly1305Combined($,Z):void 0}catch{return N(20)}let G=W.hsh&&X===void 0,K=W.hsh===void 0&&X!==void 0;if(G||K)return N(19);if(W.hsh&&X){let I=await J.blake3(X);if(!O0(I,W.hsh))return N(19)}let R=await J.blake3(V);return O({msgHead:W,bod:X,headHash:R})}class EV{now(){return new Date}}function f$(V,$,Z,J){let Q=$.getTime()-V.getTime(),W=Z.getTime()-J.getTime();return(Q+W)/2}var p0={encode(V,$){if(V.writeVarInt($.quota),$.quota>0){if($.usage===void 0)return 9;V.writeVarInt($.usage)}return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return N(Z);let J;if($>0){let[Q,W]=V.readVarInt();if(W!==0)return N(W);J=Q}return O({quota:$,usage:J})}};var SV={encode(V,$){V.writeBytes(new Uint8Array([$.status]));let Z=V.writeDate($.timeRcvd);if(Z!==0)return Z;let J=V.writeDate($.timeSent);if(J!==0)return J;let Q=V.writeVarInt($.subscription.term);if(Q!==0)return Q;let W=V.writeVarInt($.subscription.elapsed);if(W!==0)return W;let Y=V.writeStruct(p0,$.subscription.stat);if(Y!==0)return Y;let X=V.writeStruct(p0,$.subscription.dyn);if(X!==0)return X;return 0},decode(V){let[$,Z]=V.readBytes(1);if(Z!==0)return N(Z);let J=$[0],[Q,W]=V.readDate();if(W!==0)return N(W);let[Y,X]=V.readDate();if(X!==0)return N(X);let[G,K]=V.readVarInt();if(K!==0)return N(K);let[R,I]=V.readVarInt();if(I!==0)return N(I);let[z,M]=V.readStruct(p0);if(M!==0)return N(M);let[F,w]=V.readStruct(p0);if(w!==0)return N(w);return O({status:J,timeRcvd:Q,timeSent:Y,subscription:{term:G,elapsed:R,stat:z,dyn:F}})}};async function xV(V,$,Z){let{crypto:J,enclave:Q}=V,W=await Q.derive($,Z);return await J.deriveEd25519KeyPair(W)}var BV={encode(V,$){let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarInt($.seq);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return N(Z);let[J,Q]=V.readVarInt();if(Q!==0)return N(Q);return O({headCph:$,seq:J})}};var V0={encode(V,$){V.writeBytes($.pubKey),V.writeBytes($.sig);let Z=V.writeDate($.timestamp);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readBytes(q$);if(Z!==0)return N(Z);let[J,Q]=V.readBytes(F0);if(Q!==0)return N(Q);let[W,Y]=V.readDate();if(Y!==0)return N(Y);return O({pubKey:$,sig:J,timestamp:W})}};var m$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(V0,Z);if(W!==0)return W;for(let Y of J)Q.writeVarInt(Y);return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(V0);if(X!==0)return X;let G=await U0(Y,Q,J);if(G!==0)return G;let{pubKey:K}=Y,[R,I]=await W.hasUser(K);if(I!==0)return I;if(!R)return 5;let[z,M]=$.readVarInt();if(M!==0)return M;if(!$.done())return 8;let[F,w]=await W.listHeads(K,z);if(w!==0)return w;return Z.writeStructs(BV,F)},decodeResp(V){return V.readStructs(BV)}};var fV={encode(V,$){V.writeVarInt($.seq);let Z=V.writeVarBytes($.bodyCph);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return N(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return N(Q);return O({seq:$,bodyCph:J})}};var g$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(V0,Z);if(W!==0)return W;for(let Y of J){let X=Q.writeVarInt(Y);if(X!==0)return X}return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(V0);if(X!==0)return X;let G=await U0(Y,Q,J);if(G!==0)return G;let{pubKey:K}=Y,[R,I]=await W.hasUser(K);if(I!==0)return I;if(!R)return 5;let z=[];while(!$.done()){let[w,q]=$.readVarInt();if(q!==0)return q;z.push(w)}console.info(`PULL: ${z.length} bags`);let[M,F]=await W.getBodies(K,z);if(F!==0)return F;if(!M)return 17;for(let{seq:w,bodyCph:q}of M){let U={seq:w,bodyCph:q},H=Z.writeStruct(fV,U);if(H!==0)return H}return 0},decodeResp(V){return V.readStructs(fV)}};var mV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarBytes($.bodyCph);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readBytes(F0);if(Z!==0)return N(Z);let[J,Q]=V.readBytes(P0);if(Q!==0)return N(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return N(Y);let[X,G]=V.readVarBytes();if(G!==0)return N(G);return O({sig:$,kdm:J,headCph:W,bodyCph:X})}};var QV={encode(V,$){let Z=V.writeVarInt($.seq);if(Z!==0)return Z;let J=V.writeVarBytes($.headCph);if(J!==0)return J;let Q=$.bodyCph?$.bodyCph.length:0,W=V.writeVarInt(Q);if(W!==0)return W;if(Q>0){if(!$.bodyCph)return 10;V.writeBytes($.bodyCph)}return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return N(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return N(Q);let[W,Y]=V.readVarInt();if(Y!==0)return N(Y);let X;if(W>0){let[G,K]=V.readBytes(W);if(K!==0)return N(K);X=G}return O({seq:$,headCph:J,bodyCph:X})}};var WV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readBytes(F0);if(Z!==0)return N(Z);let[J,Q]=V.readBytes(P0);if(Q!==0)return N(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return N(Y);return O({sig:$,kdm:J,headCph:W})}};var YV={encode(V,$){if(V.writeVarInt($.idx),V.writeBytes(new Uint8Array([$.status])),$.status===0)V.writeVarInt($.seq);return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return N(Z);let[J,Q]=V.readBytes(1);if(Q!==0)return N(Q);let W=J[0];if(W!==0)return O({idx:$,status:W});let[Y,X]=V.readVarInt();if(X!==0)return N(X);return O({idx:$,status:W,seq:Y})}};var v$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(V0,Z);if(W!==0)return W;let Y=Q.writeStructs(mV,J);if(Y!==0)return Y;return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W,notifier:Y}=V,[X,G]=$.readStruct(V0);if(G!==0)return G;let K=await U0(X,Q,J);if(K!==0)return K;let{pubKey:R}=X,[I,z]=await W.hasUser(R);if(z!==0)return z;if(!I)return 5;let[M,F]=$.readStructs(mV);if(F!==0)return F;console.info(`PUSH: ${M.length} bags`);let w=[],q=[];for(let P=0;P<M.length;P++){let D=M[P];if(!await x$(D,R,Q)){let k={idx:P,status:3},S=Z.writeStruct(YV,k);if(S!==0)return S;continue}w.push(P),q.push(D)}let[U,H]=await W.setBags(R,q);if(H!==0)return H;if(!U||U.length!==q.length)return 17;let A=[];for(let P=0;P<q.length;P++){let D=q[P],L=w[P],k=U[P],S=new B,E=S.writeStruct(WV,D);if(E!==0)return E;let x=S.result(),C={seq:k,headCph:x};if(M.length===1&&D.bodyCph.length<=H$)C.bodyCph=D.bodyCph;A.push(C);let f={idx:L,status:0,seq:k},v=Z.writeStruct(YV,f);if(v!==0)return v}if(A.length>0){let P=new B,D=P.writeStructs(QV,A);if(D!==0)return D;let L=P.result();await Promise.resolve(Y.push(R,L))}return 0},decodeResp(V){return V.readStructs(YV)}};var i$={async encodeReq(V,$,Z,J,Q){return Q.writeStruct(V0,Z)},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(V0);if(X!==0)return X;let G=await U0(Y,Q,J);if(G!==0)return G;let{pubKey:K}=Y;if(!$.done())return 8;let[R,I]=await W.addUser(K);if(I!==0)return I;return 0},decodeResp(V){return O(void 0)}};class gV{url;websocket;constructor(V){this.url=V}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(V,$,Z=()=>{},J=()=>{}){let{url:Q}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let W=new B;W.writeStruct(V0,V);let Y=W.result(),X=Q0(Y);return Q.searchParams.set("t",X),this.websocket=new WebSocket(Q),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),J()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Z()},this.websocket.onmessage=(G)=>{let K=new Uint8Array(G.data);$(K)},this.websocket.onerror=(G)=>{console.log(`ERROR: ${JSON.stringify(G)}`),this.websocket=void 0,Z()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var h={user:{path:"/user",endpoint:i$,name:0},push:{path:"/push",endpoint:v$,name:2},peek:{path:"/peek",endpoint:m$,name:1},pull:{path:"/pull",endpoint:g$,name:3}},JJ={0:h.user,2:h.push,1:h.peek,3:h.pull},bY={[h.user.path]:h.user,[h.push.path]:h.push,[h.peek.path]:h.peek,[h.pull.path]:h.pull};class b${url;listener;constructor(V){this.url=V;this.listener=new gV(V)}async call(V,$){let{path:Z}=JJ[V],J=new URL(Z,this.url);try{return await QJ(J,$)}catch{return N(25)}}}var u$=(V)=>{return new b$(V.handle)};async function QJ(V,$){let Z=await fetch(V,{method:"POST",body:$.result().slice()});if(!Z.ok)return N(24);let J=await m.fromResponse(Z);return O(J)}class XV{enclave;crypto;host;clock;transport;updateHostMeta;constructor(V,$,Z,J,Q,W){this.enclave=V;this.crypto=$;this.host=Z;this.clock=J;this.transport=Q;this.updateHostMeta=W}async call(V,$){let{clock:Z,crypto:J,transport:Q}=this,{endpoint:W,name:Y}=V,X=await this.keys(),G=Z.now(),[K,R]=await jV(X,G,J);if(R!==0)return N(R);let I=new B,z=await W.encodeReq(this,X,K,$,I);if(z!==0)return N(z);let M=Z.now(),[F,w]=await Q.call(Y,I),q=Z.now();if(w!==0)return N(w);let[U,H]=F.readStruct(SV);if(H!==0)return N(H);if(U.status!==0)return N(U.status);let P={clockOffset:f$(M,U.timeRcvd,U.timeSent,q),subscription:U.subscription},D=await this.updateHostMeta(P);if(D!==0)return N(D);return W.decodeResp(F)}keys=()=>{let{host:V}=this;return xV(this,V.label,V.idx)};seal=async(V)=>{let{crypto:$,enclave:Z}=this,J=await this.keys();return B$(V,J,$,Z)};register=()=>this.call(h.user,[]);peek=(V)=>this.call(h.peek,[V]);push=(V)=>this.call(h.push,V);pull=(V)=>this.call(h.pull,V);listen=async(V,$,Z)=>{let{clock:J,crypto:Q,host:W,transport:Y}=this,{listener:X}=Y,G=await xV(this,W.label,W.idx),K=J.now(),[R,I]=await jV(G,K,Q);if(I!==0)return I;return await X.connect(R,V,$,Z)};isConnected(){let V=this.transport?.listener;if(V&&typeof V.connected==="function")return V.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var vV={encode(V,$){let Z=V.writeVarString($.lbl);if(Z!==0)return Z;let J=V.writeVarInt($.idx);if(J!==0)return J;let Q=V.writeVarInt($.num);if(Q!==0)return Q;return V.writeBytes($.hsh),V.writeBytes($.sig),0},decode(V){let[$,Z]=V.readVarString();if(Z!==0)return N(Z);let[J,Q]=V.readVarInt();if(Q!==0)return N(Q);let[W,Y]=V.readVarInt();if(Y!==0)return N(Y);let[X,G]=V.readBytes(o0);if(G!==0)return N(G);let[K,R]=V.readBytes(F0);if(R!==0)return N(R);return O({lbl:$,idx:J,num:W,hsh:X,sig:K})}};var iV={encode(V,$){let Z=V.writeStruct(vV,$.head);if(Z!==0)return Z;let J=V.writeVarBytes($.indexEnc);if(J!==0)return J;let Q=V.writeVarBytes($.bodyEnc);if(Q!==0)return Q;return 0},decode(V){let[$,Z]=V.readStruct(vV);if(Z!==0)return N(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return N(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return N(Y);return O({head:$,indexEnc:J,bodyEnc:W})}};var bV={encode(V,$){V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarInt($.lenBody);if(J!==0)return J;if($.lenBody>0&&$.offBody!==void 0){let Q=V.writeVarInt($.offBody);if(Q!==0)return Q}return 0},decode(V){let[$,Z]=V.readBytes(P0);if(Z!==0)return N(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return N(Q);let[W,Y]=V.readVarInt();if(Y!==0)return N(Y);let X;if(W>0){let[G,K]=V.readVarInt();if(K!==0)return N(K);X=G}return O({kdm:$,headCph:J,lenBody:W,offBody:X})}};async function y$(V,$,Z,J,Q){let W=await Q.derive(V,$),Y=await J.deriveEd25519KeyPair(W),X=new B,G=new B,K=0,R=0;for(let H of Z){let A=new B,P=A.writeStruct(J0,H.head);if(P!==0)return N(P);let D=A.result(),L=await LV(D,Y,J),k=await Q.deriveFromKDM(L),S=await J.encryptXSalsa20Poly1305Combined(D,k),E=H.body?await J.encryptXSalsa20Poly1305Combined(H.body,k):new Uint8Array(0),x=H.head.len>0&&H.head.hsh!==void 0?E.length:0,C={kdm:L,headCph:S,lenBody:x,offBody:x>0?R:void 0},f=X.writeStruct(bV,C);if(f!==0)return N(f);if(H.body)G.writeBytes(E),R+=E.length;K++}let I=G.result(),z=X.result(),M=await J.blake3(z),F=await J.signEd25519(M,Y.privateKey),w={lbl:V,idx:$,num:K,hsh:M,sig:F},q=new B;q.writeStruct(iV,{head:w,indexEnc:z,bodyEnc:I});let U=q.result();return O(U)}async function n$(V,$,Z){let[J,Q]=iV.decode(new m(V));if(Q!==0)return N(Q);let{head:W,indexEnc:Y,bodyEnc:X}=J,G=await Z.derive(W.lbl,W.idx),K=await $.deriveEd25519KeyPair(G);if(!await $.checkSigEd25519(W.sig,W.hsh,K.publicKey))return N(3);let I=await $.blake3(Y);if(!O0(I,W.hsh))return N(19);let z=new m(Y),M=[];for(let w=0;w<W.num;w++){let[q,U]=z.readStruct(bV);if(U!==0)return N(U);M.push(q)}if(M.length!==W.num)return N(14);let F=[];for(let w of M){let q=await Z.deriveFromKDM(w.kdm),U=await $.decryptXSalsa20Poly1305Combined(w.headCph,q),[H,A]=J0.decode(new m(U));if(A!==0)return N(A);let P;if(w.lenBody>0&&w.offBody!==void 0){if(H.hsh===void 0)return N(14);let D=X.slice(w.offBody,w.offBody+w.lenBody);P=await $.decryptXSalsa20Poly1305Combined(D,q);let L=await $.blake3(P);if(!O0(L,H.hsh))return N(19)}F.push({head:H,body:P})}return O(F)}async function p$({now:V,bod:$,crypto:Z}){let J=await Z.genRandomBytes(8),Q=new B,W=Q.writeStruct(Y0,{id:J,ts:V});if(W!==0)return N(W);let Y=Q.result();return GV({now:V,eid:Y,ctr:0,bod:$,crypto:Z})}async function GV({now:V,eid:$,ctr:Z,bod:J,crypto:Q}){let W=new m($),[Y,X]=Y0.decode(W);if(X!==0)return N(X);let G=V.getTime()-Y.ts.getTime(),K,R=J?.length??0;if(J&&R>0)K=await Q.blake3(J);return O({eid:$,off:G,ctr:Z,len:R,hsh:K})}class KV{inflight=null;again=!1;run(V){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain(V),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain(V){try{this.again=!1;let $=await V();while(this.again)this.again=!1,$=await V();return $}finally{this.inflight=null}}}var l$=100;class uV{timer=null;delayMs;work;tail=new KV;constructor(V,$){this.delayMs=V<0?0:V,this.work=$}schedule(){if(this.delayMs<=0){this.fire();return}if(this.timer!==null)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=null,this.fire()},this.delayMs)}async flush(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null,this.fire();await this.tail.flush()}cancel(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null}fire(){return this.tail.run(this.work)}}var yV={phase:"idle"},RV=50;function h$(V,$,Z){if(V<=0||$<=0)return!1;if(V===1||V===$)return!0;return V%Z===0}function r$(V,$){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(V,$);return}let Z=URL.createObjectURL(V),J=document.createElement("a");J.href=Z,J.download=$,document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL(Z)}function c$(V,$,Z){let J=[],Q=[],W=0;for(let Y of V){let X=$(Y);if(Q.length>0&&W+X>Z)J.push(Q),Q=[],W=0;if(Q.push(Y),W+=X,W>=Z)J.push(Q),Q=[],W=0}if(Q.length>0)J.push(Q);return J}async function d$(V,$,Z){let J=V.length;if(J<1)return[];let Q=Array(J),W=0,Y=Math.min(Math.max(1,$),J),X=async()=>{while(!0){let K=W;if(W+=1,K>=J)return;Q[K]=await Z(V[K],K)}},G=[];for(let K=0;K<Y;K++)G.push(X());return await Promise.all(G),Q}async function nV(V,$,Z,J){let Q=new m(V.headCph),[W,Y]=Q.readStruct(WV);if(Y!==0)return N(Y);let{sig:X,kdm:G,headCph:K}=W;if(!await J.checkSigEd25519(X,K,$.publicKey))return N(3);let I=await Z.deriveFromKDM(G),z;try{z=await J.decryptXSalsa20Poly1305Combined(K,I)}catch{return N(20)}return O({kdm:G,headEnc:z})}var pV=1048576,lV=1048576,WJ=64;function YJ(V){return V.sig.length+V.kdm.length+V.headCph.length+V.bodyCph.length}async function XJ(V,$,Z,J,Q){if(J.length<1)return 0;let[W,Y]=await V.push(J);if(Y!==0)return Y;if(!W)return 27;for(let G of W){if(G.status!==0){console.error("push err",G);continue}let K=Q[G.idx];if(!K){console.error("no hash",G);continue}await $.uploads.deq(Z,[K])}let X=await $.hosts.get(Z);if(X){let G=X.lastSeq,K=G,R=[];for(let I of W)if(I.status===0)R.push(I.seq);R.sort((I,z)=>I-z);for(let I of R)if(I===G+1)G=I;if(G>K)await $.hosts.touch(Z,G)}return 0}async function o$(V,$){if($.length<1)return O([]);let Z=new Map,J=[];for(let X of $)Z.set(X.seq,X),J.push(X.seq);let[Q,W]=await V.pull(J);if(W!==0)return N(W);if(!Q)return N(27);let Y=[];for(let{seq:X,bodyCph:G}of Q){let K=Z.get(X);if(!K)continue;Y.push({dl:K,bodyCph:G})}return O(Y)}async function GJ(V,$,Z,J){if(J.length<1)return O({parts:[],hashes:[]});let Q=[],W=[],Y=[],X=new Map;for(let{dl:K,bodyCph:R}of J){let{head:I,kdm:z,seq:M,host:F}=K,w=new B;w.writeStruct(J0,I);let q=w.result(),U=await Z.blake3(q),H=await $.deriveFromKDM(z),[A,P]=await kV(q,R,H,Z);if(P!==0){let k=X.get(F)??[];k.push(M),X.set(F,k);continue}let D={head:I,body:A.bod};Y.push({key:U,data:e$(D)}),Q.push(D),W.push(U);let L=X.get(F)??[];L.push(M),X.set(F,L)}let G=await V.messages.add(Y);for(let[K,R]of X)await V.downloads.deq(K,R);for(let K=0;K<G.length;K++){let R=G[K];if(R!==0&&R!==15)console.error("ERR storing",j[R],"for message",K)}return O({parts:Q,hashes:W})}async function a$({conn:V,store:$,enclave:Z,host:J,crypto:Q,onProgress:W,peekProgressEvery:Y,peekConcurrency:X}){let G=await V.keys(),K=[],[R,I]=await V.peek(J.lastSeq);if(I!==0)return I;let z=R.length,M=Y??RV,F=X??WJ;if(W&&z>0)W({phase:"peek",host:J.label,done:0,total:z});let w=0,q=await d$(R,F,async(U)=>{let[H,A]=await nV(U,G,Z,Q),P;if(A!==0||!H)P={ok:!1,seq:U.seq,stat:A};else{let D=await Q.blake3(H.headEnc);P={ok:!0,seq:U.seq,kdm:H.kdm,headEnc:H.headEnc,headEncHash:D}}if(w+=1,W&&h$(w,z,M))W({phase:"peek",host:J.label,done:w,total:z});return P});for(let U of q){if(!U.ok){console.error("peek: decrypting item head",U.stat);continue}if(await $.messages.has(U.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await $.uploads.deq(J.label,[U.headEncHash]);continue}let A=new m(U.headEnc),[P,D]=A.readStruct(J0);if(D!==0){console.error("peek: reading item head",D);continue}K.push({kdm:U.kdm,head:P,seq:U.seq,host:J.label})}if(await $.downloads.enq(K),R.length>0){let U=Math.max(...R.map((H)=>H.seq));await $.hosts.touch(J.label,U)}if(W)W({phase:"peek",host:J.label,done:z,total:z});return 0}async function s$({conn:V,store:$,host:Z,maxPushBytes:J,onProgress:Q}){let W=J??pV,Y=await $.uploads.list(Z.label),X=Y.length,G=0;if(Q&&X>0)Q({phase:"push",host:Z.label,done:0,total:X});let K=[],R=[],I=0,z=async()=>{if(K.length<1)return 0;let M=K.length,F=await XJ(V,$,Z.label,K,R);if(K=[],R=[],I=0,F===0){if(G+=M,Q)Q({phase:"push",host:Z.label,done:G,total:X})}return F};for(let M of Y){let F=await $.messages.get(M);if(!F){G+=1;continue}let w={...F.head,bod:F.body},[q,U]=await V.seal(w);if(U!==0)return U;if(!q)return 12;let H=YJ(q);if(K.length>0&&I+H>W){let A=await z();if(A!==0)return A}if(K.push(q),R.push(M),I+=H,I>=W){let A=await z();if(A!==0)return A}}return z()}async function t$({conn:V,store:$,enclave:Z,host:J,crypto:Q,maxPullBytes:W,onProgress:Y},X){let G=W??lV,K=await $.downloads.list(),R=Array.from(K).filter((w)=>w.host===J.label);if(R.length<1)return 15;let I=c$(R,(w)=>w.head.len,G),z=R.length,M=0;if(Y)Y({phase:"pull",host:J.label,done:0,total:z});let F=o$(V,I[0]);for(let w=0;w<I.length;w++){let[q,U]=await F;if(U!==0||!q)return U;if(M+=I[w].length,Y)Y({phase:"pull",host:J.label,done:M,total:z});let H=I[w+1];if(H)F=o$(V,H);if(Y)Y({phase:"open",host:J.label,done:M,total:z});let[,A]=await GJ($,Z,Q,q);if(A!==0)return A;if(X){if(Y)Y({phase:"exec",host:J.label,done:M,total:z});await X()}}return 0}function e$({head:V,body:$}){return{eid:V.eid,...V.off!==0?{off:V.off}:{},...V.ctr!==0?{ctr:V.ctr}:{},body:$,apld:!1}}async function VZ(V,{conn:$,store:Z,enclave:J,host:Q,crypto:W,onProgress:Y},X){let G=Q.label,K=await $.keys(),R=new m(V),[I,z]=R.readStructs(QV);if(z!==0){console.error("Failed decoding notif",j[z]);return}let M=!1,w=(await Z.hosts.get(G))?.lastSeq,q=[],U=!1;for(let P of I){let[D,L]=await nV({seq:P.seq,headCph:P.headCph},K,J,W);if(L!==0){console.error("Failed decrypting notif",j[L]);continue}let k=await W.blake3(D.headEnc);if(await Z.messages.has(k))continue;let S=new m(D.headEnc),[E,x]=S.readStruct(J0);if(x!==0){console.error("Failed to parse head",j[x]);continue}if(!P.bodyCph&&E.len>0)U=!0,await Z.downloads.enq([{seq:P.seq,host:G,kdm:D.kdm,head:E}]);else q.push({...D,head:E,bodyCph:P.bodyCph,headEncHash:k});if(w===void 0||P.seq!==w+1)console.log("out of seq",P.seq,w),M=!0;else w=P.seq}if(w!==void 0)await Z.hosts.touch(Q.label,w);let H=[];for(let P of q){let D=await J.deriveFromKDM(P.kdm),[L,k]=await kV(P.headEnc,P.bodyCph,D,W);if(k!==0){console.error("Failed to open body",j[k]);continue}H.push({key:P.headEncHash,data:e$({head:P.head,body:L.bod})})}let A=await Z.messages.add(H);for(let P=0;P<A.length;P++){let D=A[P];if(D!==0&&D!==15)console.error("ERR storing",j[D],"for message",P)}if(Y&&H.length>0)Y({phase:"open",host:Q.label,done:H.length,total:H.length});if(M||U||H.length>0)X()}class hV{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new KV;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=RV;lastProgress=yV;scheduledSync;constructor(V,$,Z,J,Q,W=!0,Y=pV,X=lV,G){this.clock=V;this.state=$;this.store=Z;this.transport=J;this.crypto=Q;this.forceSkewHandlingByDefault=W;this.onScheduleSync=G;this.maxPushBytes=Y,this.maxPullBytes=X,this.clientState=new q0(()=>this.getClientState()),this.xferState=new q0(()=>this.getXferState()),this.scheduledSync=new uV(l$,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(K){console.error("Debounced sync failed:",K)}})}emitProgress=(V)=>{this.lastProgress=V,this.xferState.emit()};async setSeed(V){await this.store.seed.save(V),this.clientState.emit()}async getClientState(){let{store:V,connections:$}=this,Z=await V.seed.load(),J=await V.hosts.list(),Q=!1;for(let W of $.values())if(W.isConnected()){Q=!0;break}return{hasSeed:Z!==void 0,hasHost:Array.from(J).length>0,connected:Q}}async getXferState(){let{uploads:V,downloads:$}=this.store,Z=await V.count();return{numDownloads:await $.count(),numUploads:Z,progress:this.lastProgress}}apply=async(V,$={enqueueUpload:!0,triggerUpload:!0})=>{let Z=[],J=[];for(let{head:W,body:Y}of V){let X=new B;X.writeStruct(J0,W);let G=X.result(),K=await this.crypto.blake3(G),R={eid:W.eid,...W.off!==0?{off:W.off}:{},...W.ctr!==0?{ctr:W.ctr}:{},body:Y,apld:!1};Z.push(K),J.push({key:K,data:R})}await this.store.messages.add(J);let Q=await this.applyHashes(Z);if($.enqueueUpload){let W=[];for(let Y=0;Y<Z.length;Y++){let X=Q[Y];if(X===0||X===15)W.push(Z[Y])}if(W.length>0){let Y=await this.store.hosts.list();for(let X of Y)await this.store.uploads.enq(X.label,W);this.xferState.emit()}}if($.triggerUpload)this.scheduleSync();return Q};enqueueApplyJob(V){let $=this.applyChain.then(V,V);return this.applyChain=$.then(()=>{return},()=>{return}),$}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let V=await this.store.messages.listUnapplied();if(V.length<1)return[];return this.applyStored(V)}applyHashes=(V)=>{return this.enqueueApplyJob(async()=>{let $=[];for(let Q of V){let W=await this.store.messages.get(Q);if(W)$.push(W)}let Z=await this.applyStored($),J=new Map;for(let Q=0;Q<$.length;Q++)J.set(d($[Q].hash),Z[Q]??12);return V.map((Q)=>J.get(d(Q))??13)})};async applyStored(V){if(V.length<1)return[];let $=V.map((Q)=>({...Q.head,bod:Q.body})),Z=await this.state.apply($),J=[];for(let Q=0;Q<V.length;Q++){let W=Z[Q];if(W===0||W===15)J.push(V[Q].hash)}if(J.length>0)await this.store.messages.markApplied(J);return Z}async insertRaw(V){let{clock:$,crypto:Z}=this,[J,Q]=await p$({now:$.now(),bod:V,crypto:Z});if(Q!==0)return N(Q);return await this.apply([{head:J,body:V}]),O(J)}async upsertRaw(V,$,Z=!1){let{clock:J,crypto:Q,store:W}=this,Y=J.now(),X=await W.messages.last(V);if(X){let M=new m(V),[F,w]=M.readStruct(Y0);if(w!==0)return N(w);if(F.ts.getTime()+X.head.off>Y.getTime()){if(Z===!1)return N(4);let U=X.head.off+1,H=X.head.ctr+1,A={eid:V,off:U,ctr:H,len:0},D=(await this.apply([{head:A,body:void 0}]))[0];if(D!==0)return N(D);if($===void 0)return O(A);let[L,k]=ZV({id:F.id,ts:Y});if(k!==0)return N(k);let S={now:Y,eid:L,ctr:0,bod:$,crypto:Q},[E,x]=await GV(S);if(x!==0)return N(x);let f=(await this.apply([{head:E,body:$}]))[0];if(f!==0)return N(f);return O(E)}}let G=(X?.head.ctr??-1)+1,[K,R]=await GV({now:Y,eid:V,ctr:G,bod:$,crypto:Q});if(R!==0)return N(R);let z=(await this.apply([{head:K,body:$}]))[0];if(z!==0)return N(z);return O(K)}async insert(V){let{body:$,type:Z,gid:J,pid:Q}=V,Y=e0({body:$,type:Z,gid:J,pid:Q});return this.insertRaw(Y)}async upsert(V,$=this.forceSkewHandlingByDefault){let{eid:Z,body:J,type:Q,gid:W,pid:Y}=V;if(Z===void 0)return this.insert(V);let G=e0({body:J,type:Q,gid:W,pid:Y});return this.upsertRaw(Z,G,$)}async delete(V){return this.upsertRaw(V,void 0,!0)}async genEID(V){let{clock:$,crypto:Z}=this,J=$.now();if(V!==void 0)return ZV({id:V,ts:J});let Q=await Z.genRandomBytes(8);return ZV({id:Q,ts:J})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:V,crypto:$,store:Z}=this,J=await Z.seed.load();if(!J)return 22;await this.drainApplyQueue();for(let[Q,W]of V){let Y=await Z.hosts.get(Q);if(!Y)continue;let X={conn:W,store:Z,enclave:J,host:Y,crypto:$,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},G=await a$(X);if(G!==0)return console.error(`Failed to peek: ${G}`),G;this.xferState.emit();let K=await s$(X);if(K!==0)return console.error(`Failed to push: ${K}`),K;this.xferState.emit();let R=await t$(X,async()=>{await this.drainApplyQueue()});if(R!==0&&R!==15)return console.error(`Failed to pull: ${R}`),R;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async wipe(){this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush(),await this.store.wipe(),await this.state.clear(),this.lastProgress=yV,this.clientState.emit(),this.xferState.emit()}import=async(V,$)=>{let{crypto:Z,store:J}=this,Q=$?.onProgress,W=await J.seed.load();if(!W)return 22;console.time("import: decoding file...");let Y=await V.bytes(),[X,G]=await n$(Y,Z,W);if(G!==0)return G;console.timeEnd("import: decoding file...");let K=0;while(K<X.length){let R=0,I=0,z=K;for(let w=K;w<X.length&&I<100&&R<102400;w++)R+=X[w].head.len,I++,z=w+1;let M=X.slice(K,z);console.time(`import: applying [${K}, ${z}]`);let F=await this.apply(M,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${K}, ${z}]`);for(let w=0;w<M.length;w++){let q=F[w];if(q!==0&&q!==15)console.warn(`failed to import msg ${K+w}: ${j[q]}`)}if(Q)queueMicrotask(()=>Q(z,X.length,0));this.emitProgress({phase:"import",done:z,total:X.length}),K=z}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:V,store:$}=this,Z=await $.seed.load();if(!Z)return N(22);let J=await $.messages.list();return y$("export",0,J,V,Z)}async export(V){let[$,Z]=await this.exportBytes();if(Z!==0)return Z;if(!$)return 12;let J=new Blob([$.slice()]);return r$(J,V),0}async link(V,$=!0){if(await this.store.hosts.add(V),this.clientState.emit(),$){let Z=await this.store.hosts.get(V.label);if(Z)await this.connectToHost(Z)}}async unlink(V){await this.store.hosts.del(V),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async(V,$=!0,Z=!0)=>{let{clock:J,connections:Q,crypto:W,store:Y,transport:X}=this,G=Q.get(V.label);if(G){if(G.isConnected())return;try{G.closeListener()}catch{}Q.delete(V.label)}let K=await Y.seed.load();if(!K)return;console.info(`Connecting to ${V.handle} (${V.label})`);let R=new XV(K,W,V,J,X(V),(I)=>Y.hosts.set(V.label,I));if(await R.register(),$)await R.listen(async(I)=>{let z={conn:R,store:Y,enclave:K,host:V,crypto:W,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return VZ(I,z,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(Q.set(V.label,R),this.clientState.emit(),Z)this.scheduleSync()};async connect(V=!0,$=!0){let{connectToHost:Z,scheduleSync:J,store:Q}=this;if(!await Q.seed.load())return;await this.drainApplyQueue();let Y=await Q.hosts.list();for(let X of Y)await Z(X,V,!1);if($)J()}disconnect=async()=>{for(let V of this.connections.values())try{V.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var H0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function NV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function rV(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function l(V,...$){if(!rV(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function cV(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function $Z(V,$){l(V);let Z=$.outputLen;if(V.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function dV(V){if(typeof V!=="boolean")throw Error(`boolean expected, not ${V}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var N0=(V)=>new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4));var KJ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!KJ)throw Error("Non little-endian hardware is not supported");function RJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function IV(V){if(typeof V==="string")V=RJ(V);else if(rV(V))V=wV(V);else throw Error("Uint8Array expected, got "+typeof V);return V}function ZZ(V,$){if($==null||typeof $!=="object")throw Error("options must be defined");return Object.assign(V,$)}function JZ(V,$){if(V.length!==$.length)return!1;let Z=0;for(let J=0;J<V.length;J++)Z|=V[J]^$[J];return Z===0}var QZ=(V,$)=>{function Z(J,...Q){if(l(J),V.nonceLength!==void 0){let R=Q[0];if(!R)throw Error("nonce / iv required");if(V.varSizeNonce)l(R);else l(R,V.nonceLength)}let W=V.tagLength;if(W&&Q[1]!==void 0)l(Q[1]);let Y=$(J,...Q),X=(R,I)=>{if(I!==void 0){if(R!==2)throw Error("cipher output not supported");l(I)}},G=!1;return{encrypt(R,I){if(G)throw Error("cannot encrypt() twice with same key + nonce");return G=!0,l(R),X(Y.encrypt.length,I),Y.encrypt(R,I)},decrypt(R,I){if(l(R),W&&R.length<W)throw Error("invalid ciphertext length: smaller than tagLength="+W);return X(Y.decrypt.length,I),Y.decrypt(R,I)}}}return Object.assign(Z,V),Z};function oV(V,$,Z=!0){if($===void 0)return new Uint8Array(V);if($.length!==V)throw Error("invalid output length, expected "+V+", got: "+$.length);if(Z&&!NJ($))throw Error("invalid output, must be aligned");return $}function NJ(V){return V.byteOffset%4===0}function wV(V){return Uint8Array.from(V)}function X0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function zV(V=32){if(H0&&typeof H0.getRandomValues==="function")return H0.getRandomValues(new Uint8Array(V));if(H0&&typeof H0.randomBytes==="function")return H0.randomBytes(V);throw Error("crypto.getRandomValues must be defined")}var YZ=(V)=>Uint8Array.from(V.split("").map(($)=>$.charCodeAt(0))),IJ=YZ("expand 16-byte k"),wJ=YZ("expand 32-byte k"),zJ=N0(IJ),MJ=N0(wJ);function T(V,$){return V<<$|V>>>32-$}function aV(V){return V.byteOffset%4===0}var MV=64,FJ=16,XZ=4294967295,WZ=new Uint32Array;function PJ(V,$,Z,J,Q,W,Y,X){let G=Q.length,K=new Uint8Array(MV),R=N0(K),I=aV(Q)&&aV(W),z=I?N0(Q):WZ,M=I?N0(W):WZ;for(let F=0;F<G;Y++){if(V($,Z,J,R,Y,X),Y>=XZ)throw Error("arx: counter overflow");let w=Math.min(MV,G-F);if(I&&w===MV){let q=F/4;if(F%4!==0)throw Error("arx: invalid block position");for(let U=0,H;U<FJ;U++)H=q+U,M[H]=z[H]^R[U];F+=MV;continue}for(let q=0,U;q<w;q++)U=F+q,W[U]=Q[U]^K[q];F+=w}}function GZ(V,$){let{allowShortKeys:Z,extendNonceFn:J,counterLength:Q,counterRight:W,rounds:Y}=ZZ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},$);if(typeof V!=="function")throw Error("core must be a function");return NV(Q),NV(Y),dV(W),dV(Z),(X,G,K,R,I=0)=>{l(X),l(G),l(K);let z=K.length;if(R===void 0)R=new Uint8Array(z);if(l(R),NV(I),I<0||I>=XZ)throw Error("arx: counter overflow");if(R.length<z)throw Error(`arx: output (${R.length}) is shorter than data (${z})`);let M=[],F=X.length,w,q;if(F===32)M.push(w=wV(X)),q=MJ;else if(F===16&&Z)w=new Uint8Array(32),w.set(X),w.set(X,16),q=zJ,M.push(w);else throw Error(`arx: invalid 32-byte key, got length=${F}`);if(!aV(G))M.push(G=wV(G));let U=N0(w);if(J){if(G.length!==24)throw Error("arx: extended nonce must be 24 bytes");J(q,U,N0(G.subarray(0,16)),U),G=G.subarray(16)}let H=16-Q;if(H!==G.length)throw Error(`arx: nonce must be ${H} or 16 bytes`);if(H!==12){let P=new Uint8Array(12);P.set(G,W?0:12-G.length),G=P,M.push(G)}let A=N0(G);return PJ(V,q,U,A,K,R,I,Y),X0(...M),R}}var r=(V,$)=>V[$++]&255|(V[$++]&255)<<8;class KZ{constructor(V){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,V=IV(V),l(V,32);let $=r(V,0),Z=r(V,2),J=r(V,4),Q=r(V,6),W=r(V,8),Y=r(V,10),X=r(V,12),G=r(V,14);this.r[0]=$&8191,this.r[1]=($>>>13|Z<<3)&8191,this.r[2]=(Z>>>10|J<<6)&7939,this.r[3]=(J>>>7|Q<<9)&8191,this.r[4]=(Q>>>4|W<<12)&255,this.r[5]=W>>>1&8190,this.r[6]=(W>>>14|Y<<2)&8191,this.r[7]=(Y>>>11|X<<5)&8065,this.r[8]=(X>>>8|G<<8)&8191,this.r[9]=G>>>5&127;for(let K=0;K<8;K++)this.pad[K]=r(V,16+2*K)}process(V,$,Z=!1){let J=Z?0:2048,{h:Q,r:W}=this,Y=W[0],X=W[1],G=W[2],K=W[3],R=W[4],I=W[5],z=W[6],M=W[7],F=W[8],w=W[9],q=r(V,$+0),U=r(V,$+2),H=r(V,$+4),A=r(V,$+6),P=r(V,$+8),D=r(V,$+10),L=r(V,$+12),k=r(V,$+14),S=Q[0]+(q&8191),E=Q[1]+((q>>>13|U<<3)&8191),x=Q[2]+((U>>>10|H<<6)&8191),C=Q[3]+((H>>>7|A<<9)&8191),f=Q[4]+((A>>>4|P<<12)&8191),v=Q[5]+(P>>>1&8191),u=Q[6]+((P>>>14|D<<2)&8191),y=Q[7]+((D>>>11|L<<5)&8191),n=Q[8]+((L>>>8|k<<8)&8191),p=Q[9]+(k>>>5|J),_=0,c=_+S*Y+E*(5*w)+x*(5*F)+C*(5*M)+f*(5*z);_=c>>>13,c&=8191,c+=v*(5*I)+u*(5*R)+y*(5*K)+n*(5*G)+p*(5*X),_+=c>>>13,c&=8191;let o=_+S*X+E*Y+x*(5*w)+C*(5*F)+f*(5*M);_=o>>>13,o&=8191,o+=v*(5*z)+u*(5*I)+y*(5*R)+n*(5*K)+p*(5*G),_+=o>>>13,o&=8191;let e=_+S*G+E*X+x*Y+C*(5*w)+f*(5*F);_=e>>>13,e&=8191,e+=v*(5*M)+u*(5*z)+y*(5*I)+n*(5*R)+p*(5*K),_+=e>>>13,e&=8191;let g=_+S*K+E*G+x*X+C*Y+f*(5*w);_=g>>>13,g&=8191,g+=v*(5*F)+u*(5*M)+y*(5*z)+n*(5*I)+p*(5*R),_+=g>>>13,g&=8191;let K0=_+S*R+E*K+x*G+C*X+f*Y;_=K0>>>13,K0&=8191,K0+=v*(5*w)+u*(5*F)+y*(5*M)+n*(5*z)+p*(5*I),_+=K0>>>13,K0&=8191;let A0=_+S*I+E*R+x*K+C*G+f*X;_=A0>>>13,A0&=8191,A0+=v*Y+u*(5*w)+y*(5*F)+n*(5*M)+p*(5*z),_+=A0>>>13,A0&=8191;let D0=_+S*z+E*I+x*R+C*K+f*G;_=D0>>>13,D0&=8191,D0+=v*X+u*Y+y*(5*w)+n*(5*F)+p*(5*M),_+=D0>>>13,D0&=8191;let _0=_+S*M+E*z+x*I+C*R+f*K;_=_0>>>13,_0&=8191,_0+=v*G+u*X+y*Y+n*(5*w)+p*(5*F),_+=_0>>>13,_0&=8191;let j0=_+S*F+E*M+x*z+C*I+f*R;_=j0>>>13,j0&=8191,j0+=v*K+u*G+y*X+n*Y+p*(5*w),_+=j0>>>13,j0&=8191;let L0=_+S*w+E*F+x*M+C*z+f*I;_=L0>>>13,L0&=8191,L0+=v*R+u*K+y*G+n*X+p*Y,_+=L0>>>13,L0&=8191,_=(_<<2)+_|0,_=_+c|0,c=_&8191,_=_>>>13,o+=_,Q[0]=c,Q[1]=o,Q[2]=e,Q[3]=g,Q[4]=K0,Q[5]=A0,Q[6]=D0,Q[7]=_0,Q[8]=j0,Q[9]=L0}finalize(){let{h:V,pad:$}=this,Z=new Uint16Array(10),J=V[1]>>>13;V[1]&=8191;for(let Y=2;Y<10;Y++)V[Y]+=J,J=V[Y]>>>13,V[Y]&=8191;V[0]+=J*5,J=V[0]>>>13,V[0]&=8191,V[1]+=J,J=V[1]>>>13,V[1]&=8191,V[2]+=J,Z[0]=V[0]+5,J=Z[0]>>>13,Z[0]&=8191;for(let Y=1;Y<10;Y++)Z[Y]=V[Y]+J,J=Z[Y]>>>13,Z[Y]&=8191;Z[9]-=8192;let Q=(J^1)-1;for(let Y=0;Y<10;Y++)Z[Y]&=Q;Q=~Q;for(let Y=0;Y<10;Y++)V[Y]=V[Y]&Q|Z[Y];V[0]=(V[0]|V[1]<<13)&65535,V[1]=(V[1]>>>3|V[2]<<10)&65535,V[2]=(V[2]>>>6|V[3]<<7)&65535,V[3]=(V[3]>>>9|V[4]<<4)&65535,V[4]=(V[4]>>>12|V[5]<<1|V[6]<<14)&65535,V[5]=(V[6]>>>2|V[7]<<11)&65535,V[6]=(V[7]>>>5|V[8]<<8)&65535,V[7]=(V[8]>>>8|V[9]<<5)&65535;let W=V[0]+$[0];V[0]=W&65535;for(let Y=1;Y<8;Y++)W=(V[Y]+$[Y]|0)+(W>>>16)|0,V[Y]=W&65535;X0(Z)}update(V){cV(this);let{buffer:$,blockLen:Z}=this;V=IV(V);let J=V.length;for(let Q=0;Q<J;){let W=Math.min(Z-this.pos,J-Q);if(W===Z){for(;Z<=J-Q;Q+=Z)this.process(V,Q);continue}if($.set(V.subarray(Q,Q+W),this.pos),this.pos+=W,Q+=W,this.pos===Z)this.process($,0,!1),this.pos=0}return this}destroy(){X0(this.h,this.r,this.buffer,this.pad)}digestInto(V){cV(this),$Z(V,this),this.finished=!0;let{buffer:$,h:Z}=this,{pos:J}=this;if(J){$[J++]=1;for(;J<16;J++)$[J]=0;this.process($,0,!0)}this.finalize();let Q=0;for(let W=0;W<8;W++)V[Q++]=Z[W]>>>0,V[Q++]=Z[W]>>>8;return V}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Z=V.slice(0,$);return this.destroy(),Z}}function UJ(V){let $=(J,Q)=>V(Q).update(IV(J)).digest(),Z=V(new Uint8Array(32));return $.outputLen=Z.outputLen,$.blockLen=Z.blockLen,$.create=(J)=>V(J),$}var sV=UJ((V)=>new KZ(V));function qJ(V,$,Z,J,Q,W=20){let Y=V[0],X=$[0],G=$[1],K=$[2],R=$[3],I=V[1],z=Z[0],M=Z[1],F=Q,w=0,q=V[2],U=$[4],H=$[5],A=$[6],P=$[7],D=V[3],L=Y,k=X,S=G,E=K,x=R,C=I,f=z,v=M,u=F,y=w,n=q,p=U,_=H,c=A,o=P,e=D;for(let K0=0;K0<W;K0+=2)x^=T(L+_|0,7),u^=T(x+L|0,9),_^=T(u+x|0,13),L^=T(_+u|0,18),y^=T(C+k|0,7),c^=T(y+C|0,9),k^=T(c+y|0,13),C^=T(k+c|0,18),o^=T(n+f|0,7),S^=T(o+n|0,9),f^=T(S+o|0,13),n^=T(f+S|0,18),E^=T(e+p|0,7),v^=T(E+e|0,9),p^=T(v+E|0,13),e^=T(p+v|0,18),k^=T(L+E|0,7),S^=T(k+L|0,9),E^=T(S+k|0,13),L^=T(E+S|0,18),f^=T(C+x|0,7),v^=T(f+C|0,9),x^=T(v+f|0,13),C^=T(x+v|0,18),p^=T(n+y|0,7),u^=T(p+n|0,9),y^=T(u+p|0,13),n^=T(y+u|0,18),_^=T(e+o|0,7),c^=T(_+e|0,9),o^=T(c+_|0,13),e^=T(o+c|0,18);let g=0;J[g++]=Y+L|0,J[g++]=X+k|0,J[g++]=G+S|0,J[g++]=K+E|0,J[g++]=R+x|0,J[g++]=I+C|0,J[g++]=z+f|0,J[g++]=M+v|0,J[g++]=F+u|0,J[g++]=w+y|0,J[g++]=q+n|0,J[g++]=U+p|0,J[g++]=H+_|0,J[g++]=A+c|0,J[g++]=P+o|0,J[g++]=D+e|0}function OJ(V,$,Z,J){let Q=V[0],W=$[0],Y=$[1],X=$[2],G=$[3],K=V[1],R=Z[0],I=Z[1],z=Z[2],M=Z[3],F=V[2],w=$[4],q=$[5],U=$[6],H=$[7],A=V[3];for(let D=0;D<20;D+=2)G^=T(Q+q|0,7),z^=T(G+Q|0,9),q^=T(z+G|0,13),Q^=T(q+z|0,18),M^=T(K+W|0,7),U^=T(M+K|0,9),W^=T(U+M|0,13),K^=T(W+U|0,18),H^=T(F+R|0,7),Y^=T(H+F|0,9),R^=T(Y+H|0,13),F^=T(R+Y|0,18),X^=T(A+w|0,7),I^=T(X+A|0,9),w^=T(I+X|0,13),A^=T(w+I|0,18),W^=T(Q+X|0,7),Y^=T(W+Q|0,9),X^=T(Y+W|0,13),Q^=T(X+Y|0,18),R^=T(K+G|0,7),I^=T(R+K|0,9),G^=T(I+R|0,13),K^=T(G+I|0,18),w^=T(F+M|0,7),z^=T(w+F|0,9),M^=T(z+w|0,13),F^=T(M+z|0,18),q^=T(A+H|0,7),U^=T(q+A|0,9),H^=T(U+q|0,13),A^=T(H+U|0,18);let P=0;J[P++]=Q,J[P++]=K,J[P++]=F,J[P++]=A,J[P++]=R,J[P++]=I,J[P++]=z,J[P++]=M}var tV=GZ(qJ,{counterRight:!0,extendNonceFn:OJ}),eV=QZ({blockSize:64,nonceLength:24,tagLength:16},(V,$)=>{return{encrypt(Z,J){J=oV(Z.length+32,J,!1);let Q=J.subarray(0,32),W=J.subarray(32);J.set(Z,32),X0(Q),tV(V,$,J,J);let Y=sV(W,Q);return J.set(Y,16),X0(J.subarray(0,16),Y),J.subarray(16)},decrypt(Z,J){l(Z),J=oV(Z.length+32,J,!1);let Q=J.subarray(0,32),W=J.subarray(32,48),Y=J.subarray(48);J.set(Z,32),X0(Q);let X=tV(V,$,Q,Q),G=sV(Y,X);if(!JZ(W,G))throw Error("invalid tag");return tV(V,$,J.subarray(16),J.subarray(16)),X0(Q,W,G),Y}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function HJ(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function l0(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function C0(V,...$){if(!HJ(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function h0(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function FV(V,$){C0(V);let Z=$.outputLen;if(V.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function RZ(V){return new Uint8Array(V.buffer,V.byteOffset,V.byteLength)}function x0(V){return new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4))}function B0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function r0(V,$){return V<<32-$|V>>>$}var NZ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function IZ(V){return V<<24&4278190080|V<<8&16711680|V>>>8&65280|V>>>24&255}var wZ=NZ?(V)=>V:(V)=>IZ(V);function CJ(V){for(let $=0;$<V.length;$++)V[$]=IZ(V[$]);return V}var s=NZ?(V)=>V:CJ;function TJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function f0(V){if(typeof V==="string")V=TJ(V);return C0(V),V}class V${}function zZ(V){let $=(J,Q)=>V(Q).update(f0(J)).digest(),Z=V({});return $.outputLen=Z.outputLen,$.blockLen=Z.blockLen,$.create=(J)=>V(J),$}var MZ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var PV=BigInt(4294967295),FZ=BigInt(32);function $$(V,$=!1){if($)return{h:Number(V&PV),l:Number(V>>FZ&PV)};return{h:Number(V>>FZ&PV)|0,l:Number(V&PV)|0}}function I0(V,$,Z,J,Q){return V=V+$+Q|0,J=r0(J^V,16),Z=Z+J|0,$=r0($^Z,12),{a:V,b:$,c:Z,d:J}}function w0(V,$,Z,J,Q){return V=V+$+Q|0,J=r0(J^V,8),Z=Z+J|0,$=r0($^Z,7),{a:V,b:$,c:Z,d:J}}class Z$ extends V${constructor(V,$){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,l0(V),l0($),this.blockLen=V,this.outputLen=$,this.buffer=new Uint8Array(V),this.buffer32=x0(this.buffer)}update(V){h0(this),V=f0(V),C0(V);let{blockLen:$,buffer:Z,buffer32:J}=this,Q=V.length,W=V.byteOffset,Y=V.buffer;for(let X=0;X<Q;){if(this.pos===$)s(J),this.compress(J,0,!1),s(J),this.pos=0;let G=Math.min($-this.pos,Q-X),K=W+X;if(G===$&&!(K%4)&&X+G<Q){let R=new Uint32Array(Y,K,Math.floor((Q-X)/4));s(R);for(let I=0;X+$<Q;I+=J.length,X+=$)this.length+=$,this.compress(R,I,!1);s(R);continue}Z.set(V.subarray(X,X+G),this.pos),this.pos+=G,this.length+=G,X+=G}return this}digestInto(V){h0(this),FV(V,this);let{pos:$,buffer32:Z}=this;this.finished=!0,B0(this.buffer.subarray($)),s(Z),this.compress(Z,0,!0),s(Z);let J=x0(V);this.get().forEach((Q,W)=>J[W]=wZ(Q))}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Z=V.slice(0,$);return this.destroy(),Z}_cloneInto(V){let{buffer:$,length:Z,finished:J,destroyed:Q,outputLen:W,pos:Y}=this;return V||(V=new this.constructor({dkLen:W})),V.set(...this.get()),V.buffer.set($),V.destroyed=Q,V.finished=J,V.length=Z,V.pos=Y,V.outputLen=W,V}clone(){return this._cloneInto()}}function J$(V,$,Z,J,Q,W,Y,X,G,K,R,I,z,M,F,w,q,U,H,A){let P=0;for(let D=0;D<J;D++)({a:Q,b:G,c:z,d:q}=I0(Q,G,z,q,Z[$+V[P++]])),{a:Q,b:G,c:z,d:q}=w0(Q,G,z,q,Z[$+V[P++]]),{a:W,b:K,c:M,d:U}=I0(W,K,M,U,Z[$+V[P++]]),{a:W,b:K,c:M,d:U}=w0(W,K,M,U,Z[$+V[P++]]),{a:Y,b:R,c:F,d:H}=I0(Y,R,F,H,Z[$+V[P++]]),{a:Y,b:R,c:F,d:H}=w0(Y,R,F,H,Z[$+V[P++]]),{a:X,b:I,c:w,d:A}=I0(X,I,w,A,Z[$+V[P++]]),{a:X,b:I,c:w,d:A}=w0(X,I,w,A,Z[$+V[P++]]),{a:Q,b:K,c:F,d:A}=I0(Q,K,F,A,Z[$+V[P++]]),{a:Q,b:K,c:F,d:A}=w0(Q,K,F,A,Z[$+V[P++]]),{a:W,b:R,c:w,d:q}=I0(W,R,w,q,Z[$+V[P++]]),{a:W,b:R,c:w,d:q}=w0(W,R,w,q,Z[$+V[P++]]),{a:Y,b:I,c:z,d:U}=I0(Y,I,z,U,Z[$+V[P++]]),{a:Y,b:I,c:z,d:U}=w0(Y,I,z,U,Z[$+V[P++]]),{a:X,b:G,c:M,d:H}=I0(X,G,M,H,Z[$+V[P++]]),{a:X,b:G,c:M,d:H}=w0(X,G,M,H,Z[$+V[P++]]);return{v0:Q,v1:W,v2:Y,v3:X,v4:G,v5:K,v6:R,v7:I,v8:z,v9:M,v10:F,v11:w,v12:q,v13:U,v14:H,v15:A}}var G0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},z0=MZ.slice(),PZ=(()=>{let V=Array.from({length:16},(J,Q)=>Q),$=(J)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((Q)=>J[Q]),Z=[];for(let J=0,Q=V;J<7;J++,Q=$(Q))Z.push(...Q);return Uint8Array.from(Z)})();class Q$ extends Z${constructor(V={},$=0){super(64,V.dkLen===void 0?32:V.dkLen);this.chunkPos=0,this.chunksDone=0,this.flags=0,this.stack=[],this.posOut=0,this.bufferOut32=new Uint32Array(16),this.chunkOut=0,this.enableXOF=!0;let{key:Z,context:J}=V,Q=J!==void 0;if(Z!==void 0){if(Q)throw Error('Only "key" or "context" can be specified at same time');let W=f0(Z).slice();C0(W,32),this.IV=x0(W),s(this.IV),this.flags=$|G0.KEYED_HASH}else if(Q){let W=f0(J),Y=new Q$({dkLen:32},G0.DERIVE_KEY_CONTEXT).update(W).digest();this.IV=x0(Y),s(this.IV),this.flags=$|G0.DERIVE_KEY_MATERIAL}else this.IV=z0.slice(),this.flags=$;this.state=this.IV.slice(),this.bufferOut=RZ(this.bufferOut32)}get(){return[]}set(){}b2Compress(V,$,Z,J=0){let{state:Q,pos:W}=this,{h:Y,l:X}=$$(BigInt(V),!0),{v0:G,v1:K,v2:R,v3:I,v4:z,v5:M,v6:F,v7:w,v8:q,v9:U,v10:H,v11:A,v12:P,v13:D,v14:L,v15:k}=J$(PZ,J,Z,7,Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7],z0[0],z0[1],z0[2],z0[3],Y,X,W,$);Q[0]=G^q,Q[1]=K^U,Q[2]=R^H,Q[3]=I^A,Q[4]=z^P,Q[5]=M^D,Q[6]=F^L,Q[7]=w^k}compress(V,$=0,Z=!1){let J=this.flags;if(!this.chunkPos)J|=G0.CHUNK_START;if(this.chunkPos===15||Z)J|=G0.CHUNK_END;if(!Z)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,J,V,$),this.chunkPos+=1,this.chunkPos===16||Z){let Q=this.state;this.state=this.IV.slice();for(let W,Y=this.chunksDone+1;Z||!(Y&1);Y>>=1){if(!(W=this.stack.pop()))break;this.buffer32.set(W,0),this.buffer32.set(Q,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|G0.PARENT,this.buffer32,0),Q=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(Q)}this.pos=0}_cloneInto(V){V=super._cloneInto(V);let{IV:$,flags:Z,state:J,chunkPos:Q,posOut:W,chunkOut:Y,stack:X,chunksDone:G}=this;return V.state.set(J.slice()),V.stack=X.map((K)=>Uint32Array.from(K)),V.IV.set($),V.flags=Z,V.chunkPos=Q,V.chunksDone=G,V.posOut=W,V.chunkOut=Y,V.enableXOF=this.enableXOF,V.bufferOut32.set(this.bufferOut32),V}destroy(){this.destroyed=!0,B0(this.state,this.buffer32,this.IV,this.bufferOut32),B0(...this.stack)}b2CompressOut(){let{state:V,pos:$,flags:Z,buffer32:J,bufferOut32:Q}=this,{h:W,l:Y}=$$(BigInt(this.chunkOut++));s(J);let{v0:X,v1:G,v2:K,v3:R,v4:I,v5:z,v6:M,v7:F,v8:w,v9:q,v10:U,v11:H,v12:A,v13:P,v14:D,v15:L}=J$(PZ,0,J,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],z0[0],z0[1],z0[2],z0[3],Y,W,$,Z);Q[0]=X^w,Q[1]=G^q,Q[2]=K^U,Q[3]=R^H,Q[4]=I^A,Q[5]=z^P,Q[6]=M^D,Q[7]=F^L,Q[8]=V[0]^w,Q[9]=V[1]^q,Q[10]=V[2]^U,Q[11]=V[3]^H,Q[12]=V[4]^A,Q[13]=V[5]^P,Q[14]=V[6]^D,Q[15]=V[7]^L,s(J),s(Q),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,B0(this.buffer.subarray(this.pos));let V=this.flags|G0.ROOT;if(this.stack.length)V|=G0.PARENT,s(this.buffer32),this.compress(this.buffer32,0,!0),s(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else V|=(!this.chunkPos?G0.CHUNK_START:0)|G0.CHUNK_END;this.flags=V,this.b2CompressOut()}writeInto(V){h0(this,!1),C0(V),this.finish();let{blockLen:$,bufferOut:Z}=this;for(let J=0,Q=V.length;J<Q;){if(this.posOut>=$)this.b2CompressOut();let W=Math.min($-this.posOut,Q-J);V.set(Z.subarray(this.posOut,this.posOut+W),J),this.posOut+=W,J+=W}return V}xofInto(V){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(V)}xof(V){return l0(V),this.xofInto(new Uint8Array(V))}digestInto(V){if(FV(V,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto(V),this.destroy(),V}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var UZ=zZ((V)=>new Q$(V));var W$=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function qZ(V){let $=new Uint8Array(W$.length+32);return $.set(W$),$.set(V.subarray(0,32),W$.length),$}function OZ(V){return typeof V==="string"?new TextEncoder().encode(V):V}function m0(V){let $=new ArrayBuffer(V.byteLength);return new Uint8Array($).set(V),$}class Y${verifyKeys=new Map;signKeys=new Map;async genRandomBytes(V){return zV(V)}async gen256BitSecureRandomSeed(){return zV(32)}async encryptXSalsa20Poly1305Combined(V,$){let Z=zV(24),Q=eV($,Z).encrypt(V);return new Uint8Array([...Z,...Q])}async decryptXSalsa20Poly1305Combined(V,$){let Z=V.slice(0,24),J=V.slice(24);return eV($,Z).decrypt(J)}async deriveEd25519KeyPair(V){let $=V,Z=qZ($),J=await globalThis.crypto.subtle.importKey("pkcs8",m0(Z),{name:"Ed25519"},!0,["sign"]),Q=await globalThis.crypto.subtle.exportKey("jwk",J);if(typeof Q.x!=="string")throw Error("Ed25519 JWK missing x");let W=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:Q.x},{name:"Ed25519"},!0,["verify"]),Y=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",W)),X=new Uint8Array(64);return X.set($,0),X.set(Y,32),this.signKeys.set(Q0($),J),this.verifyKeys.set(Q0(Y),W),{keyType:"ed25519",privateKey:X,publicKey:Y}}async importSignKey(V){let $=V.subarray(0,32),Z=Q0($),J=this.signKeys.get(Z);if(J)return J;let Q=qZ($),W=await globalThis.crypto.subtle.importKey("pkcs8",m0(Q),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Z,W),W}async importVerifyKey(V){let $=Q0(V),Z=this.verifyKeys.get($);if(Z)return Z;let J=await globalThis.crypto.subtle.importKey("raw",m0(V),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set($,J),J}async signEd25519(V,$){let Z=OZ(V),J=await this.importSignKey($),Q=await globalThis.crypto.subtle.sign({name:"Ed25519"},J,m0(Z));return new Uint8Array(Q)}async checkSigEd25519(V,$,Z){let J=OZ($);try{let Q=await this.importVerifyKey(Z);return await globalThis.crypto.subtle.verify({name:"Ed25519"},Q,m0(V),m0(J))}catch{return!1}}async blake3(V){return UZ(V)}}var AJ=new Y$,g0=AJ;var WG=Symbol("EntityID");function HZ(V){return"type"in V}var YG=Symbol("MasterSeed"),XG=Symbol("DerivationSeed"),GG=Symbol("PublicKey"),KG=Symbol("PrivateKey"),RG=Symbol("HostSpecificKeyPair"),NG=Symbol("Hash");function DJ(V){if(!V)return!1;if(typeof V!=="object")return!1;if("body"in V===!1)return!1;if("type"in V===!1)return!1;return!0}function _J(V){if(!V.bod||V.bod.length===0){let J={off:V.off,ctr:V.ctr,eid:V.eid};return O(J)}let $=_V(V.bod);if(DJ($)===!1)return console.warn("msg body invalid",$),N(14);let Z={off:V.off,ctr:V.ctr,eid:V.eid,gid:$.gid,pid:$.pid,type:$.type,body:$.body};return O(Z)}class UV{applier;emitter=new y0;clearer;onTypes;constructor(V,$,Z){this.applier=V;this.clearer=$,this.onTypes=Z}apply=async(V)=>{let $=[],Z=[];for(let Y of V){let[X,G]=_J(Y);if(Z.push(G),G!==0)continue;$.push(X)}let{stats:J,types:Q}=await this.applier($),W=[];for(let Y=0;Y<V.length;Y++){let X=Z[Y],G=J[Y];if(X!==0){W.push(X);continue}if(G!==0){W.push(G);continue}W.push(0)}for(let Y of Q)this.emitter.emit(Y,null);if(Q.size>0)this.onTypes?.(Q);return W};clear=async()=>{let V=await this.clearer();if(V!==0)return V;return this.emitter.emitAll(null),V};notify=(V)=>{for(let $ of V)this.emitter.emit($,null)};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}function CZ(V,$){let Z=new m($.eid),[J,Q]=Z.readStruct(Y0);if(Q!==0)return N(Q);let W=new Date(J.ts.getTime()+$.off);if(V!==void 0&&W<=V.updatedAt)return N(15);if(HZ($))return O({eid:$.eid,gid:$.gid,pid:$.pid,type:$.type,createdAt:J.ts,updatedAt:W,ctr:$.ctr,body:$.body});else return O(void 0)}var b="entities",qV="entity_type_created_at",X$="entity_type_updated_at",G$="entity_type_group_id",K$="entity_type_parent_id";function jJ(V){let $={bod:V.body,crd:V.createdAt,...V.ctr!==0?{ctr:V.ctr}:{},eid:d(V.eid),gid:V.gid,pid:V.pid?d(V.pid):void 0,typ:V.type,upd:V.updatedAt};if($.gid===void 0)delete $.gid;if($.pid===void 0)delete $.pid;if($.ctr===void 0)delete $.ctr;return $}function v0(V){return{body:V.bod,createdAt:V.crd,updatedAt:V.upd,ctr:V.ctr??0,type:V.typ,eid:R0(V.eid),gid:V.gid,pid:V.pid?R0(V.pid):void 0}}class TZ{db;async init(){this.db=await new Promise((V,$)=>{let Z=indexedDB.open("db",11);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!Q)throw Error("Transaction is null during upgrade");if(!J.objectStoreNames.contains(b))J.createObjectStore(b,{keyPath:"eid",autoIncrement:!1});let W=Q.objectStore(b);if(!W.indexNames.contains(qV))W.createIndex(qV,["typ","crd"],{unique:!1});if(!W.indexNames.contains(X$))W.createIndex(X$,["typ","upd"],{unique:!1});if(!W.indexNames.contains(G$))W.createIndex(G$,["typ","gid"],{unique:!1});if(!W.indexNames.contains(K$))W.createIndex(K$,["typ","pid"],{unique:!1})},Z.onsuccess=()=>V(Z.result),Z.onerror=()=>$(Z.error)})}apply=async(V)=>{let $=new Set;if(!this.db)return{stats:V.map(()=>16),types:$};let Z=this.db.transaction(b,"readwrite"),J=Z.objectStore(b);return new Promise((Q)=>{let W=Array(V.length).fill(0);if(V.length<1){Q({stats:[],types:$});return}Z.oncomplete=()=>{Q({stats:W,types:$})},Z.onerror=()=>{for(let X=0;X<W.length;X++)if(W[X]===void 0)W[X]=18;Q({stats:W,types:$})};let Y=new Map;for(let X=0;X<V.length;X++){let G=V[X],K=d(G.eid),R={op:G,index:X},I=Y.get(K);if(I)I.push(R);else Y.set(K,[R])}for(let[X,G]of Y){if(G.length<1)continue;let K=J.get(X);K.onsuccess=()=>{let R=K.result,I=R?v0(R):void 0;for(let{op:z,index:M}of G){let[F,w]=CZ(I,z);if(w!==0){W[M]=w;continue}if(F)$.add(F.type);else if(I)$.add(I.type);I=F}if(I){let z=jJ(I),M=J.put(z);M.onerror=(F)=>{F.preventDefault();for(let{index:w}of G)W[w]=18}}else{let z=J.delete(X);z.onerror=()=>{for(let{index:M}of G)W[M]=18}}},K.onerror=()=>{for(let{index:R}of G)W[R]=18}}})};async clear(){if(!this.db)return 16;let V=this.db.transaction(b,"readwrite"),$=V.objectStore(b);return new Promise((Z)=>{V.oncomplete=()=>Z(0),V.onerror=()=>Z(18),$.clear()})}async getEnt(V){if(!this.db)return N(16);let $=d(V),J=this.db.transaction(b,"readonly").objectStore(b);return new Promise((Q)=>{let W=J.get($);W.onsuccess=()=>{let Y=W.result;if(!Y)Q(O(void 0));else{let X=v0(Y);Q(O(X))}},W.onerror=()=>Q(N(18))})}async getAllOfTypeUpdatedBetween(V,$,Z){if(!this.db)return N(16);let Q=this.db.transaction(b,"readonly").objectStore(b).index(X$);return new Promise((W)=>{let Y=Q.getAll(IDBKeyRange.bound([V,$],[V,Z]));Y.onsuccess=()=>{let X=Y.result;W(O(X.map(v0)))},Y.onerror=()=>W(N(18))})}async getGroupMembers(V,$){if(!this.db)return N(16);let J=this.db.transaction(b,"readonly").objectStore(b).index(G$);return new Promise((Q)=>{let W=J.getAll(IDBKeyRange.only([V,$]));W.onsuccess=()=>{let Y=W.result;Q(O(Y.map(v0)))},W.onerror=()=>Q(N(18))})}async getAllOfType(V){if(!this.db)return N(16);let Z=this.db.transaction(b,"readonly").objectStore(b).index(qV);return new Promise((J)=>{let Q=Z.getAll(IDBKeyRange.bound([V],[V,[]]));Q.onsuccess=()=>{let W=Q.result;J(O(W.map(v0)))},Q.onerror=()=>J(N(18))})}async getAllEntities(V){if(!this.db)return N(16);if("pid"in V){let $=d(V.pid),J=this.db.transaction(b,"readonly").objectStore(b).index(K$);return new Promise((Q)=>{let W=J.getAll(IDBKeyRange.only([V.type,$]));W.onsuccess=()=>{let X=W.result.map(v0);Q(O(X))},W.onerror=()=>Q(N(18))})}else if("gid"in V)return await this.getGroupMembers(V.type,V.gid);else if("updatedBetween"in V)return await this.getAllOfTypeUpdatedBetween(V.type,V.updatedBetween.start,V.updatedBetween.end);return await this.getAllOfType(V.type)}async getEntities(V){let[$,Z]=await this.getAllEntities(V);if(Z!==0)return N(Z);return O($)}async countEntities({type:V}){if(!this.db)return N(16);let Z=this.db.transaction(b,"readonly").objectStore(b).index(qV);return new Promise((J)=>{let Q=IDBKeyRange.bound([V],[V,[]]),W=Z.count(Q);W.onsuccess=()=>J(O(W.result)),W.onerror=()=>J(N(18))})}}async function AZ(){let V=new TZ;return await V.init(),V}class R${db;constructor(V){this.db=V}async enq(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction($0,"readwrite"),J=Z.objectStore($0);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=`${Y.host}:${Y.seq}`;J.put(Y,X)}})}async deq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction($0,"readwrite"),Q=J.objectStore($0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let G=`${V}:${X}`;Q.delete(G)}})}async list(){let $=this.db.transaction($0,"readonly").objectStore($0);return new Promise((Z,J)=>{let Q=$.getAll();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async count(){let $=this.db.transaction($0,"readonly").objectStore($0);return new Promise((Z,J)=>{let Q=$.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction($0,"readwrite"),$=V.objectStore($0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}function DZ(V){return{label:V.label,handle:new URL(V.handle),idx:V.idx,lastSeq:V.lastSeq||0,clockOffset:V.clockOffset,subscription:V.subscription}}class N${db;constructor(V){this.db=V}async add(V){return this.put(V)}async put(V){let $={...V,handle:V.handle.toString(),lastSeq:V.lastSeq??0},Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error),J.put($)})}async touch(V,$){let Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);let Y=J.get(V);Y.onsuccess=()=>{let X=Y.result;if(!X)return;let G=X.lastSeq||0;if($<=G)return;J.put({...X,lastSeq:$})}})}async get(V){let Z=this.db.transaction(t,"readonly").objectStore(t);return new Promise((J,Q)=>{let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)J(void 0);else J(DZ(Y))},W.onerror=()=>Q(W.error)})}async set(V,$){let Z=await this.get(V);if(!Z)return 13;try{return await this.put({...Z,...$}),0}catch{return 18}}async del(V){let $=this.db.transaction(t,"readwrite"),Z=$.objectStore(t);return new Promise((J,Q)=>{$.oncomplete=()=>J(),$.onerror=()=>Q($.error),Z.delete(V)})}async list(){let $=this.db.transaction(t,"readonly").objectStore(t);return new Promise((Z,J)=>{let Q=$.getAll();Q.onsuccess=()=>{let W=Q.result;Z(W.map(DZ))},Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(t,"readwrite"),$=V.objectStore(t);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}function LJ(V){return V===!0||V==="t"}function I$(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld===void 0?!1:LJ(V.apld)}}async function c0(V,$,Z){let J=I$($),Q=J.body?.length??0,W;if(J.body&&Q>0)W=await Z.blake3(J.body);let Y={eid:J.eid,off:J.off??0,ctr:J.ctr??0,len:Q,hsh:W};return{hash:V,head:Y,body:J.body,applied:J.apld}}function _Z(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld?"t":"f"}}class w${crypto;db;constructor(V,$){this.crypto=$;this.db=V}async add(V){let $=this.db.transaction(i,"readwrite"),Z=$.objectStore(i);return new Promise((J)=>{if(V.length===0){J([]);return}let Q=Array(V.length).fill(0);$.oncomplete=()=>J(Q),$.onerror=()=>{for(let W=0;W<Q.length;W++)Q[W]=18;J(Q)};for(let W=0;W<V.length;W++){let{key:Y,data:X}=V[W],G=d(Y),K=Z.put(_Z(X),G);K.onerror=(R)=>{R.preventDefault(),Q[W]=18}}})}async del(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(i,"readwrite"),J=Z.objectStore(i);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=d(Y);J.delete(X)}})}async get(V){let Z=this.db.transaction(i,"readonly").objectStore(i);return new Promise((J,Q)=>{let W=d(V),Y=Z.get(W);Y.onsuccess=async()=>{let X=Y.result;if(X)J(await c0(V,X,this.crypto));else J(void 0)},Y.onerror=()=>Q(Y.error)})}async has(V){return await this.get(V)!==void 0}async list(){let $=this.db.transaction(i,"readonly").objectStore(i);return new Promise((Z,J)=>{let Q=[],W=$.openCursor();W.onsuccess=async(Y)=>{let X=Y.target.result;if(X){let{key:G,value:K}=X,R=R0(G),I=await c0(R,K,this.crypto);Q.push(I),X.continue()}else Z(Q)},W.onerror=()=>J(W.error)})}async last(V){let Z=this.db.transaction(i,"readonly").objectStore(i);return new Promise((J,Q)=>{let W,Y=Z.openCursor();Y.onsuccess=async(X)=>{let G=X.target.result;if(G){let{key:K,value:R}=G;if(O0(V,R.eid)){if(!W||(R.ctr??0)>(W.data.ctr??0)||(R.ctr??0)===(W.data.ctr??0)&&(R.off??0)>(W.data.off??0))W={key:K,data:R}}G.continue()}else if(W){let K=R0(W.key);J(await c0(K,W.data,this.crypto))}else J(void 0)},Y.onerror=()=>Q(Y.error)})}async listUnapplied(){let Z=this.db.transaction(i,"readonly").objectStore(i).index(OV);return new Promise((J,Q)=>{let W=[],Y=Z.openCursor(IDBKeyRange.only("f"));Y.onsuccess=(X)=>{let G=X.target.result;if(G){let{primaryKey:K,value:R}=G;W.push({hash:R0(K),data:R}),G.continue()}else Promise.all(W.map(({hash:K,data:R})=>c0(K,R,this.crypto))).then(J).catch(Q)},Y.onerror=()=>Q(Y.error)})}async markApplied(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(i,"readwrite"),J=Z.objectStore(i);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=d(Y),G=J.get(X);G.onsuccess=()=>{let K=G.result;if(!K)return;let R=I$(K);J.put(_Z({...R,apld:!0}),X)},G.onerror=(K)=>{K.preventDefault()}}})}async wipe(){let V=this.db.transaction(i,"readwrite"),$=V.objectStore(i);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}class HV{seed;crypto;constructor(V,$){this.seed=V,this.crypto=$}async deriveFromKDM(V){let $=n0(this.seed,V);return await this.crypto.blake3($)}async derive(V,$=0){let Z=new TextEncoder().encode(V),J=new Uint8Array(8);new DataView(J.buffer).setBigUint64(0,BigInt($),!1);let Q=n0(Z,J);return await this.deriveFromKDM(Q)}}class z${enclave;db;constructor(V){this.db=V}async save(V){let $=Q0(V),Z=this.db.transaction(M0,"readwrite"),J=Z.objectStore(M0);return new Promise((Q,W)=>{Z.oncomplete=()=>{this.enclave=new HV(V,g0),Q(this.enclave)},Z.onerror=()=>W(Z.error),J.put($,"seed")})}async load(){if(this.enclave)return this.enclave;let $=this.db.transaction(M0,"readonly").objectStore(M0);return new Promise((Z,J)=>{let Q=$.get("seed");Q.onsuccess=()=>{let W=Q.result;if(!W)Z(void 0);else{let Y=JV(W);this.enclave=new HV(Y,g0),Z(this.enclave)}},Q.onerror=()=>J(Q.error)})}async wipe(){this.enclave=void 0;let V=this.db.transaction(M0,"readwrite"),$=V.objectStore(M0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.delete("seed")})}}class M${db;constructor(V){this.db=V}async enq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(Z0,"readwrite"),Q=J.objectStore(Z0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let G=Q0(X);Q.put({host:V,hash:G})}})}async deq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(Z0,"readwrite"),Q=J.objectStore(Z0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let G=Q0(X);Q.delete([V,G])}})}async list(V){let Z=this.db.transaction(Z0,"readonly").objectStore(Z0);return new Promise((J,Q)=>{let W=Z.getAll();W.onsuccess=()=>{let X=W.result.filter((G)=>G.host===V).map((G)=>G.hash);J(X.map((G)=>JV(G)))},W.onerror=()=>Q(W.error)})}async count(){let $=this.db.transaction(Z0,"readonly").objectStore(Z0);return new Promise((Z,J)=>{let Q=$.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(Z0,"readwrite"),$=V.objectStore(Z0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}var M0="seedMeta",t="hosts",Z0="uploadQueue",$0="downloadQueue",i="messages",OV="apld",kJ=3;class jZ{seed;hosts;uploads;downloads;messages;db;constructor(V,$){this.db=V,this.seed=new z$(V),this.hosts=new N$(V),this.uploads=new M$(V),this.downloads=new R$(V),this.messages=new w$(V,$)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function EJ(){return new Promise((V,$)=>{let Z=indexedDB.open("diplomatic-store-db",kJ);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!J.objectStoreNames.contains(M0))J.createObjectStore(M0);if(!J.objectStoreNames.contains(t))J.createObjectStore(t,{keyPath:"label"});if(!J.objectStoreNames.contains(Z0))J.createObjectStore(Z0,{keyPath:["host","hash"]});if(!J.objectStoreNames.contains($0))J.createObjectStore($0);let W;if(!J.objectStoreNames.contains(i))W=J.createObjectStore(i);else{if(!Q)throw Error("missing upgrade transaction for messages store");W=Q.objectStore(i)}if(!W.indexNames.contains(OV))W.createIndex(OV,"apld",{unique:!1})},Z.onsuccess=()=>V(Z.result),Z.onerror=()=>$(Z.error)})}async function LZ(V){let $=await EJ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new jZ($,V)}class F${client;post;whenReady;resolveReady;rejectReady;constructor(V){this.post=V,this.whenReady=new Promise(($,Z)=>{this.resolveReady=$,this.rejectReady=Z})}async init(){try{let V=await LZ(g0),$=await AZ(),Z=new UV($.apply,()=>$.clear(),(W)=>{this.post({kind:"dirty",types:Array.from(W)})}),J=Z.clear;Z.clear=async()=>{let W=await J();if(W===0)this.post({kind:"wiped"});return W};let Q=new hV(new EV,Z,V,u$,g0);this.client=Q,Q.clientState.listen(()=>{this.emitClientState()}),Q.xferState.listen(()=>{this.emitXferState()}),this.post({kind:"ready"}),this.markReady(),await this.emitClientState(),await this.emitXferState()}catch(V){let $=V instanceof Error?V:Error(String(V));throw this.failReady($),$}}markReady(){let V=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V()}failReady(V){let $=this.rejectReady;if(this.resolveReady=void 0,this.rejectReady=void 0,$)$(V)}requireClient(){if(!this.client)throw Error("WorkerRuntime not initialized");return this.client}async emitClientState(){let V=this.client;if(!V)return;let $=await V.clientState.get();this.post({kind:"clientState",state:$})}async emitXferState(){let V=this.client;if(!V)return;let $=await V.xferState.get();this.post({kind:"xferState",state:$})}hostFromSerialized(V){return{handle:new URL(V.handle),label:V.label,idx:V.idx}}async handle(V){await this.whenReady;let $=this.requireClient();switch(V.op){case"ping":return"pong";case"setSeed":{await $.setSeed(SJ(V.seed));return}case"link":{await $.link(this.hostFromSerialized(V.host),V.connect??!0);return}case"unlink":{await $.unlink(V.label);return}case"connect":{await $.connect(V.listen??!0,V.sync??!0);return}case"disconnect":{await $.disconnect();return}case"sync":return await $.sync();case"wipe":{await $.wipe();return}case"insertRaw":{let[Z,J]=await $.insertRaw(kZ(V.body));if(J!==0)throw new W0(J);return Z}case"upsertRaw":{let[Z,J]=await $.upsertRaw(d0(V.eid),V.body!==void 0?kZ(V.body):void 0,V.force);if(J!==0)throw new W0(J);return Z}case"insert":{let[Z,J]=await $.insert({type:V.params.type,body:V.params.body,gid:V.params.gid,pid:V.params.pid!==void 0?d0(V.params.pid):void 0});if(J!==0)throw new W0(J);return Z}case"upsert":{let[Z,J]=await $.upsert({type:V.params.type,body:V.params.body,eid:V.params.eid!==void 0?d0(V.params.eid):void 0,gid:V.params.gid,pid:V.params.pid!==void 0?d0(V.params.pid):void 0},V.force);if(J!==0)throw new W0(J);return Z}case"delete":{let[Z,J]=await $.delete(d0(V.eid));if(J!==0)throw new W0(J);return Z}case"import":{let Z=V.bytes.slice(),J=new Blob([Z]),Q=new File([J],"import.dip");return await $.import(Q)}case"export":{let[Z,J]=await $.exportBytes();if(J!==0)throw new W0(J);if(!Z)throw new W0(12);return Z}case"getClientState":return await $.clientState.get();case"getXferState":return await $.xferState.get();default:{let Z=V;throw Error("unknown worker command")}}}}class W0 extends Error{status;constructor(V){super(`WorkerStatusError: ${j[V]}`);this.status=V;this.name="WorkerStatusError"}}function P$(V,$){return{kind:"reply",id:V,ok:!0,result:$}}function U$(V,$){return{kind:"reply",id:V,ok:!1,status:$}}function SJ(V){if(V.length!==32)throw new W0(10);return V}function d0(V){return V}function kZ(V){return V}var T0=globalThis,EZ=new F$((V,$)=>{if($&&$.length>0)T0.postMessage(V,$);else T0.postMessage(V)});T0.onmessage=(V)=>{let $=V.data;if(!C$($))return;xJ($)};async function xJ(V){try{let $=await EZ.handle(V);if(V.op==="export"&&$ instanceof Uint8Array){let Z=$.slice();T0.postMessage(P$(V.id,Z),[Z.buffer]);return}T0.postMessage(P$(V.id,$))}catch($){if($ instanceof W0){T0.postMessage(U$(V.id,$.status));return}console.error("worker command failed",$),T0.postMessage(U$(V.id,12))}}EZ.init().catch((V)=>{console.error("worker init failed",V)});
1
+ var F0=64;var H$=32,P0=8;var a0=32;var C$=30000,T$=512,j;((H)=>{H[H.Success=0]="Success";H[H.InvalidSignature=3]="InvalidSignature";H[H.ClockOutOfSync=4]="ClockOutOfSync";H[H.UserNotRegistered=5]="UserNotRegistered";H[H.ServerMisconfigured=6]="ServerMisconfigured";H[H.MissingBody=7]="MissingBody";H[H.ExtraBodyContent=8]="ExtraBodyContent";H[H.MissingParam=9]="MissingParam";H[H.InvalidParam=10]="InvalidParam";H[H.InvalidRequest=11]="InvalidRequest";H[H.InternalError=12]="InternalError";H[H.NotFound=13]="NotFound";H[H.InvalidMessage=14]="InvalidMessage";H[H.NoChange=15]="NoChange";H[H.DatabaseClosed=16]="DatabaseClosed";H[H.StorageError=17]="StorageError";H[H.DatabaseError=18]="DatabaseError";H[H.HashMismatch=19]="HashMismatch";H[H.DecryptionError=20]="DecryptionError";H[H.NotImplemented=21]="NotImplemented";H[H.MissingSeed=22]="MissingSeed";H[H.OutOfBounds=23]="OutOfBounds";H[H.HostError=24]="HostError";H[H.CommunicationError=25]="CommunicationError";H[H.VarLimitExceeded=26]="VarLimitExceeded";H[H.InvalidResponse=27]="InvalidResponse";H[H.ConnectionClosed=28]="ConnectionClosed"})(j||={});function A$(V){if(!V||typeof V!=="object")return!1;if(!("op"in V)||!("id"in V))return!1;return typeof V.op==="string"&&typeof V.id==="number"}function D$(V){let $=V.length,Z=0,J=0;while(J<$){let Q=V.charCodeAt(J++);if((Q&4294967168)===0){Z++;continue}else if((Q&4294965248)===0)Z+=2;else{if(Q>=55296&&Q<=56319){if(J<$){let W=V.charCodeAt(J);if((W&64512)===56320)++J,Q=((Q&1023)<<10)+(W&1023)+65536}}if((Q&4294901760)===0)Z+=3;else Z+=4}}return Z}function mZ(V,$,Z){let J=V.length,Q=Z,W=0;while(W<J){let Y=V.charCodeAt(W++);if((Y&4294967168)===0){$[Q++]=Y;continue}else if((Y&4294965248)===0)$[Q++]=Y>>6&31|192;else{if(Y>=55296&&Y<=56319){if(W<J){let X=V.charCodeAt(W);if((X&64512)===56320)++W,Y=((Y&1023)<<10)+(X&1023)+65536}}if((Y&4294901760)===0)$[Q++]=Y>>12&15|224,$[Q++]=Y>>6&63|128;else $[Q++]=Y>>18&7|240,$[Q++]=Y>>12&63|128,$[Q++]=Y>>6&63|128}$[Q++]=Y&63|128}}var gZ=new TextEncoder,vZ=50;function iZ(V,$,Z){gZ.encodeInto(V,$.subarray(Z))}function _$(V,$,Z){if(V.length>vZ)iZ(V,$,Z);else mZ(V,$,Z)}var uZ=4096;function TV(V,$,Z){let J=$,Q=J+Z,W=[],Y="";while(J<Q){let X=V[J++];if((X&128)===0)W.push(X);else if((X&224)===192){let G=V[J++]&63;W.push((X&31)<<6|G)}else if((X&240)===224){let G=V[J++]&63,K=V[J++]&63;W.push((X&31)<<12|G<<6|K)}else if((X&248)===240){let G=V[J++]&63,K=V[J++]&63,R=V[J++]&63,I=(X&7)<<18|G<<12|K<<6|R;if(I>65535)I-=65536,W.push(I>>>10&1023|55296),I=56320|I&1023;W.push(I)}else W.push(X);if(W.length>=uZ)Y+=String.fromCharCode(...W),W.length=0}if(W.length>0)Y+=String.fromCharCode(...W);return Y}var bZ=new TextDecoder,yZ=200;function nZ(V,$,Z){let J=V.subarray($,$+Z);return bZ.decode(J)}function j$(V,$,Z){if(Z>yZ)return nZ(V,$,Z);else return TV(V,$,Z)}class k0{type;data;constructor(V,$){this.type=V,this.data=$}}class a extends Error{constructor(V){super(V);let $=Object.create(a.prototype);Object.setPrototypeOf(this,$),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:a.name})}}var E0=4294967295;function L$(V,$,Z){let J=Z/4294967296,Q=Z;V.setUint32($,J),V.setUint32($+4,Q)}function s0(V,$,Z){let J=Math.floor(Z/4294967296),Q=Z;V.setUint32($,J),V.setUint32($+4,Q)}function t0(V,$){let Z=V.getInt32($),J=V.getUint32($+4);return Z*4294967296+J}function k$(V,$){let Z=V.getUint32($),J=V.getUint32($+4);return Z*4294967296+J}var pZ=-1,lZ=4294967295,hZ=17179869183;function rZ({sec:V,nsec:$}){if(V>=0&&$>=0&&V<=hZ)if($===0&&V<=lZ){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,V),Z}else{let Z=V/4294967296,J=V&4294967295,Q=new Uint8Array(8),W=new DataView(Q.buffer);return W.setUint32(0,$<<2|Z&3),W.setUint32(4,J),Q}else{let Z=new Uint8Array(12),J=new DataView(Z.buffer);return J.setUint32(0,$),s0(J,4,V),Z}}function cZ(V){let $=V.getTime(),Z=Math.floor($/1000),J=($-Z*1000)*1e6,Q=Math.floor(J/1e9);return{sec:Z+Q,nsec:J-Q*1e9}}function dZ(V){if(V instanceof Date){let $=cZ(V);return rZ($)}else return null}function oZ(V){let $=new DataView(V.buffer,V.byteOffset,V.byteLength);switch(V.byteLength){case 4:{let Z=$.getUint32(0),J=0;return{sec:Z,nsec:0}}case 8:{let Z=$.getUint32(0),J=$.getUint32(4),Q=(Z&3)*4294967296+J,W=Z>>>2;return{sec:Q,nsec:W}}case 12:{let Z=t0($,4),J=$.getUint32(0);return{sec:Z,nsec:J}}default:throw new a(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${V.length}`)}}function aZ(V){let $=oZ(V);return new Date($.sec*1000+$.nsec/1e6)}var E$={type:pZ,encode:dZ,decode:aZ};class S0{static defaultCodec=new S0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(E$)}register({type:V,encode:$,decode:Z}){if(V>=0)this.encoders[V]=$,this.decoders[V]=Z;else{let J=-1-V;this.builtInEncoders[J]=$,this.builtInDecoders[J]=Z}}tryToEncode(V,$){for(let Z=0;Z<this.builtInEncoders.length;Z++){let J=this.builtInEncoders[Z];if(J!=null){let Q=J(V,$);if(Q!=null){let W=-1-Z;return new k0(W,Q)}}}for(let Z=0;Z<this.encoders.length;Z++){let J=this.encoders[Z];if(J!=null){let Q=J(V,$);if(Q!=null)return new k0(Z,Q)}}if(V instanceof k0)return V;return null}decode(V,$,Z){let J=$<0?this.builtInDecoders[-1-$]:this.decoders[$];if(J)return J(V,$,Z);else return new k0($,V)}}function sZ(V){return V instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&V instanceof SharedArrayBuffer}function i0(V){if(V instanceof Uint8Array)return V;else if(ArrayBuffer.isView(V))return new Uint8Array(V.buffer,V.byteOffset,V.byteLength);else if(sZ(V))return new Uint8Array(V);else return Uint8Array.from(V)}var tZ=100,eZ=2048;class e0{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??S0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.maxDepth=V?.maxDepth??tZ,this.initialBufferSize=V?.initialBufferSize??eZ,this.sortKeys=V?.sortKeys??!1,this.forceFloat32=V?.forceFloat32??!1,this.ignoreUndefined=V?.ignoreUndefined??!1,this.forceIntegerToFloat=V?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new e0({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(V){if(this.entered)return this.clone().encodeSharedRef(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(V){if(this.entered)return this.clone().encode(V);try{return this.entered=!0,this.reinitializeState(),this.doEncode(V,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(V,$){if($>this.maxDepth)throw Error(`Too deep objects in depth ${$}`);if(V==null)this.encodeNil();else if(typeof V==="boolean")this.encodeBoolean(V);else if(typeof V==="number")if(!this.forceIntegerToFloat)this.encodeNumber(V);else this.encodeNumberAsFloat(V);else if(typeof V==="string")this.encodeString(V);else if(this.useBigInt64&&typeof V==="bigint")this.encodeBigInt64(V);else this.encodeObject(V,$)}ensureBufferSizeToWrite(V){let $=this.pos+V;if(this.view.byteLength<$)this.resizeBuffer($*2)}resizeBuffer(V){let $=new ArrayBuffer(V),Z=new Uint8Array($),J=new DataView($);Z.set(this.bytes),this.view=J,this.bytes=Z}encodeNil(){this.writeU8(192)}encodeBoolean(V){if(V===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber(V){if(!this.forceIntegerToFloat&&Number.isSafeInteger(V))if(V>=0)if(V<128)this.writeU8(V);else if(V<256)this.writeU8(204),this.writeU8(V);else if(V<65536)this.writeU8(205),this.writeU16(V);else if(V<4294967296)this.writeU8(206),this.writeU32(V);else if(!this.useBigInt64)this.writeU8(207),this.writeU64(V);else this.encodeNumberAsFloat(V);else if(V>=-32)this.writeU8(224|V+32);else if(V>=-128)this.writeU8(208),this.writeI8(V);else if(V>=-32768)this.writeU8(209),this.writeI16(V);else if(V>=-2147483648)this.writeU8(210),this.writeI32(V);else if(!this.useBigInt64)this.writeU8(211),this.writeI64(V);else this.encodeNumberAsFloat(V);else this.encodeNumberAsFloat(V)}encodeNumberAsFloat(V){if(this.forceFloat32)this.writeU8(202),this.writeF32(V);else this.writeU8(203),this.writeF64(V)}encodeBigInt64(V){if(V>=BigInt(0))this.writeU8(207),this.writeBigUint64(V);else this.writeU8(211),this.writeBigInt64(V)}writeStringHeader(V){if(V<32)this.writeU8(160+V);else if(V<256)this.writeU8(217),this.writeU8(V);else if(V<65536)this.writeU8(218),this.writeU16(V);else if(V<4294967296)this.writeU8(219),this.writeU32(V);else throw Error(`Too long string: ${V} bytes in UTF-8`)}encodeString(V){let Z=D$(V);this.ensureBufferSizeToWrite(5+Z),this.writeStringHeader(Z),_$(V,this.bytes,this.pos),this.pos+=Z}encodeObject(V,$){let Z=this.extensionCodec.tryToEncode(V,this.context);if(Z!=null)this.encodeExtension(Z);else if(Array.isArray(V))this.encodeArray(V,$);else if(ArrayBuffer.isView(V))this.encodeBinary(V);else if(typeof V==="object")this.encodeMap(V,$);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply(V)}`)}encodeBinary(V){let $=V.byteLength;if($<256)this.writeU8(196),this.writeU8($);else if($<65536)this.writeU8(197),this.writeU16($);else if($<4294967296)this.writeU8(198),this.writeU32($);else throw Error(`Too large binary: ${$}`);let Z=i0(V);this.writeU8a(Z)}encodeArray(V,$){let Z=V.length;if(Z<16)this.writeU8(144+Z);else if(Z<65536)this.writeU8(220),this.writeU16(Z);else if(Z<4294967296)this.writeU8(221),this.writeU32(Z);else throw Error(`Too large array: ${Z}`);for(let J of V)this.doEncode(J,$+1)}countWithoutUndefined(V,$){let Z=0;for(let J of $)if(V[J]!==void 0)Z++;return Z}encodeMap(V,$){let Z=Object.keys(V);if(this.sortKeys)Z.sort();let J=this.ignoreUndefined?this.countWithoutUndefined(V,Z):Z.length;if(J<16)this.writeU8(128+J);else if(J<65536)this.writeU8(222),this.writeU16(J);else if(J<4294967296)this.writeU8(223),this.writeU32(J);else throw Error(`Too large map object: ${J}`);for(let Q of Z){let W=V[Q];if(!(this.ignoreUndefined&&W===void 0))this.encodeString(Q),this.doEncode(W,$+1)}}encodeExtension(V){if(typeof V.data==="function"){let Z=V.data(this.pos+6),J=Z.length;if(J>=4294967296)throw Error(`Too large extension object: ${J}`);this.writeU8(201),this.writeU32(J),this.writeI8(V.type),this.writeU8a(Z);return}let $=V.data.length;if($===1)this.writeU8(212);else if($===2)this.writeU8(213);else if($===4)this.writeU8(214);else if($===8)this.writeU8(215);else if($===16)this.writeU8(216);else if($<256)this.writeU8(199),this.writeU8($);else if($<65536)this.writeU8(200),this.writeU16($);else if($<4294967296)this.writeU8(201),this.writeU32($);else throw Error(`Too large extension object: ${$}`);this.writeI8(V.type),this.writeU8a(V.data)}writeU8(V){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,V),this.pos++}writeU8a(V){let $=V.length;this.ensureBufferSizeToWrite($),this.bytes.set(V,this.pos),this.pos+=$}writeI8(V){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,V),this.pos++}writeU16(V){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,V),this.pos+=2}writeI16(V){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,V),this.pos+=2}writeU32(V){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,V),this.pos+=4}writeI32(V){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,V),this.pos+=4}writeF32(V){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,V),this.pos+=4}writeF64(V){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,V),this.pos+=8}writeU64(V){this.ensureBufferSizeToWrite(8),L$(this.view,this.pos,V),this.pos+=8}writeI64(V){this.ensureBufferSizeToWrite(8),s0(this.view,this.pos,V),this.pos+=8}writeBigUint64(V){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,V),this.pos+=8}writeBigInt64(V){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,V),this.pos+=8}}function VV(V,$){return new e0($).encodeSharedRef(V)}function $V(V){return`${V<0?"-":""}0x${Math.abs(V).toString(16).padStart(2,"0")}`}var VJ=16,$J=16;class AV{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(V=VJ,$=$J){this.maxKeyLength=V,this.maxLengthPerKey=$,this.caches=[];for(let Z=0;Z<this.maxKeyLength;Z++)this.caches.push([])}canBeCached(V){return V>0&&V<=this.maxKeyLength}find(V,$,Z){let J=this.caches[Z-1];V:for(let Q of J){let W=Q.bytes;for(let Y=0;Y<Z;Y++)if(W[Y]!==V[$+Y])continue V;return Q.str}return null}store(V,$){let Z=this.caches[V.length-1],J={bytes:V,str:$};if(Z.length>=this.maxLengthPerKey)Z[Math.random()*Z.length|0]=J;else Z.push(J)}decode(V,$,Z){let J=this.find(V,$,Z);if(J!=null)return this.hit++,J;this.miss++;let Q=TV(V,$,Z),W=Uint8Array.prototype.slice.call(V,$,$+Z);return this.store(W,Q),Q}}var DV="array",b0="map_key",x$="map_value",ZJ=(V)=>{if(typeof V==="string"||typeof V==="number")return V;throw new a("The type of key must be string or number but "+typeof V)};class B${stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(V){let $=this.getUninitializedStateFromPool();$.type=DV,$.position=0,$.size=V,$.array=Array(V)}pushMapState(V){let $=this.getUninitializedStateFromPool();$.type=b0,$.readCount=0,$.size=V,$.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let V={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(V)}return this.stack[this.stackHeadPosition]}release(V){if(this.stack[this.stackHeadPosition]!==V)throw Error("Invalid stack state. Released state is not on top of the stack.");if(V.type===DV){let Z=V;Z.size=0,Z.array=void 0,Z.position=0,Z.type=void 0}if(V.type===b0||V.type===x$){let Z=V;Z.size=0,Z.map=void 0,Z.readCount=0,Z.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var u0=-1,_V=new DataView(new ArrayBuffer(0)),JJ=new Uint8Array(_V.buffer);try{_V.getInt8(0)}catch(V){if(!(V instanceof RangeError))throw Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var S$=RangeError("Insufficient data"),QJ=new AV;class ZV{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=_V;bytes=JJ;headByte=u0;stack=new B$;entered=!1;constructor(V){this.extensionCodec=V?.extensionCodec??S0.defaultCodec,this.context=V?.context,this.useBigInt64=V?.useBigInt64??!1,this.rawStrings=V?.rawStrings??!1,this.maxStrLength=V?.maxStrLength??E0,this.maxBinLength=V?.maxBinLength??E0,this.maxArrayLength=V?.maxArrayLength??E0,this.maxMapLength=V?.maxMapLength??E0,this.maxExtLength=V?.maxExtLength??E0,this.keyDecoder=V?.keyDecoder!==void 0?V.keyDecoder:QJ,this.mapKeyConverter=V?.mapKeyConverter??ZJ}clone(){return new ZV({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=u0,this.stack.reset()}setBuffer(V){let $=i0(V);this.bytes=$,this.view=new DataView($.buffer,$.byteOffset,$.byteLength),this.pos=0}appendBuffer(V){if(this.headByte===u0&&!this.hasRemaining(1))this.setBuffer(V);else{let $=this.bytes.subarray(this.pos),Z=i0(V),J=new Uint8Array($.length+Z.length);J.set($),J.set(Z,$.length),this.setBuffer(J)}}hasRemaining(V){return this.view.byteLength-this.pos>=V}createExtraByteError(V){let{view:$,pos:Z}=this;return RangeError(`Extra ${$.byteLength-Z} of ${$.byteLength} byte(s) found at buffer[${V}]`)}decode(V){if(this.entered)return this.clone().decode(V);try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);let $=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return $}finally{this.entered=!1}}*decodeMulti(V){if(this.entered){yield*this.clone().decodeMulti(V);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer(V);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(V){if(this.entered)return this.clone().decodeAsync(V);try{this.entered=!0;let $=!1,Z;for await(let Y of V){if($)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(Y);try{Z=this.doDecodeSync(),$=!0}catch(X){if(!(X instanceof RangeError))throw X}this.totalPos+=this.pos}if($){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Z}let{headByte:J,pos:Q,totalPos:W}=this;throw RangeError(`Insufficient data in parsing ${$V(J)} at ${W} (${Q} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(V){return this.decodeMultiAsync(V,!0)}decodeStream(V){return this.decodeMultiAsync(V,!1)}async*decodeMultiAsync(V,$){if(this.entered){yield*this.clone().decodeMultiAsync(V,$);return}try{this.entered=!0;let Z=$,J=-1;for await(let Q of V){if($&&J===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(Q),Z)J=this.readArraySize(),Z=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--J===0)break}catch(W){if(!(W instanceof RangeError))throw W}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){V:while(!0){let V=this.readHeadByte(),$;if(V>=224)$=V-256;else if(V<192)if(V<128)$=V;else if(V<144){let J=V-128;if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V<160){let J=V-144;if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else{let J=V-160;$=this.decodeString(J,0)}else if(V===192)$=null;else if(V===194)$=!1;else if(V===195)$=!0;else if(V===202)$=this.readF32();else if(V===203)$=this.readF64();else if(V===204)$=this.readU8();else if(V===205)$=this.readU16();else if(V===206)$=this.readU32();else if(V===207)if(this.useBigInt64)$=this.readU64AsBigInt();else $=this.readU64();else if(V===208)$=this.readI8();else if(V===209)$=this.readI16();else if(V===210)$=this.readI32();else if(V===211)if(this.useBigInt64)$=this.readI64AsBigInt();else $=this.readI64();else if(V===217){let J=this.lookU8();$=this.decodeString(J,1)}else if(V===218){let J=this.lookU16();$=this.decodeString(J,2)}else if(V===219){let J=this.lookU32();$=this.decodeString(J,4)}else if(V===220){let J=this.readU16();if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else if(V===221){let J=this.readU32();if(J!==0){this.pushArrayState(J),this.complete();continue V}else $=[]}else if(V===222){let J=this.readU16();if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V===223){let J=this.readU32();if(J!==0){this.pushMapState(J),this.complete();continue V}else $={}}else if(V===196){let J=this.lookU8();$=this.decodeBinary(J,1)}else if(V===197){let J=this.lookU16();$=this.decodeBinary(J,2)}else if(V===198){let J=this.lookU32();$=this.decodeBinary(J,4)}else if(V===212)$=this.decodeExtension(1,0);else if(V===213)$=this.decodeExtension(2,0);else if(V===214)$=this.decodeExtension(4,0);else if(V===215)$=this.decodeExtension(8,0);else if(V===216)$=this.decodeExtension(16,0);else if(V===199){let J=this.lookU8();$=this.decodeExtension(J,1)}else if(V===200){let J=this.lookU16();$=this.decodeExtension(J,2)}else if(V===201){let J=this.lookU32();$=this.decodeExtension(J,4)}else throw new a(`Unrecognized type byte: ${$V(V)}`);this.complete();let Z=this.stack;while(Z.length>0){let J=Z.top();if(J.type===DV)if(J.array[J.position]=$,J.position++,J.position===J.size)$=J.array,Z.release(J);else continue V;else if(J.type===b0){if($==="__proto__")throw new a("The key __proto__ is not allowed");J.key=this.mapKeyConverter($),J.type=x$;continue V}else if(J.map[J.key]=$,J.readCount++,J.readCount===J.size)$=J.map,Z.release(J);else{J.key=null,J.type=b0;continue V}}return $}}readHeadByte(){if(this.headByte===u0)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=u0}readArraySize(){let V=this.readHeadByte();switch(V){case 220:return this.readU16();case 221:return this.readU32();default:if(V<160)return V-144;else throw new a(`Unrecognized array type byte: ${$V(V)}`)}}pushMapState(V){if(V>this.maxMapLength)throw new a(`Max length exceeded: map length (${V}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(V)}pushArrayState(V){if(V>this.maxArrayLength)throw new a(`Max length exceeded: array length (${V}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(V)}decodeString(V,$){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String(V,$);return this.decodeBinary(V,$)}decodeUtf8String(V,$){if(V>this.maxStrLength)throw new a(`Max length exceeded: UTF-8 byte length (${V}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+$+V)throw S$;let Z=this.pos+$,J;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached(V))J=this.keyDecoder.decode(this.bytes,Z,V);else J=j$(this.bytes,Z,V);return this.pos+=$+V,J}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===b0;return!1}decodeBinary(V,$){if(V>this.maxBinLength)throw new a(`Max length exceeded: bin length (${V}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(V+$))throw S$;let Z=this.pos+$,J=this.bytes.subarray(Z,Z+V);return this.pos+=$+V,J}decodeExtension(V,$){if(V>this.maxExtLength)throw new a(`Max length exceeded: ext length (${V}) > maxExtLength (${this.maxExtLength})`);let Z=this.view.getInt8(this.pos+$),J=this.decodeBinary(V,$+1);return this.extensionCodec.decode(J,Z,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let V=this.view.getUint8(this.pos);return this.pos++,V}readI8(){let V=this.view.getInt8(this.pos);return this.pos++,V}readU16(){let V=this.view.getUint16(this.pos);return this.pos+=2,V}readI16(){let V=this.view.getInt16(this.pos);return this.pos+=2,V}readU32(){let V=this.view.getUint32(this.pos);return this.pos+=4,V}readI32(){let V=this.view.getInt32(this.pos);return this.pos+=4,V}readU64(){let V=k$(this.view,this.pos);return this.pos+=8,V}readI64(){let V=t0(this.view,this.pos);return this.pos+=8,V}readU64AsBigInt(){let V=this.view.getBigUint64(this.pos);return this.pos+=8,V}readI64AsBigInt(){let V=this.view.getBigInt64(this.pos);return this.pos+=8,V}readF32(){let V=this.view.getFloat32(this.pos);return this.pos+=4,V}readF64(){let V=this.view.getFloat64(this.pos);return this.pos+=8,V}}function jV(V,$){return new ZV($).decode(V)}class y0{listeners=new Map;addEventListener(V,$){let Z=this.listeners.get(V);if(!Z)Z=new Set,this.listeners.set(V,Z);return Z.add($),()=>{this.removeEventListener(V,$)}}removeEventListener(V,$){let Z=this.listeners.get(V);if(Z){if(Z.delete($),Z.size===0)this.listeners.delete(V)}}emit(V,$){let Z=this.listeners.get(V);if(Z){let J=Array.from(Z);for(let Q of J)Q($)}}emitAll(V){let $=Array.from(this.listeners.keys());for(let Z of $)this.emit(Z,V)}}class q0{getter;static eventName="update";emitter;constructor(V){this.getter=V;this.emitter=new y0}get=()=>this.getter();async emit(){let V=await this.getter();queueMicrotask(()=>this.emitter.emit(q0.eventName,V))}listen(V){return this.emitter.addEventListener(q0.eventName,V),()=>{this.emitter.removeEventListener(q0.eventName,V)}}}function O(V){return[V,0]}function N(V){return[void 0,V]}function WJ(V){if(V<0)console.info("N",V),console.trace();if(typeof V!=="bigint")V=BigInt(V);if(V<0n)return N(10);let $=[];while(V>0n){let Z=Number(V&0x7fn);if(V>>=7n,V>0n)$.push(Z|128);else $.push(Z)}if($.length===0)return O(new Uint8Array([0]));if($.length>8)return N(26);return O(new Uint8Array($))}function YJ(V,$=0){let Z=0n,J=0,Q=$;while(!0){if(Q>=V.length)return N(14);let W=V[Q++];if(W===void 0)return N(14);if(Z|=BigInt(W&127)<<BigInt(J),(W&128)===0){if(Q-$>8)return N(26);return O({value:Z>0x1fffffffffffffn?Z:Number(Z),bytesRead:Q-$})}if(J+=7,J>=56)return N(26)}}class m{data;pos=0;constructor(V){this.data=V}static async fromResponse(V){let $=await V.arrayBuffer(),Z=new Uint8Array($);return new m(Z)}readBigInt(){if(this.pos+8>this.data.length)return N(7);let V=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,O(V)}readDate(){let[V,$]=this.readVarInt();if($!==0)return N($);return O(new Date(V))}readVarInt(){let[V,$]=YJ(this.data,this.pos);if($!==0)return N($);this.pos+=V.bytesRead;let Z=V.value;return O(typeof Z==="bigint"?Number(Z):Z)}readVarString(){let[V,$]=this.readVarInt();if($!==0)return N($);let[Z,J]=this.readBytes(V);if(J!==0)return N(J);let Q=new TextDecoder().decode(Z);return O(Q)}readBytes(V){if(V<0)return N(10);if(this.pos+V>this.data.length)return N(23);let $=this.data.slice(this.pos,this.pos+V);return this.pos+=V,O($)}readVarBytes(){let[V,$]=this.readVarInt();if($!==0)return N($);return this.readBytes(V)}readStruct(V){return V.decode(this)}readStructs(V){let $=[];while(!this.done()){let[Z,J]=this.readStruct(V);if(J!==0)return N(J);$.push(Z)}return O($)}readBytesSeq(V){let $=[];while(!this.done()){let[Z,J]=this.readBytes(V);if(J!==0)return N(J);$.push(Z)}return O($)}done(){return this.pos>=this.data.length}consumed(){return this.pos}}class B{parts=[];writeBigInt(V){let $=new Uint8Array(8);new DataView($.buffer).setBigUint64(0,V,!1),this.parts.push($)}writeDate(V){let $=V.getTime();return this.writeVarInt($)}writeVarInt(V){let[$,Z]=WJ(V);if(Z!==0)return Z;return this.parts.push($),0}writeVarString(V){let $=new TextEncoder().encode(V),Z=this.writeVarInt($.length);if(Z!==0)return Z;return this.writeBytes($),0}prependBytes(V){this.parts.unshift(V)}writeBytes(V){this.parts.push(V)}writeVarBytes(V){let $=this.writeVarInt(V.length);if($!==0)return $;return this.writeBytes(V),0}writeStruct(V,$){return V.encode(this,$)}writeStructs(V,$){for(let Z of $){let J=this.writeStruct(V,Z);if(J!==0)return J}return 0}writeBytesSeq(V){for(let $ of V)this.writeBytes($)}result(){let V=this.parts.reduce((J,Q)=>J+Q.length,0),$=new Uint8Array(V),Z=0;for(let J of this.parts)$.set(J,Z),Z+=J.length;return $}*scan(){for(let V of this.parts)yield V}}async function LV(V,$,Z){let J=new B,Q=J.writeDate($);if(Q!==0)return N(Q);let W=J.result(),Y=await Z.signEd25519(W,V.privateKey);return O({pubKey:V.publicKey,sig:Y,timestamp:$})}async function U0(V,$,Z){let J=Z.now().getTime(),Q=V.timestamp.getTime();if(Math.abs(J-Q)>C$)return 4;let Y=new B;Y.writeDate(V.timestamp);let X=Y.result();if(!await $.checkSigEd25519(V.sig,X,V.pubKey))return 3;return 0}var J0={encode(V,$){let Z=V.writeVarBytes($.id);if(Z!==0)return Z;let J=V.writeDate($.ts);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return N(Z);let[J,Q]=V.readDate();if(Q!==0)return N(Q);return O({id:$,ts:J})}};function JV(V){let $=new B,Z=$.writeStruct(J0,V);if(Z!==0)return N(Z);let J=$.result();return O(J)}var Q0={encode(V,$){let Z=V.writeVarBytes($.eid);if(Z!==0)return Z;let J=V.writeVarInt($.off);if(J!==0)return J;let Q=V.writeVarInt($.ctr);if(Q!==0)return Q;let W=V.writeVarInt($.len);if(W!==0)return W;if($.hsh)V.writeBytes($.hsh);return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return N(Z);let J=new m($),[,Q]=J0.decode(J);if(Q!==0)return N(Q);let[W,Y]=V.readVarInt();if(Y!==0)return N(Y);let[X,G]=V.readVarInt();if(G!==0)return N(G);let[K,R]=V.readVarInt();if(R!==0)return N(R);let I;if(K>0){let[w,M]=V.readBytes(a0);if(M!==0)return N(M);I=w}return O({eid:$,off:W,ctr:X,len:K,hsh:I})}};function W0(V){return Array.from(V).map((Z)=>Z.toString(16).padStart(2,"0")).join("")}function QV(V){if(V.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(V.length/2);for(let Z=0;Z<V.length;Z+=2)$[Z/2]=Number.parseInt(V.substr(Z,2),16);return $}function O0(V,$){if(V===$)return!0;if(V.byteLength!==$.byteLength)return!1;return V.every((Z,J)=>Z===$[J])}var i;if(typeof Uint8Array.prototype.toBase64==="function")i=(V)=>V.toBase64();else i=(V)=>btoa(String.fromCharCode(...V));var R0;if(typeof Uint8Array.fromBase64==="function")R0=(V)=>Uint8Array.fromBase64(V);else R0=(V)=>Uint8Array.from(atob(V),($)=>$.charCodeAt(0));function n0(V,$){let Z=new Uint8Array(V.length+$.length);return Z.set(V,0),Z.set($,V.length),Z}function f$(V,$,Z){return Z.checkSigEd25519(V.sig,V.headCph,$)}async function kV(V,$,Z){let J=n0($.privateKey,V);return(await Z.blake3(J)).slice(0,P0)}async function m$(V,$,Z,J){let Q;if(V.bod&&V.len>0)Q=await Z.blake3(V.bod);let W=new B,Y=Q0.encode(W,{...V,hsh:Q});if(Y!==0)return N(Y);let X=W.result(),G=await kV(X,$,Z),K=await J.deriveFromKDM(G),R=await Z.encryptXSalsa20Poly1305Combined(X,K),I=V.bod?await Z.encryptXSalsa20Poly1305Combined(V.bod,K):new Uint8Array(0),w=await Z.signEd25519(R,$.privateKey);return O({sig:w,kdm:G,headCph:R,bodyCph:I})}async function EV(V,$,Z,J,Q){let W=new m(V),[Y,X]=Q0.decode(W);if(X!==0)return N(14);let G;try{G=$&&$.length>0?await J.decryptXSalsa20Poly1305Combined($,Z):void 0}catch{return N(20)}let K=Y.hsh&&G===void 0,R=Y.hsh===void 0&&G!==void 0;if(K||R)return N(19);if(Y.hsh&&G){let w=await J.blake3(G);if(!O0(w,Y.hsh))return N(19)}let I=Q??await J.blake3(V);return O({msgHead:Y,bod:G,headHash:I})}class SV{now(){return new Date}}function g$(V,$,Z,J){let Q=$.getTime()-V.getTime(),W=Z.getTime()-J.getTime();return(Q+W)/2}var p0={encode(V,$){if(V.writeVarInt($.quota),$.quota>0){if($.usage===void 0)return 9;V.writeVarInt($.usage)}return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return N(Z);let J;if($>0){let[Q,W]=V.readVarInt();if(W!==0)return N(W);J=Q}return O({quota:$,usage:J})}};var xV={encode(V,$){V.writeBytes(new Uint8Array([$.status]));let Z=V.writeDate($.timeRcvd);if(Z!==0)return Z;let J=V.writeDate($.timeSent);if(J!==0)return J;let Q=V.writeVarInt($.subscription.term);if(Q!==0)return Q;let W=V.writeVarInt($.subscription.elapsed);if(W!==0)return W;let Y=V.writeStruct(p0,$.subscription.stat);if(Y!==0)return Y;let X=V.writeStruct(p0,$.subscription.dyn);if(X!==0)return X;return 0},decode(V){let[$,Z]=V.readBytes(1);if(Z!==0)return N(Z);let J=$[0],[Q,W]=V.readDate();if(W!==0)return N(W);let[Y,X]=V.readDate();if(X!==0)return N(X);let[G,K]=V.readVarInt();if(K!==0)return N(K);let[R,I]=V.readVarInt();if(I!==0)return N(I);let[w,M]=V.readStruct(p0);if(M!==0)return N(M);let[P,z]=V.readStruct(p0);if(z!==0)return N(z);return O({status:J,timeRcvd:Q,timeSent:Y,subscription:{term:G,elapsed:R,stat:w,dyn:P}})}};async function BV(V,$,Z){let{crypto:J,enclave:Q}=V,W=await Q.derive($,Z);return await J.deriveEd25519KeyPair(W)}var fV={encode(V,$){let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarInt($.seq);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readVarBytes();if(Z!==0)return N(Z);let[J,Q]=V.readVarInt();if(Q!==0)return N(Q);return O({headCph:$,seq:J})}};var V0={encode(V,$){V.writeBytes($.pubKey),V.writeBytes($.sig);let Z=V.writeDate($.timestamp);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readBytes(H$);if(Z!==0)return N(Z);let[J,Q]=V.readBytes(F0);if(Q!==0)return N(Q);let[W,Y]=V.readDate();if(Y!==0)return N(Y);return O({pubKey:$,sig:J,timestamp:W})}};var v$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(V0,Z);if(W!==0)return W;for(let Y of J)Q.writeVarInt(Y);return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(V0);if(X!==0)return X;let G=await U0(Y,Q,J);if(G!==0)return G;let{pubKey:K}=Y,[R,I]=await W.hasUser(K);if(I!==0)return I;if(!R)return 5;let[w,M]=$.readVarInt();if(M!==0)return M;if(!$.done())return 8;let[P,z]=await W.listHeads(K,w);if(z!==0)return z;return Z.writeStructs(fV,P)},decodeResp(V){return V.readStructs(fV)}};var mV={encode(V,$){V.writeVarInt($.seq);let Z=V.writeVarBytes($.bodyCph);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return N(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return N(Q);return O({seq:$,bodyCph:J})}};var i$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(V0,Z);if(W!==0)return W;for(let Y of J){let X=Q.writeVarInt(Y);if(X!==0)return X}return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(V0);if(X!==0)return X;let G=await U0(Y,Q,J);if(G!==0)return G;let{pubKey:K}=Y,[R,I]=await W.hasUser(K);if(I!==0)return I;if(!R)return 5;let w=[];while(!$.done()){let[z,q]=$.readVarInt();if(q!==0)return q;w.push(z)}console.info(`PULL: ${w.length} bags`);let[M,P]=await W.getBodies(K,w);if(P!==0)return P;if(!M)return 17;for(let{seq:z,bodyCph:q}of M){let U={seq:z,bodyCph:q},C=Z.writeStruct(mV,U);if(C!==0)return C}return 0},decodeResp(V){return V.readStructs(mV)}};var gV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarBytes($.bodyCph);if(J!==0)return J;return 0},decode(V){let[$,Z]=V.readBytes(F0);if(Z!==0)return N(Z);let[J,Q]=V.readBytes(P0);if(Q!==0)return N(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return N(Y);let[X,G]=V.readVarBytes();if(G!==0)return N(G);return O({sig:$,kdm:J,headCph:W,bodyCph:X})}};var WV={encode(V,$){let Z=V.writeVarInt($.seq);if(Z!==0)return Z;let J=V.writeVarBytes($.headCph);if(J!==0)return J;let Q=$.bodyCph?$.bodyCph.length:0,W=V.writeVarInt(Q);if(W!==0)return W;if(Q>0){if(!$.bodyCph)return 10;V.writeBytes($.bodyCph)}return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return N(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return N(Q);let[W,Y]=V.readVarInt();if(Y!==0)return N(Y);let X;if(W>0){let[G,K]=V.readBytes(W);if(K!==0)return N(K);X=G}return O({seq:$,headCph:J,bodyCph:X})}};var YV={encode(V,$){V.writeBytes($.sig),V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;return 0},decode(V){let[$,Z]=V.readBytes(F0);if(Z!==0)return N(Z);let[J,Q]=V.readBytes(P0);if(Q!==0)return N(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return N(Y);return O({sig:$,kdm:J,headCph:W})}};var XV={encode(V,$){if(V.writeVarInt($.idx),V.writeBytes(new Uint8Array([$.status])),$.status===0)V.writeVarInt($.seq);return 0},decode(V){let[$,Z]=V.readVarInt();if(Z!==0)return N(Z);let[J,Q]=V.readBytes(1);if(Q!==0)return N(Q);let W=J[0];if(W!==0)return O({idx:$,status:W});let[Y,X]=V.readVarInt();if(X!==0)return N(X);return O({idx:$,status:W,seq:Y})}};var u$={async encodeReq(V,$,Z,J,Q){let W=Q.writeStruct(V0,Z);if(W!==0)return W;let Y=Q.writeStructs(gV,J);if(Y!==0)return Y;return 0},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W,notifier:Y}=V,[X,G]=$.readStruct(V0);if(G!==0)return G;let K=await U0(X,Q,J);if(K!==0)return K;let{pubKey:R}=X,[I,w]=await W.hasUser(R);if(w!==0)return w;if(!I)return 5;let[M,P]=$.readStructs(gV);if(P!==0)return P;console.info(`PUSH: ${M.length} bags`);let z=[],q=[];for(let F=0;F<M.length;F++){let A=M[F];if(!await f$(A,R,Q)){let S={idx:F,status:3},k=Z.writeStruct(XV,S);if(k!==0)return k;continue}z.push(F),q.push(A)}let[U,C]=await W.setBags(R,q);if(C!==0)return C;if(!U||U.length!==q.length)return 17;let D=[];for(let F=0;F<q.length;F++){let A=q[F],L=z[F],S=U[F],k=new B,E=k.writeStruct(YV,A);if(E!==0)return E;let x=k.result(),H={seq:S,headCph:x};if(M.length===1&&A.bodyCph.length<=T$)H.bodyCph=A.bodyCph;D.push(H);let f={idx:L,status:0,seq:S},v=Z.writeStruct(XV,f);if(v!==0)return v}if(D.length>0){let F=new B,A=F.writeStructs(WV,D);if(A!==0)return A;let L=F.result();await Promise.resolve(Y.push(R,L))}return 0},decodeResp(V){return V.readStructs(XV)}};var b$={async encodeReq(V,$,Z,J,Q){return Q.writeStruct(V0,Z)},async handleReq(V,$,Z){let{clock:J,crypto:Q,storage:W}=V,[Y,X]=$.readStruct(V0);if(X!==0)return X;let G=await U0(Y,Q,J);if(G!==0)return G;let{pubKey:K}=Y;if(!$.done())return 8;let[R,I]=await W.addUser(K);if(I!==0)return I;return 0},decodeResp(V){return O(void 0)}};class vV{url;websocket;constructor(V){this.url=V}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(V,$,Z=()=>{},J=()=>{}){let{url:Q}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let W=new B;W.writeStruct(V0,V);let Y=W.result(),X=W0(Y);return Q.searchParams.set("t",X),this.websocket=new WebSocket(Q),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),J()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,Z()},this.websocket.onmessage=(G)=>{let K=new Uint8Array(G.data);$(K)},this.websocket.onerror=(G)=>{console.log(`ERROR: ${JSON.stringify(G)}`),this.websocket=void 0,Z()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}var r={user:{path:"/user",endpoint:b$,name:0},push:{path:"/push",endpoint:u$,name:2},peek:{path:"/peek",endpoint:v$,name:1},pull:{path:"/pull",endpoint:i$,name:3}},XJ={0:r.user,2:r.push,1:r.peek,3:r.pull},hY={[r.user.path]:r.user,[r.push.path]:r.push,[r.peek.path]:r.peek,[r.pull.path]:r.pull};class y${url;listener;constructor(V){this.url=V;this.listener=new vV(V)}async call(V,$){let{path:Z}=XJ[V],J=new URL(Z,this.url);try{return await GJ(J,$)}catch{return N(25)}}}var n$=(V)=>{return new y$(V.handle)};async function GJ(V,$){let Z=await fetch(V,{method:"POST",body:$.result().slice()});if(!Z.ok)return N(24);let J=await m.fromResponse(Z);return O(J)}class GV{enclave;crypto;host;clock;transport;updateHostMeta;constructor(V,$,Z,J,Q,W){this.enclave=V;this.crypto=$;this.host=Z;this.clock=J;this.transport=Q;this.updateHostMeta=W}async call(V,$){let{clock:Z,crypto:J,transport:Q}=this,{endpoint:W,name:Y}=V,X=await this.keys(),G=Z.now(),[K,R]=await LV(X,G,J);if(R!==0)return N(R);let I=new B,w=await W.encodeReq(this,X,K,$,I);if(w!==0)return N(w);let M=Z.now(),[P,z]=await Q.call(Y,I),q=Z.now();if(z!==0)return N(z);let[U,C]=P.readStruct(xV);if(C!==0)return N(C);if(U.status!==0)return N(U.status);let F={clockOffset:g$(M,U.timeRcvd,U.timeSent,q),subscription:U.subscription},A=await this.updateHostMeta(F);if(A!==0)return N(A);return W.decodeResp(P)}keys=()=>{let{host:V}=this;return BV(this,V.label,V.idx)};seal=async(V)=>{let{crypto:$,enclave:Z}=this,J=await this.keys();return m$(V,J,$,Z)};register=()=>this.call(r.user,[]);peek=(V)=>this.call(r.peek,[V]);push=(V)=>this.call(r.push,V);pull=(V)=>this.call(r.pull,V);listen=async(V,$,Z)=>{let{clock:J,crypto:Q,host:W,transport:Y}=this,{listener:X}=Y,G=await BV(this,W.label,W.idx),K=J.now(),[R,I]=await LV(G,K,Q);if(I!==0)return I;return await X.connect(R,V,$,Z)};isConnected(){let V=this.transport?.listener;if(V&&typeof V.connected==="function")return V.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}var iV={encode(V,$){let Z=V.writeVarString($.lbl);if(Z!==0)return Z;let J=V.writeVarInt($.idx);if(J!==0)return J;let Q=V.writeVarInt($.num);if(Q!==0)return Q;return V.writeBytes($.hsh),V.writeBytes($.sig),0},decode(V){let[$,Z]=V.readVarString();if(Z!==0)return N(Z);let[J,Q]=V.readVarInt();if(Q!==0)return N(Q);let[W,Y]=V.readVarInt();if(Y!==0)return N(Y);let[X,G]=V.readBytes(a0);if(G!==0)return N(G);let[K,R]=V.readBytes(F0);if(R!==0)return N(R);return O({lbl:$,idx:J,num:W,hsh:X,sig:K})}};var uV={encode(V,$){let Z=V.writeStruct(iV,$.head);if(Z!==0)return Z;let J=V.writeVarBytes($.indexEnc);if(J!==0)return J;let Q=V.writeVarBytes($.bodyEnc);if(Q!==0)return Q;return 0},decode(V){let[$,Z]=V.readStruct(iV);if(Z!==0)return N(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return N(Q);let[W,Y]=V.readVarBytes();if(Y!==0)return N(Y);return O({head:$,indexEnc:J,bodyEnc:W})}};var bV={encode(V,$){V.writeBytes($.kdm);let Z=V.writeVarBytes($.headCph);if(Z!==0)return Z;let J=V.writeVarInt($.lenBody);if(J!==0)return J;if($.lenBody>0&&$.offBody!==void 0){let Q=V.writeVarInt($.offBody);if(Q!==0)return Q}return 0},decode(V){let[$,Z]=V.readBytes(P0);if(Z!==0)return N(Z);let[J,Q]=V.readVarBytes();if(Q!==0)return N(Q);let[W,Y]=V.readVarInt();if(Y!==0)return N(Y);let X;if(W>0){let[G,K]=V.readVarInt();if(K!==0)return N(K);X=G}return O({kdm:$,headCph:J,lenBody:W,offBody:X})}};async function p$(V,$,Z,J,Q){let W=await Q.derive(V,$),Y=await J.deriveEd25519KeyPair(W),X=new B,G=new B,K=0,R=0;for(let C of Z){let D=new B,F=D.writeStruct(Q0,C.head);if(F!==0)return N(F);let A=D.result(),L=await kV(A,Y,J),S=await Q.deriveFromKDM(L),k=await J.encryptXSalsa20Poly1305Combined(A,S),E=C.body?await J.encryptXSalsa20Poly1305Combined(C.body,S):new Uint8Array(0),x=C.head.len>0&&C.head.hsh!==void 0?E.length:0,H={kdm:L,headCph:k,lenBody:x,offBody:x>0?R:void 0},f=X.writeStruct(bV,H);if(f!==0)return N(f);if(C.body)G.writeBytes(E),R+=E.length;K++}let I=G.result(),w=X.result(),M=await J.blake3(w),P=await J.signEd25519(M,Y.privateKey),z={lbl:V,idx:$,num:K,hsh:M,sig:P},q=new B;q.writeStruct(uV,{head:z,indexEnc:w,bodyEnc:I});let U=q.result();return O(U)}async function l$(V,$,Z){let[J,Q]=uV.decode(new m(V));if(Q!==0)return N(Q);let{head:W,indexEnc:Y,bodyEnc:X}=J,G=await Z.derive(W.lbl,W.idx),K=await $.deriveEd25519KeyPair(G);if(!await $.checkSigEd25519(W.sig,W.hsh,K.publicKey))return N(3);let I=await $.blake3(Y);if(!O0(I,W.hsh))return N(19);let w=new m(Y),M=[];for(let z=0;z<W.num;z++){let[q,U]=w.readStruct(bV);if(U!==0)return N(U);M.push(q)}if(M.length!==W.num)return N(14);let P=[];for(let z of M){let q=await Z.deriveFromKDM(z.kdm),U=await $.decryptXSalsa20Poly1305Combined(z.headCph,q),[C,D]=Q0.decode(new m(U));if(D!==0)return N(D);let F;if(z.lenBody>0&&z.offBody!==void 0){if(C.hsh===void 0)return N(14);let A=X.slice(z.offBody,z.offBody+z.lenBody);F=await $.decryptXSalsa20Poly1305Combined(A,q);let L=await $.blake3(F);if(!O0(L,C.hsh))return N(19)}P.push({head:C,body:F})}return O(P)}async function h$({now:V,bod:$,crypto:Z}){let J=await Z.genRandomBytes(8),Q=new B,W=Q.writeStruct(J0,{id:J,ts:V});if(W!==0)return N(W);let Y=Q.result();return KV({now:V,eid:Y,ctr:0,bod:$,crypto:Z})}async function KV({now:V,eid:$,ctr:Z,bod:J,crypto:Q}){let W=new m($),[Y,X]=J0.decode(W);if(X!==0)return N(X);let G=V.getTime()-Y.ts.getTime(),K,R=J?.length??0;if(J&&R>0)K=await Q.blake3(J);return O({eid:$,off:G,ctr:Z,len:R,hsh:K})}class RV{inflight=null;again=!1;run(V){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain(V),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain(V){try{this.again=!1;let $=await V();while(this.again)this.again=!1,$=await V();return $}finally{this.inflight=null}}}var r$=100;class yV{timer=null;delayMs;work;tail=new RV;constructor(V,$){this.delayMs=V<0?0:V,this.work=$}schedule(){if(this.delayMs<=0){this.fire();return}if(this.timer!==null)clearTimeout(this.timer);this.timer=setTimeout(()=>{this.timer=null,this.fire()},this.delayMs)}async flush(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null,this.fire();await this.tail.flush()}cancel(){if(this.timer!==null)clearTimeout(this.timer),this.timer=null}fire(){return this.tail.run(this.work)}}function c$(V){let $=new m(V.eid),[Z,J]=J0.decode($);if(J!==0)return;return Z.ts.getTime()+V.off}function KJ(V,$){let Z=c$(V),J=c$($);if(Z===void 0&&J===void 0)return 0;if(Z===void 0)return 1;if(J===void 0)return-1;if(J!==Z)return J-Z;return $.ctr-V.ctr}function l0(V,$){return V.slice().sort((Z,J)=>KJ($(Z),$(J)))}var nV={phase:"idle"},NV=50;function d$(V,$,Z){if(V<=0||$<=0)return!1;if(V===1||V===$)return!0;return V%Z===0}function o$(V,$){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(V,$);return}let Z=URL.createObjectURL(V),J=document.createElement("a");J.href=Z,J.download=$,document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL(Z)}function pV(V,$,Z){let J=[],Q=[],W=0;for(let Y of V){let X=$(Y);if(Q.length>0&&W+X>Z)J.push(Q),Q=[],W=0;if(Q.push(Y),W+=X,W>=Z)J.push(Q),Q=[],W=0}if(Q.length>0)J.push(Q);return J}async function a$(V,$,Z){let J=V.length;if(J<1)return[];let Q=Array(J),W=0,Y=Math.min(Math.max(1,$),J),X=async()=>{while(!0){let K=W;if(W+=1,K>=J)return;Q[K]=await Z(V[K],K)}},G=[];for(let K=0;K<Y;K++)G.push(X());return await Promise.all(G),Q}async function lV(V,$,Z,J){let Q=new m(V.headCph),[W,Y]=Q.readStruct(YV);if(Y!==0)return N(Y);let{sig:X,kdm:G,headCph:K}=W;if(!await J.checkSigEd25519(X,K,$.publicKey))return N(3);let I=await Z.deriveFromKDM(G),w;try{w=await J.decryptXSalsa20Poly1305Combined(K,I)}catch{return N(20)}return O({kdm:G,headEnc:w})}var hV=1048576,rV=1048576,RJ=64;function NJ(V){return V.sig.length+V.kdm.length+V.headCph.length+V.bodyCph.length}async function IJ(V,$,Z,J,Q){if(J.length<1)return 0;let[W,Y]=await V.push(J);if(Y!==0)return Y;if(!W)return 27;for(let G of W){if(G.status!==0){console.error("push err",G);continue}let K=Q[G.idx];if(!K){console.error("no hash",G);continue}await $.uploads.deq(Z,[K])}let X=await $.hosts.get(Z);if(X){let G=X.lastSeq,K=G,R=[];for(let I of W)if(I.status===0)R.push(I.seq);R.sort((I,w)=>I-w);for(let I of R)if(I===G+1)G=I;if(G>K)await $.hosts.touch(Z,G)}return 0}async function s$(V,$){if($.length<1)return O([]);let Z=new Map,J=[];for(let X of $)Z.set(X.seq,X),J.push(X.seq);let[Q,W]=await V.pull(J);if(W!==0)return N(W);if(!Q)return N(27);let Y=[];for(let{seq:X,bodyCph:G}of Q){let K=Z.get(X);if(!K)continue;Y.push({dl:K,bodyCph:G})}return O(Y)}async function wJ(V,$,Z,J){if(J.length<1)return O({parts:[],hashes:[]});let Q=[],W=[],Y=[],X=new Map;for(let{dl:K,bodyCph:R}of J){let{head:I,kdm:w,seq:M,host:P}=K,[z,q]=await t$(K,Z);if(q!==0||!z){let E=X.get(P)??[];E.push(M),X.set(P,E);continue}let{headEnc:U,headEncHash:C}=z,D=await $.deriveFromKDM(w),[F,A]=await EV(U,R,D,Z,C);if(A!==0||!F){let E=X.get(P)??[];E.push(M),X.set(P,E);continue}let L={head:I,body:F.bod},S=F.headHash;Y.push({key:S,data:JZ(L)}),Q.push(L),W.push(S);let k=X.get(P)??[];k.push(M),X.set(P,k)}let G=await V.messages.add(Y);for(let[K,R]of X)await V.downloads.deq(K,R);for(let K=0;K<G.length;K++){let R=G[K];if(R!==0&&R!==15)console.error("ERR storing",j[R],"for message",K)}return O({parts:Q,hashes:W})}async function t$(V,$){let Z=V.headEnc;if(!Z){let Q=new B,W=Q.writeStruct(Q0,V.head);if(W!==0)return N(W);Z=Q.result()}if(V.headEncHash)return O({headEnc:Z,headEncHash:V.headEncHash});let J=await $.blake3(Z);return O({headEnc:Z,headEncHash:J})}async function e$(V,$,Z){let J=new Set;for(let Y of $)J.add(i(Y));if(J.size<1)return;let Q=Array.from(await V.downloads.list());if(Q.length<1)return;let W=new Map;for(let Y of Q){let X;if(Y.headEncHash)X=i(Y.headEncHash);else{let[K,R]=await t$(Y,Z);if(R!==0||!K)continue;X=i(K.headEncHash)}if(!J.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 V.downloads.deq(Y,X)}async function VZ({conn:V,store:$,enclave:Z,host:J,crypto:Q,onProgress:W,peekProgressEvery:Y,peekConcurrency:X}){let G=await V.keys(),K=[],[R,I]=await V.peek(J.lastSeq);if(I!==0)return I;let w=R.length,M=Y??NV,P=X??RJ;if(W&&w>0)W({phase:"peek",host:J.label,done:0,total:w});let z=0,q=await a$(R,P,async(U)=>{let[C,D]=await lV(U,G,Z,Q),F;if(D!==0||!C)F={ok:!1,seq:U.seq,stat:D};else{let A=await Q.blake3(C.headEnc);F={ok:!0,seq:U.seq,kdm:C.kdm,headEnc:C.headEnc,headEncHash:A}}if(z+=1,W&&d$(z,w,M))W({phase:"peek",host:J.label,done:z,total:w});return F});for(let U of q){if(!U.ok){console.error("peek: decrypting item head",U.stat);continue}if(await $.messages.has(U.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await $.uploads.deq(J.label,[U.headEncHash]),await $.downloads.deq(J.label,[U.seq]);continue}let D=new m(U.headEnc),[F,A]=D.readStruct(Q0);if(A!==0){console.error("peek: reading item head",A);continue}K.push({kdm:U.kdm,head:F,seq:U.seq,host:J.label,headEnc:U.headEnc,headEncHash:U.headEncHash})}if(await $.downloads.enq(K),R.length>0){let U=Math.max(...R.map((C)=>C.seq));await $.hosts.touch(J.label,U)}if(W)W({phase:"peek",host:J.label,done:w,total:w});return 0}var zJ=1048576;async function $Z({conn:V,store:$,host:Z,maxPushBytes:J,onProgress:Q}){let W=J??hV,Y=zJ,X=await $.uploads.list(Z.label),G=X.length,K=0;if(Q&&G>0)Q({phase:"push",host:Z.label,done:0,total:G});let R=pV(X,(z)=>Math.max(1,z.bodyLen),Y),I=[],w=[],M=0,P=async()=>{if(I.length<1)return 0;let z=I.length,q=await IJ(V,$,Z.label,I,w);if(I=[],w=[],M=0,q===0){if(K+=z,Q)Q({phase:"push",host:Z.label,done:K,total:G})}return q};for(let z of R){let q=await $.messages.getMany(z.map((U)=>U.hash));for(let U=0;U<z.length;U++){let C=z[U],D=q[U];if(!D){K+=1;continue}let F={...D.head,bod:D.body},[A,L]=await V.seal(F);if(L!==0)return L;if(!A)return 12;let S=NJ(A);if(I.length>0&&M+S>W){let k=await P();if(k!==0)return k}if(I.push(A),w.push(C.hash),M+=S,M>=W){let k=await P();if(k!==0)return k}}}return P()}async function ZZ({conn:V,store:$,enclave:Z,host:J,crypto:Q,maxPullBytes:W,onProgress:Y},X){let G=W??rV,K=await $.downloads.list(),R=Array.from(K).filter((q)=>q.host===J.label);if(R.length<1)return 15;let I=l0(R,(q)=>q.head),w=pV(I,(q)=>q.head.len,G),M=I.length,P=0;if(Y)Y({phase:"pull",host:J.label,done:0,total:M});let z=s$(V,w[0]);for(let q=0;q<w.length;q++){let[U,C]=await z;if(C!==0||!U)return C;if(P+=w[q].length,Y)Y({phase:"pull",host:J.label,done:P,total:M});let D=w[q+1];if(D)z=s$(V,D);if(Y)Y({phase:"open",host:J.label,done:P,total:M});let F=l0(U,(L)=>L.dl.head),[,A]=await wJ($,Z,Q,F);if(A!==0)return A;if(X){if(Y)Y({phase:"exec",host:J.label,done:P,total:M});await X()}}return 0}function JZ({head:V,body:$}){return{eid:V.eid,...V.off!==0?{off:V.off}:{},...V.ctr!==0?{ctr:V.ctr}:{},body:$,apld:!1}}async function QZ(V,{conn:$,store:Z,enclave:J,host:Q,crypto:W,onProgress:Y},X){let G=Q.label,K=await $.keys(),R=new m(V),[I,w]=R.readStructs(WV);if(w!==0){console.error("Failed decoding notif",j[w]);return}let M=!1,z=(await Z.hosts.get(G))?.lastSeq,q=[],U=!1;for(let F of I){let[A,L]=await lV({seq:F.seq,headCph:F.headCph},K,J,W);if(L!==0){console.error("Failed decrypting notif",j[L]);continue}let S=await W.blake3(A.headEnc);if(await Z.messages.has(S))continue;let k=new m(A.headEnc),[E,x]=k.readStruct(Q0);if(x!==0){console.error("Failed to parse head",j[x]);continue}if(!F.bodyCph&&E.len>0)U=!0,await Z.downloads.enq([{seq:F.seq,host:G,kdm:A.kdm,head:E,headEnc:A.headEnc,headEncHash:S}]);else q.push({...A,head:E,bodyCph:F.bodyCph,headEncHash:S});if(z===void 0||F.seq!==z+1)console.log("out of seq",F.seq,z),M=!0;else z=F.seq}if(z!==void 0)await Z.hosts.touch(Q.label,z);let C=[];for(let F of q){let A=await J.deriveFromKDM(F.kdm),[L,S]=await EV(F.headEnc,F.bodyCph,A,W);if(S!==0){console.error("Failed to open body",j[S]);continue}C.push({key:F.headEncHash,data:JZ({head:F.head,body:L.bod})})}let D=await Z.messages.add(C);for(let F=0;F<D.length;F++){let A=D[F];if(A!==0&&A!==15)console.error("ERR storing",j[A],"for message",F)}if(Y&&C.length>0)Y({phase:"open",host:Q.label,done:C.length,total:C.length});if(M||U||C.length>0)X()}class cV{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;applyChain=Promise.resolve();syncRuns=new RV;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=NV;lastProgress=nV;scheduledSync;constructor(V,$,Z,J,Q,W=!0,Y=hV,X=rV,G){this.clock=V;this.state=$;this.store=Z;this.transport=J;this.crypto=Q;this.forceSkewHandlingByDefault=W;this.onScheduleSync=G;this.maxPushBytes=Y,this.maxPullBytes=X,this.clientState=new q0(()=>this.getClientState()),this.xferState=new q0(()=>this.getXferState()),this.scheduledSync=new yV(r$,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(K){console.error("Debounced sync failed:",K)}})}emitProgress=(V)=>{this.lastProgress=V,this.xferState.emit()};async setSeed(V){await this.store.seed.save(V),this.clientState.emit()}async getClientState(){let{store:V,connections:$}=this,Z=await V.seed.load(),J=await V.hosts.list(),Q=!1;for(let W of $.values())if(W.isConnected()){Q=!0;break}return{hasSeed:Z!==void 0,hasHost:Array.from(J).length>0,connected:Q}}async getXferState(){let{uploads:V,downloads:$}=this.store,Z=await V.count();return{numDownloads:await $.count(),numUploads:Z,progress:this.lastProgress}}apply=async(V,$={enqueueUpload:!0,triggerUpload:!0})=>{let Z=[],J=[];for(let{head:W,body:Y}of V){let X=new B;X.writeStruct(Q0,W);let G=X.result(),K=await this.crypto.blake3(G),R={eid:W.eid,...W.off!==0?{off:W.off}:{},...W.ctr!==0?{ctr:W.ctr}:{},body:Y,apld:!1};Z.push(K),J.push({key:K,data:R})}await this.store.messages.add(J),await e$(this.store,Z,this.crypto);let Q=await this.applyHashes(Z);if($.enqueueUpload){let W=[];for(let Y=0;Y<Z.length;Y++){let X=Q[Y];if(X===0||X===15)W.push({hash:Z[Y],bodyLen:V[Y].body?.length??0})}if(W.length>0){let Y=await this.store.hosts.list();for(let X of Y)await this.store.uploads.enq(X.label,W);this.xferState.emit()}}if($.triggerUpload)this.scheduleSync();return Q};enqueueApplyJob(V){let $=this.applyChain.then(V,V);return this.applyChain=$.then(()=>{return},()=>{return}),$}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let V=await this.store.messages.listUnapplied();if(V.length<1)return[];let $=l0(V,(Z)=>Z.head);return this.applyStored($)}applyHashes=(V)=>{return this.enqueueApplyJob(async()=>{let $=[];for(let Q of V){let W=await this.store.messages.get(Q);if(W)$.push(W)}let Z=await this.applyStored($),J=new Map;for(let Q=0;Q<$.length;Q++)J.set(i($[Q].hash),Z[Q]??12);return V.map((Q)=>J.get(i(Q))??13)})};async applyStored(V){if(V.length<1)return[];let $=V.map((Q)=>({...Q.head,bod:Q.body})),Z=await this.state.apply($),J=[];for(let Q=0;Q<V.length;Q++){let W=Z[Q];if(W===0||W===15)J.push(V[Q].hash)}if(J.length>0)await this.store.messages.markApplied(J);return Z}async insertRaw(V){let{clock:$,crypto:Z}=this,[J,Q]=await h$({now:$.now(),bod:V,crypto:Z});if(Q!==0)return N(Q);return await this.apply([{head:J,body:V}]),O(J)}async upsertRaw(V,$,Z=!1){let{clock:J,crypto:Q,store:W}=this,Y=J.now(),X=await W.messages.last(V);if(X){let M=new m(V),[P,z]=M.readStruct(J0);if(z!==0)return N(z);if(P.ts.getTime()+X.head.off>Y.getTime()){if(Z===!1)return N(4);let U=X.head.off+1,C=X.head.ctr+1,D={eid:V,off:U,ctr:C,len:0},A=(await this.apply([{head:D,body:void 0}]))[0];if(A!==0)return N(A);if($===void 0)return O(D);let[L,S]=JV({id:P.id,ts:Y});if(S!==0)return N(S);let k={now:Y,eid:L,ctr:0,bod:$,crypto:Q},[E,x]=await KV(k);if(x!==0)return N(x);let f=(await this.apply([{head:E,body:$}]))[0];if(f!==0)return N(f);return O(E)}}let G=(X?.head.ctr??-1)+1,[K,R]=await KV({now:Y,eid:V,ctr:G,bod:$,crypto:Q});if(R!==0)return N(R);let w=(await this.apply([{head:K,body:$}]))[0];if(w!==0)return N(w);return O(K)}async insert(V){let{body:$,type:Z,gid:J,pid:Q}=V,Y=VV({body:$,type:Z,gid:J,pid:Q});return this.insertRaw(Y)}async upsert(V,$=this.forceSkewHandlingByDefault){let{eid:Z,body:J,type:Q,gid:W,pid:Y}=V;if(Z===void 0)return this.insert(V);let G=VV({body:J,type:Q,gid:W,pid:Y});return this.upsertRaw(Z,G,$)}async delete(V){return this.upsertRaw(V,void 0,!0)}async genEID(V){let{clock:$,crypto:Z}=this,J=$.now();if(V!==void 0)return JV({id:V,ts:J});let Q=await Z.genRandomBytes(8);return JV({id:Q,ts:J})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:V,crypto:$,store:Z}=this,J=await Z.seed.load();if(!J)return 22;await this.drainApplyQueue();for(let[Q,W]of V){let Y=await Z.hosts.get(Q);if(!Y)continue;let X={conn:W,store:Z,enclave:J,host:Y,crypto:$,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},G=await VZ(X);if(G!==0)return console.error(`Failed to peek: ${G}`),G;this.xferState.emit();let K=await $Z(X);if(K!==0)return console.error(`Failed to push: ${K}`),K;this.xferState.emit();let R=await ZZ(X,async()=>{await this.drainApplyQueue()});if(R!==0&&R!==15)return console.error(`Failed to pull: ${R}`),R;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async wipe(){this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush(),await this.store.wipe(),await this.state.clear(),this.lastProgress=nV,this.clientState.emit(),this.xferState.emit()}import=async(V,$)=>{let{crypto:Z,store:J}=this,Q=$?.onProgress,W=await J.seed.load();if(!W)return 22;console.time("import: decoding file...");let Y=await V.bytes(),[X,G]=await l$(Y,Z,W);if(G!==0)return G;console.timeEnd("import: decoding file...");let K=0;while(K<X.length){let R=0,I=0,w=K;for(let z=K;z<X.length&&I<100&&R<102400;z++)R+=X[z].head.len,I++,w=z+1;let M=X.slice(K,w);console.time(`import: applying [${K}, ${w}]`);let P=await this.apply(M,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${K}, ${w}]`);for(let z=0;z<M.length;z++){let q=P[z];if(q!==0&&q!==15)console.warn(`failed to import msg ${K+z}: ${j[q]}`)}if(Q)queueMicrotask(()=>Q(w,X.length,0));this.emitProgress({phase:"import",done:w,total:X.length}),K=w}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:V,store:$}=this,Z=await $.seed.load();if(!Z)return N(22);let J=await $.messages.list();return p$("export",0,J,V,Z)}async export(V){let[$,Z]=await this.exportBytes();if(Z!==0)return Z;if(!$)return 12;let J=new Blob([$.slice()]);return o$(J,V),0}async link(V,$=!0){if(await this.store.hosts.add(V),this.clientState.emit(),$){let Z=await this.store.hosts.get(V.label);if(Z)await this.connectToHost(Z)}}async unlink(V){await this.store.hosts.del(V),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async(V,$=!0,Z=!0)=>{let{clock:J,connections:Q,crypto:W,store:Y,transport:X}=this,G=Q.get(V.label);if(G){if(G.isConnected())return;try{G.closeListener()}catch{}Q.delete(V.label)}let K=await Y.seed.load();if(!K)return;console.info(`Connecting to ${V.handle} (${V.label})`);let R=new GV(K,W,V,J,X(V),(I)=>Y.hosts.set(V.label,I));if(await R.register(),$)await R.listen(async(I)=>{let w={conn:R,store:Y,enclave:K,host:V,crypto:W,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return QZ(I,w,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(Q.set(V.label,R),this.clientState.emit(),Z)this.scheduleSync()};async connect(V=!0,$=!0){let{connectToHost:Z,scheduleSync:J,store:Q}=this;if(!await Q.seed.load())return;await this.drainApplyQueue();let Y=await Q.hosts.list();for(let X of Y)await Z(X,V,!1);if($)J()}disconnect=async()=>{for(let V of this.connections.values())try{V.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}var H0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function IV(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function dV(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function h(V,...$){if(!dV(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function oV(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function WZ(V,$){h(V);let Z=$.outputLen;if(V.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function aV(V){if(typeof V!=="boolean")throw Error(`boolean expected, not ${V}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */var N0=(V)=>new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4));var MJ=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!MJ)throw Error("Non little-endian hardware is not supported");function FJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function wV(V){if(typeof V==="string")V=FJ(V);else if(dV(V))V=zV(V);else throw Error("Uint8Array expected, got "+typeof V);return V}function YZ(V,$){if($==null||typeof $!=="object")throw Error("options must be defined");return Object.assign(V,$)}function XZ(V,$){if(V.length!==$.length)return!1;let Z=0;for(let J=0;J<V.length;J++)Z|=V[J]^$[J];return Z===0}var GZ=(V,$)=>{function Z(J,...Q){if(h(J),V.nonceLength!==void 0){let R=Q[0];if(!R)throw Error("nonce / iv required");if(V.varSizeNonce)h(R);else h(R,V.nonceLength)}let W=V.tagLength;if(W&&Q[1]!==void 0)h(Q[1]);let Y=$(J,...Q),X=(R,I)=>{if(I!==void 0){if(R!==2)throw Error("cipher output not supported");h(I)}},G=!1;return{encrypt(R,I){if(G)throw Error("cannot encrypt() twice with same key + nonce");return G=!0,h(R),X(Y.encrypt.length,I),Y.encrypt(R,I)},decrypt(R,I){if(h(R),W&&R.length<W)throw Error("invalid ciphertext length: smaller than tagLength="+W);return X(Y.decrypt.length,I),Y.decrypt(R,I)}}}return Object.assign(Z,V),Z};function sV(V,$,Z=!0){if($===void 0)return new Uint8Array(V);if($.length!==V)throw Error("invalid output length, expected "+V+", got: "+$.length);if(Z&&!PJ($))throw Error("invalid output, must be aligned");return $}function PJ(V){return V.byteOffset%4===0}function zV(V){return Uint8Array.from(V)}function X0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function MV(V=32){if(H0&&typeof H0.getRandomValues==="function")return H0.getRandomValues(new Uint8Array(V));if(H0&&typeof H0.randomBytes==="function")return H0.randomBytes(V);throw Error("crypto.getRandomValues must be defined")}var RZ=(V)=>Uint8Array.from(V.split("").map(($)=>$.charCodeAt(0))),UJ=RZ("expand 16-byte k"),qJ=RZ("expand 32-byte k"),OJ=N0(UJ),HJ=N0(qJ);function T(V,$){return V<<$|V>>>32-$}function tV(V){return V.byteOffset%4===0}var FV=64,CJ=16,NZ=4294967295,KZ=new Uint32Array;function TJ(V,$,Z,J,Q,W,Y,X){let G=Q.length,K=new Uint8Array(FV),R=N0(K),I=tV(Q)&&tV(W),w=I?N0(Q):KZ,M=I?N0(W):KZ;for(let P=0;P<G;Y++){if(V($,Z,J,R,Y,X),Y>=NZ)throw Error("arx: counter overflow");let z=Math.min(FV,G-P);if(I&&z===FV){let q=P/4;if(P%4!==0)throw Error("arx: invalid block position");for(let U=0,C;U<CJ;U++)C=q+U,M[C]=w[C]^R[U];P+=FV;continue}for(let q=0,U;q<z;q++)U=P+q,W[U]=Q[U]^K[q];P+=z}}function IZ(V,$){let{allowShortKeys:Z,extendNonceFn:J,counterLength:Q,counterRight:W,rounds:Y}=YZ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},$);if(typeof V!=="function")throw Error("core must be a function");return IV(Q),IV(Y),aV(W),aV(Z),(X,G,K,R,I=0)=>{h(X),h(G),h(K);let w=K.length;if(R===void 0)R=new Uint8Array(w);if(h(R),IV(I),I<0||I>=NZ)throw Error("arx: counter overflow");if(R.length<w)throw Error(`arx: output (${R.length}) is shorter than data (${w})`);let M=[],P=X.length,z,q;if(P===32)M.push(z=zV(X)),q=HJ;else if(P===16&&Z)z=new Uint8Array(32),z.set(X),z.set(X,16),q=OJ,M.push(z);else throw Error(`arx: invalid 32-byte key, got length=${P}`);if(!tV(G))M.push(G=zV(G));let U=N0(z);if(J){if(G.length!==24)throw Error("arx: extended nonce must be 24 bytes");J(q,U,N0(G.subarray(0,16)),U),G=G.subarray(16)}let C=16-Q;if(C!==G.length)throw Error(`arx: nonce must be ${C} or 16 bytes`);if(C!==12){let F=new Uint8Array(12);F.set(G,W?0:12-G.length),G=F,M.push(G)}let D=N0(G);return TJ(V,q,U,D,K,R,I,Y),X0(...M),R}}var c=(V,$)=>V[$++]&255|(V[$++]&255)<<8;class wZ{constructor(V){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,V=wV(V),h(V,32);let $=c(V,0),Z=c(V,2),J=c(V,4),Q=c(V,6),W=c(V,8),Y=c(V,10),X=c(V,12),G=c(V,14);this.r[0]=$&8191,this.r[1]=($>>>13|Z<<3)&8191,this.r[2]=(Z>>>10|J<<6)&7939,this.r[3]=(J>>>7|Q<<9)&8191,this.r[4]=(Q>>>4|W<<12)&255,this.r[5]=W>>>1&8190,this.r[6]=(W>>>14|Y<<2)&8191,this.r[7]=(Y>>>11|X<<5)&8065,this.r[8]=(X>>>8|G<<8)&8191,this.r[9]=G>>>5&127;for(let K=0;K<8;K++)this.pad[K]=c(V,16+2*K)}process(V,$,Z=!1){let J=Z?0:2048,{h:Q,r:W}=this,Y=W[0],X=W[1],G=W[2],K=W[3],R=W[4],I=W[5],w=W[6],M=W[7],P=W[8],z=W[9],q=c(V,$+0),U=c(V,$+2),C=c(V,$+4),D=c(V,$+6),F=c(V,$+8),A=c(V,$+10),L=c(V,$+12),S=c(V,$+14),k=Q[0]+(q&8191),E=Q[1]+((q>>>13|U<<3)&8191),x=Q[2]+((U>>>10|C<<6)&8191),H=Q[3]+((C>>>7|D<<9)&8191),f=Q[4]+((D>>>4|F<<12)&8191),v=Q[5]+(F>>>1&8191),y=Q[6]+((F>>>14|A<<2)&8191),n=Q[7]+((A>>>11|L<<5)&8191),p=Q[8]+((L>>>8|S<<8)&8191),l=Q[9]+(S>>>5|J),_=0,d=_+k*Y+E*(5*z)+x*(5*P)+H*(5*M)+f*(5*w);_=d>>>13,d&=8191,d+=v*(5*I)+y*(5*R)+n*(5*K)+p*(5*G)+l*(5*X),_+=d>>>13,d&=8191;let o=_+k*X+E*Y+x*(5*z)+H*(5*P)+f*(5*M);_=o>>>13,o&=8191,o+=v*(5*w)+y*(5*I)+n*(5*R)+p*(5*K)+l*(5*G),_+=o>>>13,o&=8191;let e=_+k*G+E*X+x*Y+H*(5*z)+f*(5*P);_=e>>>13,e&=8191,e+=v*(5*M)+y*(5*w)+n*(5*I)+p*(5*R)+l*(5*K),_+=e>>>13,e&=8191;let g=_+k*K+E*G+x*X+H*Y+f*(5*z);_=g>>>13,g&=8191,g+=v*(5*P)+y*(5*M)+n*(5*w)+p*(5*I)+l*(5*R),_+=g>>>13,g&=8191;let K0=_+k*R+E*K+x*G+H*X+f*Y;_=K0>>>13,K0&=8191,K0+=v*(5*z)+y*(5*P)+n*(5*M)+p*(5*w)+l*(5*I),_+=K0>>>13,K0&=8191;let A0=_+k*I+E*R+x*K+H*G+f*X;_=A0>>>13,A0&=8191,A0+=v*Y+y*(5*z)+n*(5*P)+p*(5*M)+l*(5*w),_+=A0>>>13,A0&=8191;let D0=_+k*w+E*I+x*R+H*K+f*G;_=D0>>>13,D0&=8191,D0+=v*X+y*Y+n*(5*z)+p*(5*P)+l*(5*M),_+=D0>>>13,D0&=8191;let _0=_+k*M+E*w+x*I+H*R+f*K;_=_0>>>13,_0&=8191,_0+=v*G+y*X+n*Y+p*(5*z)+l*(5*P),_+=_0>>>13,_0&=8191;let j0=_+k*P+E*M+x*w+H*I+f*R;_=j0>>>13,j0&=8191,j0+=v*K+y*G+n*X+p*Y+l*(5*z),_+=j0>>>13,j0&=8191;let L0=_+k*z+E*P+x*M+H*w+f*I;_=L0>>>13,L0&=8191,L0+=v*R+y*K+n*G+p*X+l*Y,_+=L0>>>13,L0&=8191,_=(_<<2)+_|0,_=_+d|0,d=_&8191,_=_>>>13,o+=_,Q[0]=d,Q[1]=o,Q[2]=e,Q[3]=g,Q[4]=K0,Q[5]=A0,Q[6]=D0,Q[7]=_0,Q[8]=j0,Q[9]=L0}finalize(){let{h:V,pad:$}=this,Z=new Uint16Array(10),J=V[1]>>>13;V[1]&=8191;for(let Y=2;Y<10;Y++)V[Y]+=J,J=V[Y]>>>13,V[Y]&=8191;V[0]+=J*5,J=V[0]>>>13,V[0]&=8191,V[1]+=J,J=V[1]>>>13,V[1]&=8191,V[2]+=J,Z[0]=V[0]+5,J=Z[0]>>>13,Z[0]&=8191;for(let Y=1;Y<10;Y++)Z[Y]=V[Y]+J,J=Z[Y]>>>13,Z[Y]&=8191;Z[9]-=8192;let Q=(J^1)-1;for(let Y=0;Y<10;Y++)Z[Y]&=Q;Q=~Q;for(let Y=0;Y<10;Y++)V[Y]=V[Y]&Q|Z[Y];V[0]=(V[0]|V[1]<<13)&65535,V[1]=(V[1]>>>3|V[2]<<10)&65535,V[2]=(V[2]>>>6|V[3]<<7)&65535,V[3]=(V[3]>>>9|V[4]<<4)&65535,V[4]=(V[4]>>>12|V[5]<<1|V[6]<<14)&65535,V[5]=(V[6]>>>2|V[7]<<11)&65535,V[6]=(V[7]>>>5|V[8]<<8)&65535,V[7]=(V[8]>>>8|V[9]<<5)&65535;let W=V[0]+$[0];V[0]=W&65535;for(let Y=1;Y<8;Y++)W=(V[Y]+$[Y]|0)+(W>>>16)|0,V[Y]=W&65535;X0(Z)}update(V){oV(this);let{buffer:$,blockLen:Z}=this;V=wV(V);let J=V.length;for(let Q=0;Q<J;){let W=Math.min(Z-this.pos,J-Q);if(W===Z){for(;Z<=J-Q;Q+=Z)this.process(V,Q);continue}if($.set(V.subarray(Q,Q+W),this.pos),this.pos+=W,Q+=W,this.pos===Z)this.process($,0,!1),this.pos=0}return this}destroy(){X0(this.h,this.r,this.buffer,this.pad)}digestInto(V){oV(this),WZ(V,this),this.finished=!0;let{buffer:$,h:Z}=this,{pos:J}=this;if(J){$[J++]=1;for(;J<16;J++)$[J]=0;this.process($,0,!0)}this.finalize();let Q=0;for(let W=0;W<8;W++)V[Q++]=Z[W]>>>0,V[Q++]=Z[W]>>>8;return V}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Z=V.slice(0,$);return this.destroy(),Z}}function AJ(V){let $=(J,Q)=>V(Q).update(wV(J)).digest(),Z=V(new Uint8Array(32));return $.outputLen=Z.outputLen,$.blockLen=Z.blockLen,$.create=(J)=>V(J),$}var eV=AJ((V)=>new wZ(V));function DJ(V,$,Z,J,Q,W=20){let Y=V[0],X=$[0],G=$[1],K=$[2],R=$[3],I=V[1],w=Z[0],M=Z[1],P=Q,z=0,q=V[2],U=$[4],C=$[5],D=$[6],F=$[7],A=V[3],L=Y,S=X,k=G,E=K,x=R,H=I,f=w,v=M,y=P,n=z,p=q,l=U,_=C,d=D,o=F,e=A;for(let K0=0;K0<W;K0+=2)x^=T(L+_|0,7),y^=T(x+L|0,9),_^=T(y+x|0,13),L^=T(_+y|0,18),n^=T(H+S|0,7),d^=T(n+H|0,9),S^=T(d+n|0,13),H^=T(S+d|0,18),o^=T(p+f|0,7),k^=T(o+p|0,9),f^=T(k+o|0,13),p^=T(f+k|0,18),E^=T(e+l|0,7),v^=T(E+e|0,9),l^=T(v+E|0,13),e^=T(l+v|0,18),S^=T(L+E|0,7),k^=T(S+L|0,9),E^=T(k+S|0,13),L^=T(E+k|0,18),f^=T(H+x|0,7),v^=T(f+H|0,9),x^=T(v+f|0,13),H^=T(x+v|0,18),l^=T(p+n|0,7),y^=T(l+p|0,9),n^=T(y+l|0,13),p^=T(n+y|0,18),_^=T(e+o|0,7),d^=T(_+e|0,9),o^=T(d+_|0,13),e^=T(o+d|0,18);let g=0;J[g++]=Y+L|0,J[g++]=X+S|0,J[g++]=G+k|0,J[g++]=K+E|0,J[g++]=R+x|0,J[g++]=I+H|0,J[g++]=w+f|0,J[g++]=M+v|0,J[g++]=P+y|0,J[g++]=z+n|0,J[g++]=q+p|0,J[g++]=U+l|0,J[g++]=C+_|0,J[g++]=D+d|0,J[g++]=F+o|0,J[g++]=A+e|0}function _J(V,$,Z,J){let Q=V[0],W=$[0],Y=$[1],X=$[2],G=$[3],K=V[1],R=Z[0],I=Z[1],w=Z[2],M=Z[3],P=V[2],z=$[4],q=$[5],U=$[6],C=$[7],D=V[3];for(let A=0;A<20;A+=2)G^=T(Q+q|0,7),w^=T(G+Q|0,9),q^=T(w+G|0,13),Q^=T(q+w|0,18),M^=T(K+W|0,7),U^=T(M+K|0,9),W^=T(U+M|0,13),K^=T(W+U|0,18),C^=T(P+R|0,7),Y^=T(C+P|0,9),R^=T(Y+C|0,13),P^=T(R+Y|0,18),X^=T(D+z|0,7),I^=T(X+D|0,9),z^=T(I+X|0,13),D^=T(z+I|0,18),W^=T(Q+X|0,7),Y^=T(W+Q|0,9),X^=T(Y+W|0,13),Q^=T(X+Y|0,18),R^=T(K+G|0,7),I^=T(R+K|0,9),G^=T(I+R|0,13),K^=T(G+I|0,18),z^=T(P+M|0,7),w^=T(z+P|0,9),M^=T(w+z|0,13),P^=T(M+w|0,18),q^=T(D+C|0,7),U^=T(q+D|0,9),C^=T(U+q|0,13),D^=T(C+U|0,18);let F=0;J[F++]=Q,J[F++]=K,J[F++]=P,J[F++]=D,J[F++]=R,J[F++]=I,J[F++]=w,J[F++]=M}var V$=IZ(DJ,{counterRight:!0,extendNonceFn:_J}),$$=GZ({blockSize:64,nonceLength:24,tagLength:16},(V,$)=>{return{encrypt(Z,J){J=sV(Z.length+32,J,!1);let Q=J.subarray(0,32),W=J.subarray(32);J.set(Z,32),X0(Q),V$(V,$,J,J);let Y=eV(W,Q);return J.set(Y,16),X0(J.subarray(0,16),Y),J.subarray(16)},decrypt(Z,J){h(Z),J=sV(Z.length+32,J,!1);let Q=J.subarray(0,32),W=J.subarray(32,48),Y=J.subarray(48);J.set(Z,32),X0(Q);let X=V$(V,$,Q,Q),G=eV(Y,X);if(!XZ(W,G))throw Error("invalid tag");return V$(V,$,J.subarray(16),J.subarray(16)),X0(Q,W,G),Y}}});/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function jJ(V){return V instanceof Uint8Array||ArrayBuffer.isView(V)&&V.constructor.name==="Uint8Array"}function h0(V){if(!Number.isSafeInteger(V)||V<0)throw Error("positive integer expected, got "+V)}function C0(V,...$){if(!jJ(V))throw Error("Uint8Array expected");if($.length>0&&!$.includes(V.length))throw Error("Uint8Array expected of length "+$+", got length="+V.length)}function r0(V,$=!0){if(V.destroyed)throw Error("Hash instance has been destroyed");if($&&V.finished)throw Error("Hash#digest() has already been called")}function PV(V,$){C0(V);let Z=$.outputLen;if(V.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function zZ(V){return new Uint8Array(V.buffer,V.byteOffset,V.byteLength)}function x0(V){return new Uint32Array(V.buffer,V.byteOffset,Math.floor(V.byteLength/4))}function B0(...V){for(let $=0;$<V.length;$++)V[$].fill(0)}function c0(V,$){return V<<32-$|V>>>$}var MZ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function FZ(V){return V<<24&4278190080|V<<8&16711680|V>>>8&65280|V>>>24&255}var PZ=MZ?(V)=>V:(V)=>FZ(V);function LJ(V){for(let $=0;$<V.length;$++)V[$]=FZ(V[$]);return V}var s=MZ?(V)=>V:LJ;function kJ(V){if(typeof V!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(V))}function f0(V){if(typeof V==="string")V=kJ(V);return C0(V),V}class Z${}function UZ(V){let $=(J,Q)=>V(Q).update(f0(J)).digest(),Z=V({});return $.outputLen=Z.outputLen,$.blockLen=Z.blockLen,$.create=(J)=>V(J),$}var qZ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var UV=BigInt(4294967295),OZ=BigInt(32);function J$(V,$=!1){if($)return{h:Number(V&UV),l:Number(V>>OZ&UV)};return{h:Number(V>>OZ&UV)|0,l:Number(V&UV)|0}}function I0(V,$,Z,J,Q){return V=V+$+Q|0,J=c0(J^V,16),Z=Z+J|0,$=c0($^Z,12),{a:V,b:$,c:Z,d:J}}function w0(V,$,Z,J,Q){return V=V+$+Q|0,J=c0(J^V,8),Z=Z+J|0,$=c0($^Z,7),{a:V,b:$,c:Z,d:J}}class Q$ extends Z${constructor(V,$){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,h0(V),h0($),this.blockLen=V,this.outputLen=$,this.buffer=new Uint8Array(V),this.buffer32=x0(this.buffer)}update(V){r0(this),V=f0(V),C0(V);let{blockLen:$,buffer:Z,buffer32:J}=this,Q=V.length,W=V.byteOffset,Y=V.buffer;for(let X=0;X<Q;){if(this.pos===$)s(J),this.compress(J,0,!1),s(J),this.pos=0;let G=Math.min($-this.pos,Q-X),K=W+X;if(G===$&&!(K%4)&&X+G<Q){let R=new Uint32Array(Y,K,Math.floor((Q-X)/4));s(R);for(let I=0;X+$<Q;I+=J.length,X+=$)this.length+=$,this.compress(R,I,!1);s(R);continue}Z.set(V.subarray(X,X+G),this.pos),this.pos+=G,this.length+=G,X+=G}return this}digestInto(V){r0(this),PV(V,this);let{pos:$,buffer32:Z}=this;this.finished=!0,B0(this.buffer.subarray($)),s(Z),this.compress(Z,0,!0),s(Z);let J=x0(V);this.get().forEach((Q,W)=>J[W]=PZ(Q))}digest(){let{buffer:V,outputLen:$}=this;this.digestInto(V);let Z=V.slice(0,$);return this.destroy(),Z}_cloneInto(V){let{buffer:$,length:Z,finished:J,destroyed:Q,outputLen:W,pos:Y}=this;return V||(V=new this.constructor({dkLen:W})),V.set(...this.get()),V.buffer.set($),V.destroyed=Q,V.finished=J,V.length=Z,V.pos=Y,V.outputLen=W,V}clone(){return this._cloneInto()}}function W$(V,$,Z,J,Q,W,Y,X,G,K,R,I,w,M,P,z,q,U,C,D){let F=0;for(let A=0;A<J;A++)({a:Q,b:G,c:w,d:q}=I0(Q,G,w,q,Z[$+V[F++]])),{a:Q,b:G,c:w,d:q}=w0(Q,G,w,q,Z[$+V[F++]]),{a:W,b:K,c:M,d:U}=I0(W,K,M,U,Z[$+V[F++]]),{a:W,b:K,c:M,d:U}=w0(W,K,M,U,Z[$+V[F++]]),{a:Y,b:R,c:P,d:C}=I0(Y,R,P,C,Z[$+V[F++]]),{a:Y,b:R,c:P,d:C}=w0(Y,R,P,C,Z[$+V[F++]]),{a:X,b:I,c:z,d:D}=I0(X,I,z,D,Z[$+V[F++]]),{a:X,b:I,c:z,d:D}=w0(X,I,z,D,Z[$+V[F++]]),{a:Q,b:K,c:P,d:D}=I0(Q,K,P,D,Z[$+V[F++]]),{a:Q,b:K,c:P,d:D}=w0(Q,K,P,D,Z[$+V[F++]]),{a:W,b:R,c:z,d:q}=I0(W,R,z,q,Z[$+V[F++]]),{a:W,b:R,c:z,d:q}=w0(W,R,z,q,Z[$+V[F++]]),{a:Y,b:I,c:w,d:U}=I0(Y,I,w,U,Z[$+V[F++]]),{a:Y,b:I,c:w,d:U}=w0(Y,I,w,U,Z[$+V[F++]]),{a:X,b:G,c:M,d:C}=I0(X,G,M,C,Z[$+V[F++]]),{a:X,b:G,c:M,d:C}=w0(X,G,M,C,Z[$+V[F++]]);return{v0:Q,v1:W,v2:Y,v3:X,v4:G,v5:K,v6:R,v7:I,v8:w,v9:M,v10:P,v11:z,v12:q,v13:U,v14:C,v15:D}}var G0={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},z0=qZ.slice(),HZ=(()=>{let V=Array.from({length:16},(J,Q)=>Q),$=(J)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((Q)=>J[Q]),Z=[];for(let J=0,Q=V;J<7;J++,Q=$(Q))Z.push(...Q);return Uint8Array.from(Z)})();class Y$ extends Q${constructor(V={},$=0){super(64,V.dkLen===void 0?32:V.dkLen);this.chunkPos=0,this.chunksDone=0,this.flags=0,this.stack=[],this.posOut=0,this.bufferOut32=new Uint32Array(16),this.chunkOut=0,this.enableXOF=!0;let{key:Z,context:J}=V,Q=J!==void 0;if(Z!==void 0){if(Q)throw Error('Only "key" or "context" can be specified at same time');let W=f0(Z).slice();C0(W,32),this.IV=x0(W),s(this.IV),this.flags=$|G0.KEYED_HASH}else if(Q){let W=f0(J),Y=new Y$({dkLen:32},G0.DERIVE_KEY_CONTEXT).update(W).digest();this.IV=x0(Y),s(this.IV),this.flags=$|G0.DERIVE_KEY_MATERIAL}else this.IV=z0.slice(),this.flags=$;this.state=this.IV.slice(),this.bufferOut=zZ(this.bufferOut32)}get(){return[]}set(){}b2Compress(V,$,Z,J=0){let{state:Q,pos:W}=this,{h:Y,l:X}=J$(BigInt(V),!0),{v0:G,v1:K,v2:R,v3:I,v4:w,v5:M,v6:P,v7:z,v8:q,v9:U,v10:C,v11:D,v12:F,v13:A,v14:L,v15:S}=W$(HZ,J,Z,7,Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7],z0[0],z0[1],z0[2],z0[3],Y,X,W,$);Q[0]=G^q,Q[1]=K^U,Q[2]=R^C,Q[3]=I^D,Q[4]=w^F,Q[5]=M^A,Q[6]=P^L,Q[7]=z^S}compress(V,$=0,Z=!1){let J=this.flags;if(!this.chunkPos)J|=G0.CHUNK_START;if(this.chunkPos===15||Z)J|=G0.CHUNK_END;if(!Z)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,J,V,$),this.chunkPos+=1,this.chunkPos===16||Z){let Q=this.state;this.state=this.IV.slice();for(let W,Y=this.chunksDone+1;Z||!(Y&1);Y>>=1){if(!(W=this.stack.pop()))break;this.buffer32.set(W,0),this.buffer32.set(Q,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|G0.PARENT,this.buffer32,0),Q=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(Q)}this.pos=0}_cloneInto(V){V=super._cloneInto(V);let{IV:$,flags:Z,state:J,chunkPos:Q,posOut:W,chunkOut:Y,stack:X,chunksDone:G}=this;return V.state.set(J.slice()),V.stack=X.map((K)=>Uint32Array.from(K)),V.IV.set($),V.flags=Z,V.chunkPos=Q,V.chunksDone=G,V.posOut=W,V.chunkOut=Y,V.enableXOF=this.enableXOF,V.bufferOut32.set(this.bufferOut32),V}destroy(){this.destroyed=!0,B0(this.state,this.buffer32,this.IV,this.bufferOut32),B0(...this.stack)}b2CompressOut(){let{state:V,pos:$,flags:Z,buffer32:J,bufferOut32:Q}=this,{h:W,l:Y}=J$(BigInt(this.chunkOut++));s(J);let{v0:X,v1:G,v2:K,v3:R,v4:I,v5:w,v6:M,v7:P,v8:z,v9:q,v10:U,v11:C,v12:D,v13:F,v14:A,v15:L}=W$(HZ,0,J,7,V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],z0[0],z0[1],z0[2],z0[3],Y,W,$,Z);Q[0]=X^z,Q[1]=G^q,Q[2]=K^U,Q[3]=R^C,Q[4]=I^D,Q[5]=w^F,Q[6]=M^A,Q[7]=P^L,Q[8]=V[0]^z,Q[9]=V[1]^q,Q[10]=V[2]^U,Q[11]=V[3]^C,Q[12]=V[4]^D,Q[13]=V[5]^F,Q[14]=V[6]^A,Q[15]=V[7]^L,s(J),s(Q),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,B0(this.buffer.subarray(this.pos));let V=this.flags|G0.ROOT;if(this.stack.length)V|=G0.PARENT,s(this.buffer32),this.compress(this.buffer32,0,!0),s(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else V|=(!this.chunkPos?G0.CHUNK_START:0)|G0.CHUNK_END;this.flags=V,this.b2CompressOut()}writeInto(V){r0(this,!1),C0(V),this.finish();let{blockLen:$,bufferOut:Z}=this;for(let J=0,Q=V.length;J<Q;){if(this.posOut>=$)this.b2CompressOut();let W=Math.min($-this.posOut,Q-J);V.set(Z.subarray(this.posOut,this.posOut+W),J),this.posOut+=W,J+=W}return V}xofInto(V){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(V)}xof(V){return h0(V),this.xofInto(new Uint8Array(V))}digestInto(V){if(PV(V,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto(V),this.destroy(),V}digest(){return this.digestInto(new Uint8Array(this.outputLen))}}var CZ=UZ((V)=>new Y$(V));var X$=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function TZ(V){let $=new Uint8Array(X$.length+32);return $.set(X$),$.set(V.subarray(0,32),X$.length),$}function AZ(V){return typeof V==="string"?new TextEncoder().encode(V):V}function m0(V){let $=new ArrayBuffer(V.byteLength);return new Uint8Array($).set(V),$}class G${verifyKeys=new Map;signKeys=new Map;async genRandomBytes(V){return MV(V)}async gen256BitSecureRandomSeed(){return MV(32)}async encryptXSalsa20Poly1305Combined(V,$){let Z=MV(24),Q=$$($,Z).encrypt(V);return new Uint8Array([...Z,...Q])}async decryptXSalsa20Poly1305Combined(V,$){let Z=V.slice(0,24),J=V.slice(24);return $$($,Z).decrypt(J)}async deriveEd25519KeyPair(V){let $=V,Z=TZ($),J=await globalThis.crypto.subtle.importKey("pkcs8",m0(Z),{name:"Ed25519"},!0,["sign"]),Q=await globalThis.crypto.subtle.exportKey("jwk",J);if(typeof Q.x!=="string")throw Error("Ed25519 JWK missing x");let W=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:Q.x},{name:"Ed25519"},!0,["verify"]),Y=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",W)),X=new Uint8Array(64);return X.set($,0),X.set(Y,32),this.signKeys.set(W0($),J),this.verifyKeys.set(W0(Y),W),{keyType:"ed25519",privateKey:X,publicKey:Y}}async importSignKey(V){let $=V.subarray(0,32),Z=W0($),J=this.signKeys.get(Z);if(J)return J;let Q=TZ($),W=await globalThis.crypto.subtle.importKey("pkcs8",m0(Q),{name:"Ed25519"},!1,["sign"]);return this.signKeys.set(Z,W),W}async importVerifyKey(V){let $=W0(V),Z=this.verifyKeys.get($);if(Z)return Z;let J=await globalThis.crypto.subtle.importKey("raw",m0(V),{name:"Ed25519"},!1,["verify"]);return this.verifyKeys.set($,J),J}async signEd25519(V,$){let Z=AZ(V),J=await this.importSignKey($),Q=await globalThis.crypto.subtle.sign({name:"Ed25519"},J,m0(Z));return new Uint8Array(Q)}async checkSigEd25519(V,$,Z){let J=AZ($);try{let Q=await this.importVerifyKey(Z);return await globalThis.crypto.subtle.verify({name:"Ed25519"},Q,m0(V),m0(J))}catch{return!1}}async blake3(V){return CZ(V)}}var EJ=new G$,g0=EJ;var UG=Symbol("EntityID");function DZ(V){return"type"in V}var qG=Symbol("MasterSeed"),OG=Symbol("DerivationSeed"),HG=Symbol("PublicKey"),CG=Symbol("PrivateKey"),TG=Symbol("HostSpecificKeyPair"),AG=Symbol("Hash");function SJ(V){if(!V)return!1;if(typeof V!=="object")return!1;if("body"in V===!1)return!1;if("type"in V===!1)return!1;return!0}function xJ(V){if(!V.bod||V.bod.length===0){let J={off:V.off,ctr:V.ctr,eid:V.eid};return O(J)}let $=jV(V.bod);if(SJ($)===!1)return console.warn("msg body invalid",$),N(14);let Z={off:V.off,ctr:V.ctr,eid:V.eid,gid:$.gid,pid:$.pid,type:$.type,body:$.body};return O(Z)}class qV{applier;emitter=new y0;clearer;onTypes;constructor(V,$,Z){this.applier=V;this.clearer=$,this.onTypes=Z}apply=async(V)=>{let $=[],Z=[];for(let Y of V){let[X,G]=xJ(Y);if(Z.push(G),G!==0)continue;$.push(X)}let{stats:J,types:Q}=await this.applier($),W=[];for(let Y=0;Y<V.length;Y++){let X=Z[Y],G=J[Y];if(X!==0){W.push(X);continue}if(G!==0){W.push(G);continue}W.push(0)}for(let Y of Q)this.emitter.emit(Y,null);if(Q.size>0)this.onTypes?.(Q);return W};clear=async()=>{let V=await this.clearer();if(V!==0)return V;return this.emitter.emitAll(null),V};notify=(V)=>{for(let $ of V)this.emitter.emit($,null)};on=(V,$)=>{this.emitter.addEventListener(V,$)};off=(V,$)=>{this.emitter.removeEventListener(V,$)}}function _Z(V,$){let Z=new m($.eid),[J,Q]=Z.readStruct(J0);if(Q!==0)return N(Q);let W=new Date(J.ts.getTime()+$.off);if(V!==void 0&&W<=V.updatedAt)return N(15);if(DZ($))return O({eid:$.eid,gid:$.gid,pid:$.pid,type:$.type,createdAt:J.ts,updatedAt:W,ctr:$.ctr,body:$.body});else return O(void 0)}var b="entities",OV="entity_type_created_at",K$="entity_type_updated_at",R$="entity_type_group_id",N$="entity_type_parent_id";function BJ(V){let $={bod:V.body,crd:V.createdAt,...V.ctr!==0?{ctr:V.ctr}:{},eid:i(V.eid),gid:V.gid,pid:V.pid?i(V.pid):void 0,typ:V.type,upd:V.updatedAt};if($.gid===void 0)delete $.gid;if($.pid===void 0)delete $.pid;if($.ctr===void 0)delete $.ctr;return $}function v0(V){return{body:V.bod,createdAt:V.crd,updatedAt:V.upd,ctr:V.ctr??0,type:V.typ,eid:R0(V.eid),gid:V.gid,pid:V.pid?R0(V.pid):void 0}}class jZ{db;async init(){this.db=await new Promise((V,$)=>{let Z=indexedDB.open("db",11);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!Q)throw Error("Transaction is null during upgrade");if(!J.objectStoreNames.contains(b))J.createObjectStore(b,{keyPath:"eid",autoIncrement:!1});let W=Q.objectStore(b);if(!W.indexNames.contains(OV))W.createIndex(OV,["typ","crd"],{unique:!1});if(!W.indexNames.contains(K$))W.createIndex(K$,["typ","upd"],{unique:!1});if(!W.indexNames.contains(R$))W.createIndex(R$,["typ","gid"],{unique:!1});if(!W.indexNames.contains(N$))W.createIndex(N$,["typ","pid"],{unique:!1})},Z.onsuccess=()=>V(Z.result),Z.onerror=()=>$(Z.error)})}apply=async(V)=>{let $=new Set;if(!this.db)return{stats:V.map(()=>16),types:$};let Z=this.db.transaction(b,"readwrite"),J=Z.objectStore(b);return new Promise((Q)=>{let W=Array(V.length).fill(0);if(V.length<1){Q({stats:[],types:$});return}Z.oncomplete=()=>{Q({stats:W,types:$})},Z.onerror=()=>{for(let X=0;X<W.length;X++)if(W[X]===void 0)W[X]=18;Q({stats:W,types:$})};let Y=new Map;for(let X=0;X<V.length;X++){let G=V[X],K=i(G.eid),R={op:G,index:X},I=Y.get(K);if(I)I.push(R);else Y.set(K,[R])}for(let[X,G]of Y){if(G.length<1)continue;let K=J.get(X);K.onsuccess=()=>{let R=K.result,I=R?v0(R):void 0;for(let{op:w,index:M}of G){let[P,z]=_Z(I,w);if(z!==0){W[M]=z;continue}if(P)$.add(P.type);else if(I)$.add(I.type);I=P}if(I){let w=BJ(I),M=J.put(w);M.onerror=(P)=>{P.preventDefault();for(let{index:z}of G)W[z]=18}}else{let w=J.delete(X);w.onerror=()=>{for(let{index:M}of G)W[M]=18}}},K.onerror=()=>{for(let{index:R}of G)W[R]=18}}})};async clear(){if(!this.db)return 16;let V=this.db.transaction(b,"readwrite"),$=V.objectStore(b);return new Promise((Z)=>{V.oncomplete=()=>Z(0),V.onerror=()=>Z(18),$.clear()})}async getEnt(V){if(!this.db)return N(16);let $=i(V),J=this.db.transaction(b,"readonly").objectStore(b);return new Promise((Q)=>{let W=J.get($);W.onsuccess=()=>{let Y=W.result;if(!Y)Q(O(void 0));else{let X=v0(Y);Q(O(X))}},W.onerror=()=>Q(N(18))})}async getAllOfTypeUpdatedBetween(V,$,Z){if(!this.db)return N(16);let Q=this.db.transaction(b,"readonly").objectStore(b).index(K$);return new Promise((W)=>{let Y=Q.getAll(IDBKeyRange.bound([V,$],[V,Z]));Y.onsuccess=()=>{let X=Y.result;W(O(X.map(v0)))},Y.onerror=()=>W(N(18))})}async getGroupMembers(V,$){if(!this.db)return N(16);let J=this.db.transaction(b,"readonly").objectStore(b).index(R$);return new Promise((Q)=>{let W=J.getAll(IDBKeyRange.only([V,$]));W.onsuccess=()=>{let Y=W.result;Q(O(Y.map(v0)))},W.onerror=()=>Q(N(18))})}async getAllOfType(V){if(!this.db)return N(16);let Z=this.db.transaction(b,"readonly").objectStore(b).index(OV);return new Promise((J)=>{let Q=Z.getAll(IDBKeyRange.bound([V],[V,[]]));Q.onsuccess=()=>{let W=Q.result;J(O(W.map(v0)))},Q.onerror=()=>J(N(18))})}async getAllEntities(V){if(!this.db)return N(16);if("pid"in V){let $=i(V.pid),J=this.db.transaction(b,"readonly").objectStore(b).index(N$);return new Promise((Q)=>{let W=J.getAll(IDBKeyRange.only([V.type,$]));W.onsuccess=()=>{let X=W.result.map(v0);Q(O(X))},W.onerror=()=>Q(N(18))})}else if("gid"in V)return await this.getGroupMembers(V.type,V.gid);else if("updatedBetween"in V)return await this.getAllOfTypeUpdatedBetween(V.type,V.updatedBetween.start,V.updatedBetween.end);return await this.getAllOfType(V.type)}async getEntities(V){let[$,Z]=await this.getAllEntities(V);if(Z!==0)return N(Z);return O($)}async countEntities({type:V}){if(!this.db)return N(16);let Z=this.db.transaction(b,"readonly").objectStore(b).index(OV);return new Promise((J)=>{let Q=IDBKeyRange.bound([V],[V,[]]),W=Z.count(Q);W.onsuccess=()=>J(O(W.result)),W.onerror=()=>J(N(18))})}}async function LZ(){let V=new jZ;return await V.init(),V}class I${db;constructor(V){this.db=V}async enq(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction($0,"readwrite"),J=Z.objectStore($0);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=`${Y.host}:${Y.seq}`;J.put(Y,X)}})}async deq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction($0,"readwrite"),Q=J.objectStore($0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let G=`${V}:${X}`;Q.delete(G)}})}async list(){let $=this.db.transaction($0,"readonly").objectStore($0);return new Promise((Z,J)=>{let Q=$.getAll();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async count(){let $=this.db.transaction($0,"readonly").objectStore($0);return new Promise((Z,J)=>{let Q=$.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction($0,"readwrite"),$=V.objectStore($0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}function kZ(V){return{label:V.label,handle:new URL(V.handle),idx:V.idx,lastSeq:V.lastSeq||0,clockOffset:V.clockOffset,subscription:V.subscription}}class w${db;constructor(V){this.db=V}async add(V){return this.put(V)}async put(V){let $={...V,handle:V.handle.toString(),lastSeq:V.lastSeq??0},Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error),J.put($)})}async touch(V,$){let Z=this.db.transaction(t,"readwrite"),J=Z.objectStore(t);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);let Y=J.get(V);Y.onsuccess=()=>{let X=Y.result;if(!X)return;let G=X.lastSeq||0;if($<=G)return;J.put({...X,lastSeq:$})}})}async get(V){let Z=this.db.transaction(t,"readonly").objectStore(t);return new Promise((J,Q)=>{let W=Z.get(V);W.onsuccess=()=>{let Y=W.result;if(!Y)J(void 0);else J(kZ(Y))},W.onerror=()=>Q(W.error)})}async set(V,$){let Z=await this.get(V);if(!Z)return 13;try{return await this.put({...Z,...$}),0}catch{return 18}}async del(V){let $=this.db.transaction(t,"readwrite"),Z=$.objectStore(t);return new Promise((J,Q)=>{$.oncomplete=()=>J(),$.onerror=()=>Q($.error),Z.delete(V)})}async list(){let $=this.db.transaction(t,"readonly").objectStore(t);return new Promise((Z,J)=>{let Q=$.getAll();Q.onsuccess=()=>{let W=Q.result;Z(W.map(kZ))},Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(t,"readwrite"),$=V.objectStore(t);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}function fJ(V){return V===!0||V==="t"}function z$(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld===void 0?!1:fJ(V.apld)}}async function d0(V,$,Z){let J=z$($),Q=J.body?.length??0,W;if(J.body&&Q>0)W=await Z.blake3(J.body);let Y={eid:J.eid,off:J.off??0,ctr:J.ctr??0,len:Q,hsh:W};return{hash:V,head:Y,body:J.body,applied:J.apld}}function EZ(V){return{eid:V.eid,...V.off!==void 0?{off:V.off}:{},...V.ctr!==void 0?{ctr:V.ctr}:{},...V.body!==void 0?{body:V.body}:{},apld:V.apld?"t":"f"}}class M${crypto;db;constructor(V,$){this.crypto=$;this.db=V}async add(V){let $=this.db.transaction(u,"readwrite"),Z=$.objectStore(u);return new Promise((J)=>{if(V.length===0){J([]);return}let Q=Array(V.length).fill(0);$.oncomplete=()=>J(Q),$.onerror=()=>{for(let W=0;W<Q.length;W++)Q[W]=18;J(Q)};for(let W=0;W<V.length;W++){let{key:Y,data:X}=V[W],G=i(Y),K=Z.put(EZ(X),G);K.onerror=(R)=>{R.preventDefault(),Q[W]=18}}})}async del(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(u,"readwrite"),J=Z.objectStore(u);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=i(Y);J.delete(X)}})}async get(V){let[$]=await this.getMany([V]);return $}async getMany(V){let $=[...V];if($.length<1)return[];let J=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Q,W)=>{let Y=Array($.length),X=$.length,G=!1,K=async()=>{try{let R=[];for(let I=0;I<$.length;I++){let w=Y[I];if(w)R.push(await d0($[I],w,this.crypto));else R.push(void 0)}Q(R)}catch(R){W(R)}};for(let R=0;R<$.length;R++){let I=R,w=J.get(i($[R]));w.onsuccess=()=>{if(G)return;if(Y[I]=w.result,X-=1,X===0)K()},w.onerror=()=>{if(G)return;G=!0,W(w.error)}}})}async has(V){return await this.get(V)!==void 0}async list(){let $=this.db.transaction(u,"readonly").objectStore(u);return new Promise((Z,J)=>{let Q=[],W=$.openCursor();W.onsuccess=async(Y)=>{let X=Y.target.result;if(X){let{key:G,value:K}=X,R=R0(G),I=await d0(R,K,this.crypto);Q.push(I),X.continue()}else Z(Q)},W.onerror=()=>J(W.error)})}async last(V){let Z=this.db.transaction(u,"readonly").objectStore(u);return new Promise((J,Q)=>{let W,Y=Z.openCursor();Y.onsuccess=async(X)=>{let G=X.target.result;if(G){let{key:K,value:R}=G;if(O0(V,R.eid)){if(!W||(R.ctr??0)>(W.data.ctr??0)||(R.ctr??0)===(W.data.ctr??0)&&(R.off??0)>(W.data.off??0))W={key:K,data:R}}G.continue()}else if(W){let K=R0(W.key);J(await d0(K,W.data,this.crypto))}else J(void 0)},Y.onerror=()=>Q(Y.error)})}async listUnapplied(){let Z=this.db.transaction(u,"readonly").objectStore(u).index(HV);return new Promise((J,Q)=>{let W=[],Y=Z.openCursor(IDBKeyRange.only("f"));Y.onsuccess=(X)=>{let G=X.target.result;if(G){let{primaryKey:K,value:R}=G;W.push({hash:R0(K),data:R}),G.continue()}else Promise.all(W.map(({hash:K,data:R})=>d0(K,R,this.crypto))).then(J).catch(Q)},Y.onerror=()=>Q(Y.error)})}async markApplied(V){let $=[...V];if($.length===0)return;let Z=this.db.transaction(u,"readwrite"),J=Z.objectStore(u);return new Promise((Q,W)=>{Z.oncomplete=()=>Q(),Z.onerror=()=>W(Z.error);for(let Y of $){let X=i(Y),G=J.get(X);G.onsuccess=()=>{let K=G.result;if(!K)return;let R=z$(K);J.put(EZ({...R,apld:!0}),X)},G.onerror=(K)=>{K.preventDefault()}}})}async wipe(){let V=this.db.transaction(u,"readwrite"),$=V.objectStore(u);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}class CV{seed;crypto;constructor(V,$){this.seed=V,this.crypto=$}async deriveFromKDM(V){let $=n0(this.seed,V);return await this.crypto.blake3($)}async derive(V,$=0){let Z=new TextEncoder().encode(V),J=new Uint8Array(8);new DataView(J.buffer).setBigUint64(0,BigInt($),!1);let Q=n0(Z,J);return await this.deriveFromKDM(Q)}}class F${enclave;db;constructor(V){this.db=V}async save(V){let $=W0(V),Z=this.db.transaction(M0,"readwrite"),J=Z.objectStore(M0);return new Promise((Q,W)=>{Z.oncomplete=()=>{this.enclave=new CV(V,g0),Q(this.enclave)},Z.onerror=()=>W(Z.error),J.put($,"seed")})}async load(){if(this.enclave)return this.enclave;let $=this.db.transaction(M0,"readonly").objectStore(M0);return new Promise((Z,J)=>{let Q=$.get("seed");Q.onsuccess=()=>{let W=Q.result;if(!W)Z(void 0);else{let Y=QV(W);this.enclave=new CV(Y,g0),Z(this.enclave)}},Q.onerror=()=>J(Q.error)})}async wipe(){this.enclave=void 0;let V=this.db.transaction(M0,"readwrite"),$=V.objectStore(M0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.delete("seed")})}}class P${db;constructor(V){this.db=V}async enq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(Z0,"readwrite"),Q=J.objectStore(Z0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let G=W0(X.hash);Q.put({host:V,hash:G,bodyLen:X.bodyLen})}})}async deq(V,$){let Z=[...$];if(Z.length===0)return;let J=this.db.transaction(Z0,"readwrite"),Q=J.objectStore(Z0);return new Promise((W,Y)=>{J.oncomplete=()=>W(),J.onerror=()=>Y(J.error);for(let X of Z){let G=W0(X);Q.delete([V,G])}})}async list(V){let Z=this.db.transaction(Z0,"readonly").objectStore(Z0);return new Promise((J,Q)=>{let W=Z.getAll();W.onsuccess=()=>{let Y=W.result,X=[];for(let G of Y){if(G.host!==V)continue;X.push({hash:QV(G.hash),bodyLen:G.bodyLen??0})}J(X)},W.onerror=()=>Q(W.error)})}async count(){let $=this.db.transaction(Z0,"readonly").objectStore(Z0);return new Promise((Z,J)=>{let Q=$.count();Q.onsuccess=()=>Z(Q.result),Q.onerror=()=>J(Q.error)})}async wipe(){let V=this.db.transaction(Z0,"readwrite"),$=V.objectStore(Z0);return new Promise((Z,J)=>{V.oncomplete=()=>Z(),V.onerror=()=>J(V.error),$.clear()})}}var M0="seedMeta",t="hosts",Z0="uploadQueue",$0="downloadQueue",u="messages",HV="apld",mJ=3;class SZ{seed;hosts;uploads;downloads;messages;db;constructor(V,$){this.db=V,this.seed=new F$(V),this.hosts=new w$(V),this.uploads=new P$(V),this.downloads=new I$(V),this.messages=new M$(V,$)}async wipe(){await this.seed.wipe(),await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function gJ(){return new Promise((V,$)=>{let Z=indexedDB.open("diplomatic-store-db",mJ);Z.onupgradeneeded=()=>{let{result:J,transaction:Q}=Z;if(!J.objectStoreNames.contains(M0))J.createObjectStore(M0);if(!J.objectStoreNames.contains(t))J.createObjectStore(t,{keyPath:"label"});if(!J.objectStoreNames.contains(Z0))J.createObjectStore(Z0,{keyPath:["host","hash"]});if(!J.objectStoreNames.contains($0))J.createObjectStore($0);let W;if(!J.objectStoreNames.contains(u))W=J.createObjectStore(u);else{if(!Q)throw Error("missing upgrade transaction for messages store");W=Q.objectStore(u)}if(!W.indexNames.contains(HV))W.createIndex(HV,"apld",{unique:!1})},Z.onsuccess=()=>V(Z.result),Z.onerror=()=>$(Z.error)})}async function xZ(V){let $=await gJ();if(navigator.storage&&navigator.storage.persist)await navigator.storage.persist();return new SZ($,V)}class U${client;post;whenReady;resolveReady;rejectReady;constructor(V){this.post=V,this.whenReady=new Promise(($,Z)=>{this.resolveReady=$,this.rejectReady=Z})}async init(){try{let V=await xZ(g0),$=await LZ(),Z=new qV($.apply,()=>$.clear(),(W)=>{this.post({kind:"dirty",types:Array.from(W)})}),J=Z.clear;Z.clear=async()=>{let W=await J();if(W===0)this.post({kind:"wiped"});return W};let Q=new cV(new SV,Z,V,n$,g0);this.client=Q,Q.clientState.listen(()=>{this.emitClientState()}),Q.xferState.listen(()=>{this.emitXferState()}),this.post({kind:"ready"}),this.markReady(),await this.emitClientState(),await this.emitXferState()}catch(V){let $=V instanceof Error?V:Error(String(V));throw this.failReady($),$}}markReady(){let V=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,V)V()}failReady(V){let $=this.rejectReady;if(this.resolveReady=void 0,this.rejectReady=void 0,$)$(V)}requireClient(){if(!this.client)throw Error("WorkerRuntime not initialized");return this.client}async emitClientState(){let V=this.client;if(!V)return;let $=await V.clientState.get();this.post({kind:"clientState",state:$})}async emitXferState(){let V=this.client;if(!V)return;let $=await V.xferState.get();this.post({kind:"xferState",state:$})}hostFromSerialized(V){return{handle:new URL(V.handle),label:V.label,idx:V.idx}}async handle(V){await this.whenReady;let $=this.requireClient();switch(V.op){case"ping":return"pong";case"setSeed":{await $.setSeed(vJ(V.seed));return}case"link":{await $.link(this.hostFromSerialized(V.host),V.connect??!0);return}case"unlink":{await $.unlink(V.label);return}case"connect":{await $.connect(V.listen??!0,V.sync??!0);return}case"disconnect":{await $.disconnect();return}case"sync":return await $.sync();case"wipe":{await $.wipe();return}case"insertRaw":{let[Z,J]=await $.insertRaw(BZ(V.body));if(J!==0)throw new Y0(J);return Z}case"upsertRaw":{let[Z,J]=await $.upsertRaw(o0(V.eid),V.body!==void 0?BZ(V.body):void 0,V.force);if(J!==0)throw new Y0(J);return Z}case"insert":{let[Z,J]=await $.insert({type:V.params.type,body:V.params.body,gid:V.params.gid,pid:V.params.pid!==void 0?o0(V.params.pid):void 0});if(J!==0)throw new Y0(J);return Z}case"upsert":{let[Z,J]=await $.upsert({type:V.params.type,body:V.params.body,eid:V.params.eid!==void 0?o0(V.params.eid):void 0,gid:V.params.gid,pid:V.params.pid!==void 0?o0(V.params.pid):void 0},V.force);if(J!==0)throw new Y0(J);return Z}case"delete":{let[Z,J]=await $.delete(o0(V.eid));if(J!==0)throw new Y0(J);return Z}case"import":{let Z=V.bytes.slice(),J=new Blob([Z]),Q=new File([J],"import.dip");return await $.import(Q)}case"export":{let[Z,J]=await $.exportBytes();if(J!==0)throw new Y0(J);if(!Z)throw new Y0(12);return Z}case"getClientState":return await $.clientState.get();case"getXferState":return await $.xferState.get();default:{let Z=V;throw Error("unknown worker command")}}}}class Y0 extends Error{status;constructor(V){super(`WorkerStatusError: ${j[V]}`);this.status=V;this.name="WorkerStatusError"}}function q$(V,$){return{kind:"reply",id:V,ok:!0,result:$}}function O$(V,$){return{kind:"reply",id:V,ok:!1,status:$}}function vJ(V){if(V.length!==32)throw new Y0(10);return V}function o0(V){return V}function BZ(V){return V}var T0=globalThis,fZ=new U$((V,$)=>{if($&&$.length>0)T0.postMessage(V,$);else T0.postMessage(V)});T0.onmessage=(V)=>{let $=V.data;if(!A$($))return;iJ($)};async function iJ(V){try{let $=await fZ.handle(V);if(V.op==="export"&&$ instanceof Uint8Array){let Z=$.slice();T0.postMessage(q$(V.id,Z),[Z.buffer]);return}T0.postMessage(q$(V.id,$))}catch($){if($ instanceof Y0){T0.postMessage(O$(V.id,$.status));return}console.error("worker command failed",$),T0.postMessage(O$(V.id,12))}}fZ.init().catch((V)=>{console.error("worker init failed",V)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@interncom/diplomatic",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "type": "module",
5
5
  "description": "Secure sync layer and CLI utilities for DIPLOMATIC",
6
6
  "files": [