@interncom/diplomatic 0.24.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.mjs +2 -2
- package/dist/cli/shared/crypto/derivation.d.ts +1 -0
- package/dist/cli/shared/crypto/enclave.d.ts +1 -0
- package/dist/web/index.d.ts +2 -1
- package/dist/web/index.mjs +1 -1
- package/dist/web/shared/codecs/file.d.ts +2 -3
- package/dist/web/shared/codecs/fileHead.d.ts +6 -4
- package/dist/web/shared/codecs/fileIndexItem.d.ts +0 -1
- package/dist/web/shared/codecs/fileRealm.d.ts +9 -0
- package/dist/web/shared/crypto/derivation.d.ts +1 -0
- package/dist/web/shared/crypto/enclave.d.ts +1 -0
- package/dist/web/shared/crypto/exim.d.ts +22 -0
- package/dist/web/shared/crypto/export.d.ts +5 -0
- package/dist/web/worker.mjs +1 -1
- package/package.json +1 -1
- package/dist/web/shared/exim.d.ts +0 -24
package/dist/web/worker.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Sa=Object.defineProperty;var ba=(e)=>e;function Ia(e,t){this[e]=ba.bind(null,t)}var wa=(e,t)=>{for(var r in t)Sa(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Ia.bind(t,r)})};var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var Re=64,oe=32,As=32,Le=8,er=32,ks=30000,Ds=512,A;var D=_(()=>{((I)=>{I[I.Success=0]="Success";I[I.InvalidSignature=3]="InvalidSignature";I[I.ClockOutOfSync=4]="ClockOutOfSync";I[I.UserNotRegistered=5]="UserNotRegistered";I[I.ServerMisconfigured=6]="ServerMisconfigured";I[I.MissingBody=7]="MissingBody";I[I.ExtraBodyContent=8]="ExtraBodyContent";I[I.MissingParam=9]="MissingParam";I[I.InvalidParam=10]="InvalidParam";I[I.InvalidRequest=11]="InvalidRequest";I[I.InternalError=12]="InternalError";I[I.NotFound=13]="NotFound";I[I.InvalidMessage=14]="InvalidMessage";I[I.NoChange=15]="NoChange";I[I.DatabaseClosed=16]="DatabaseClosed";I[I.StorageError=17]="StorageError";I[I.DatabaseError=18]="DatabaseError";I[I.HashMismatch=19]="HashMismatch";I[I.DecryptionError=20]="DecryptionError";I[I.NotImplemented=21]="NotImplemented";I[I.MissingSeed=22]="MissingSeed";I[I.OutOfBounds=23]="OutOfBounds";I[I.HostError=24]="HostError";I[I.CommunicationError=25]="CommunicationError";I[I.VarLimitExceeded=26]="VarLimitExceeded";I[I.InvalidResponse=27]="InvalidResponse";I[I.ConnectionClosed=28]="ConnectionClosed";I[I.CryptoError=29]="CryptoError";I[I.WebAuthnError=30]="WebAuthnError"})(A||={})});function f(e){return[e,0]}function a(e){return[void 0,e]}var M=_(()=>{D()});function xa(e){if(e<0)console.info("N",e),console.trace();if(typeof e!=="bigint")e=BigInt(e);if(e<0n)return a(10);let t=[];while(e>0n){let r=Number(e&0x7fn);if(e>>=7n,e>0n)t.push(r|128);else t.push(r)}if(t.length===0)return f(new Uint8Array([0]));if(t.length>8)return a(26);return f(new Uint8Array(t))}function Pa(e,t=0){let r=0n,n=0,s=t;while(!0){if(s>=e.length)return a(14);let o=e[s++];if(o===void 0)return a(14);if(r|=BigInt(o&127)<<BigInt(n),(o&128)===0){if(s-t>8)return a(26);return f({value:r>0x1fffffffffffffn?r:Number(r),bytesRead:s-t})}if(n+=7,n>=56)return a(26)}}class L{data;pos=0;constructor(e){this.data=e}static async fromResponse(e){let t=await e.arrayBuffer(),r=new Uint8Array(t);return new L(r)}readBigInt(){if(this.pos+8>this.data.length)return a(7);let e=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,f(e)}readDate(){let[e,t]=this.readVarInt();if(t!==0)return a(t);return f(new Date(e))}readVarInt(){let[e,t]=Pa(this.data,this.pos);if(t!==0)return a(t);this.pos+=e.bytesRead;let r=e.value;return f(typeof r==="bigint"?Number(r):r)}readVarString(){let[e,t]=this.readVarInt();if(t!==0)return a(t);let[r,n]=this.readBytes(e);if(n!==0)return a(n);let s=new TextDecoder().decode(r);return f(s)}readVarStrings(){let[e,t]=this.readVarInt();if(t!==0)return a(t);if(e<0||e>this.remaining())return a(14);let r=[];for(let n=0;n<e;n++){let[s,o]=this.readVarString();if(o!==0)return a(o);r.push(s)}return f(r)}readBytes(e){if(e<0)return a(10);if(this.pos+e>this.data.length)return a(23);let t=this.data.slice(this.pos,this.pos+e);return this.pos+=e,f(t)}readVarBytes(){let[e,t]=this.readVarInt();if(t!==0)return a(t);return this.readBytes(e)}readStruct(e){return e.decode(this)}readStructs(e){let t=[];while(!this.done()){let[r,n]=this.readStruct(e);if(n!==0)return a(n);t.push(r)}return f(t)}readBytesSeq(e){let t=[];while(!this.done()){let[r,n]=this.readBytes(e);if(n!==0)return a(n);t.push(r)}return f(t)}done(){return this.pos>=this.data.length}remaining(){return this.data.length-this.pos}readRest(){let e=this.data.subarray(this.pos);return this.pos=this.data.length,e}consumed(){return this.pos}}class q{parts=[];writeBigInt(e){let t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e,!1),this.parts.push(t)}writeDate(e){let t=e.getTime();return this.writeVarInt(t)}writeVarInt(e){let[t,r]=xa(e);if(r!==0)return r;return this.parts.push(t),0}writeVarString(e){let t=new TextEncoder().encode(e),r=this.writeVarInt(t.length);if(r!==0)return r;return this.writeBytes(t),0}writeVarStrings(e){let t=this.writeVarInt(e.length);if(t!==0)return t;for(let r of e){let n=this.writeVarString(r);if(n!==0)return n}return 0}prependBytes(e){this.parts.unshift(e.slice())}writeBytes(e){this.parts.push(e.slice())}writeVarBytes(e){let t=this.writeVarInt(e.length);if(t!==0)return t;return this.writeBytes(e),0}writeStruct(e,t){return e.encode(this,t)}writeStructs(e,t){for(let r of t){let n=this.writeStruct(e,r);if(n!==0)return n}return 0}writeBytesSeq(e){for(let t of e)this.writeBytes(t)}result(){let e=this.parts.reduce((n,s)=>n+s.length,0),t=new Uint8Array(e),r=0;for(let n of this.parts)t.set(n,r),r+=n.length;return t}wipe(){for(let e of this.parts)e.fill(0);this.parts.length=0}*scan(){for(let e of this.parts)yield e}}var ee=_(()=>{M();D()});function tr(e,t){if(e.byteLength!==t.byteLength)return!1;let r=0;for(let n=0;n<e.byteLength;n++){let s=e[n],o=t[n];if(s===void 0||o===void 0)return!1;r|=s^o}return r===0}function Ye(e){return Array.from(e).map((r)=>r.toString(16).padStart(2,"0")).join("")}function vs(e){if(e.length%2!==0)throw Error("Invalid hex string");let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=Number.parseInt(e.substr(r,2),16);return t}function Q(e,t){return tr(e,t)}function Ms(e){return V(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Us(e){let t=e.length%4===0?"":"=".repeat(4-e.length%4),r=e.replace(/-/g,"+").replace(/_/g,"/")+t;return Ee(r)}function ut(e,t){let r=new Uint8Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}var V,Ee;var ae=_(()=>{if(typeof Uint8Array.prototype.toBase64==="function")V=(e)=>e.toBase64();else V=(e)=>btoa(String.fromCharCode(...e));if(typeof Uint8Array.fromBase64==="function")Ee=(e)=>Uint8Array.fromBase64(e);else Ee=(e)=>Uint8Array.from(atob(e),(t)=>t.charCodeAt(0))});function nr(e,t){return e.label===t.label&&e.index===t.index}var Hs;var sr=_(()=>{D();M();Hs={encode(e,t){let r=e.writeVarString(t.label);if(r!==0)return r;let n=e.writeVarInt(t.index);if(n!==0)return n;return 0},decode(e){let[t,r]=e.readVarString();if(r!==0)return a(r);let[n,s]=e.readVarInt();if(s!==0)return a(s);return f({label:t,index:n})}}});var Je;var Ks=_(()=>{Je=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0});function or(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function Jr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ce(e,...t){if(!Jr(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function Zr(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Vs(e,t){ce(e);let r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}function en(e){if(typeof e!=="boolean")throw Error(`boolean expected, not ${e}`)}var Tt=()=>{};function Aa(e){if(typeof e!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ir(e){if(typeof e==="string")e=Aa(e);else if(Jr(e))e=ar(e);else throw Error("Uint8Array expected, got "+typeof e);return e}function Os(e,t){if(t==null||typeof t!=="object")throw Error("options must be defined");return Object.assign(e,t)}function Ls(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function tn(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw Error("invalid output length, expected "+e+", got: "+t.length);if(r&&!ka(t))throw Error("invalid output, must be aligned");return t}function ka(e){return e.byteOffset%4===0}function ar(e){return Uint8Array.from(e)}function Be(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Te=(e)=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),Ea,qs=(e,t)=>{function r(n,...s){if(ce(n),e.nonceLength!==void 0){let l=s[0];if(!l)throw Error("nonce / iv required");if(e.varSizeNonce)ce(l);else ce(l,e.nonceLength)}let o=e.tagLength;if(o&&s[1]!==void 0)ce(s[1]);let i=t(n,...s),c=(l,p)=>{if(p!==void 0){if(l!==2)throw Error("cipher output not supported");ce(p)}},u=!1;return{encrypt(l,p){if(u)throw Error("cannot encrypt() twice with same key + nonce");return u=!0,ce(l),c(i.encrypt.length,p),i.encrypt(l,p)},decrypt(l,p){if(ce(l),o&&l.length<o)throw Error("invalid ciphertext length: smaller than tagLength="+o);return c(i.decrypt.length,p),i.decrypt(l,p)}}}return Object.assign(r,e),r};var cr=_(()=>{Tt();/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */Ea=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ea)throw Error("Non little-endian hardware is not supported")});function Ht(e=32){if(Je&&typeof Je.getRandomValues==="function")return Je.getRandomValues(new Uint8Array(e));if(Je&&typeof Je.randomBytes==="function")return Je.randomBytes(e);throw Error("crypto.getRandomValues must be defined")}var Ns=_(()=>{Ks()});function B(e,t){return e<<t|e>>>32-t}function rn(e){return e.byteOffset%4===0}function Ca(e,t,r,n,s,o,i,c){let u=s.length,d=new Uint8Array(ur),l=Te(d),p=rn(s)&&rn(o),y=p?Te(s):_s,m=p?Te(o):_s;for(let h=0;h<u;i++){if(e(t,r,n,l,i,c),i>=Ws)throw Error("arx: counter overflow");let g=Math.min(ur,u-h);if(p&&g===ur){let S=h/4;if(h%4!==0)throw Error("arx: invalid block position");for(let b=0,E;b<Ua;b++)E=S+b,m[E]=y[E]^l[b];h+=ur;continue}for(let S=0,b;S<g;S++)b=h+S,o[b]=s[b]^d[S];h+=g}}function js(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:o,rounds:i}=Os({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=="function")throw Error("core must be a function");return or(s),or(i),en(o),en(r),(c,u,d,l,p=0)=>{ce(c),ce(u),ce(d);let y=d.length;if(l===void 0)l=new Uint8Array(y);if(ce(l),or(p),p<0||p>=Ws)throw Error("arx: counter overflow");if(l.length<y)throw Error(`arx: output (${l.length}) is shorter than data (${y})`);let m=[],h=c.length,g,S;if(h===32)m.push(g=ar(c)),S=Ma;else if(h===16&&r)g=new Uint8Array(32),g.set(c),g.set(c,16),S=va,m.push(g);else throw Error(`arx: invalid 32-byte key, got length=${h}`);if(!rn(u))m.push(u=ar(u));let b=Te(g);if(n){if(u.length!==24)throw Error("arx: extended nonce must be 24 bytes");n(S,b,Te(u.subarray(0,16)),b),u=u.subarray(16)}let E=16-s;if(E!==u.length)throw Error(`arx: nonce must be ${E} or 16 bytes`);if(E!==12){let x=new Uint8Array(12);x.set(u,o?0:12-u.length),u=x,m.push(u)}let P=Te(u);return Ca(e,S,b,P,d,l,p,i),Be(...m),l}}var Fs=(e)=>Uint8Array.from(e.split("").map((t)=>t.charCodeAt(0))),Da,Ba,va,Ma,ur=64,Ua=16,Ws=4294967295,_s;var Xs=_(()=>{Tt();cr();Da=Fs("expand 16-byte k"),Ba=Fs("expand 32-byte k"),va=Te(Da),Ma=Te(Ba);_s=new Uint32Array});class Gs{constructor(e){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,e=ir(e),ce(e,32);let t=de(e,0),r=de(e,2),n=de(e,4),s=de(e,6),o=de(e,8),i=de(e,10),c=de(e,12),u=de(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|n<<6)&7939,this.r[3]=(n>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|i<<2)&8191,this.r[7]=(i>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let d=0;d<8;d++)this.pad[d]=de(e,16+2*d)}process(e,t,r=!1){let n=r?0:2048,{h:s,r:o}=this,i=o[0],c=o[1],u=o[2],d=o[3],l=o[4],p=o[5],y=o[6],m=o[7],h=o[8],g=o[9],S=de(e,t+0),b=de(e,t+2),E=de(e,t+4),P=de(e,t+6),x=de(e,t+8),w=de(e,t+10),k=de(e,t+12),T=de(e,t+14),R=s[0]+(S&8191),H=s[1]+((S>>>13|b<<3)&8191),C=s[2]+((b>>>10|E<<6)&8191),K=s[3]+((E>>>7|P<<9)&8191),U=s[4]+((P>>>4|x<<12)&8191),I=s[5]+(x>>>1&8191),N=s[6]+((x>>>14|w<<2)&8191),O=s[7]+((w>>>11|k<<5)&8191),F=s[8]+((k>>>8|T<<8)&8191),W=s[9]+(T>>>5|n),v=0,Z=v+R*i+H*(5*g)+C*(5*h)+K*(5*m)+U*(5*y);v=Z>>>13,Z&=8191,Z+=I*(5*p)+N*(5*l)+O*(5*d)+F*(5*u)+W*(5*c),v+=Z>>>13,Z&=8191;let re=v+R*c+H*i+C*(5*g)+K*(5*h)+U*(5*m);v=re>>>13,re&=8191,re+=I*(5*y)+N*(5*p)+O*(5*l)+F*(5*d)+W*(5*u),v+=re>>>13,re&=8191;let se=v+R*u+H*c+C*i+K*(5*g)+U*(5*h);v=se>>>13,se&=8191,se+=I*(5*m)+N*(5*y)+O*(5*p)+F*(5*l)+W*(5*d),v+=se>>>13,se&=8191;let z=v+R*d+H*u+C*c+K*i+U*(5*g);v=z>>>13,z&=8191,z+=I*(5*h)+N*(5*m)+O*(5*y)+F*(5*p)+W*(5*l),v+=z>>>13,z&=8191;let Ce=v+R*l+H*d+C*u+K*c+U*i;v=Ce>>>13,Ce&=8191,Ce+=I*(5*g)+N*(5*h)+O*(5*m)+F*(5*y)+W*(5*p),v+=Ce>>>13,Ce&=8191;let nt=v+R*p+H*l+C*d+K*u+U*c;v=nt>>>13,nt&=8191,nt+=I*i+N*(5*g)+O*(5*h)+F*(5*m)+W*(5*y),v+=nt>>>13,nt&=8191;let st=v+R*y+H*p+C*l+K*d+U*u;v=st>>>13,st&=8191,st+=I*c+N*i+O*(5*g)+F*(5*h)+W*(5*m),v+=st>>>13,st&=8191;let ot=v+R*m+H*y+C*p+K*l+U*d;v=ot>>>13,ot&=8191,ot+=I*u+N*c+O*i+F*(5*g)+W*(5*h),v+=ot>>>13,ot&=8191;let it=v+R*h+H*m+C*y+K*p+U*l;v=it>>>13,it&=8191,it+=I*d+N*u+O*c+F*i+W*(5*g),v+=it>>>13,it&=8191;let at=v+R*g+H*h+C*m+K*y+U*p;v=at>>>13,at&=8191,at+=I*l+N*d+O*u+F*c+W*i,v+=at>>>13,at&=8191,v=(v<<2)+v|0,v=v+Z|0,Z=v&8191,v=v>>>13,re+=v,s[0]=Z,s[1]=re,s[2]=se,s[3]=z,s[4]=Ce,s[5]=nt,s[6]=st,s[7]=ot,s[8]=it,s[9]=at}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(let i=2;i<10;i++)e[i]+=n,n=e[i]>>>13,e[i]&=8191;e[0]+=n*5,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let i=1;i<10;i++)r[i]=e[i]+n,n=r[i]>>>13,r[i]&=8191;r[9]-=8192;let s=(n^1)-1;for(let i=0;i<10;i++)r[i]&=s;s=~s;for(let i=0;i<10;i++)e[i]=e[i]&s|r[i];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let i=1;i<8;i++)o=(e[i]+t[i]|0)+(o>>>16)|0,e[i]=o&65535;Be(r)}update(e){Zr(this);let{buffer:t,blockLen:r}=this;e=ir(e);let n=e.length;for(let s=0;s<n;){let o=Math.min(r-this.pos,n-s);if(o===r){for(;r<=n-s;s+=r)this.process(e,s);continue}if(t.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r)this.process(t,0,!1),this.pos=0}return this}destroy(){Be(this.h,this.r,this.buffer,this.pad)}digestInto(e){Zr(this),Vs(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:n}=this;if(n){t[n++]=1;for(;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=r[o]>>>0,e[s++]=r[o]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}function Ra(e){let t=(n,s)=>e(s).update(ir(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=(n)=>e(n),t}var de=(e,t)=>e[t++]&255|(e[t++]&255)<<8,nn;var Qs=_(()=>{Tt();cr();nn=Ra((e)=>new Gs(e))});function Ta(e,t,r,n,s,o=20){let i=e[0],c=t[0],u=t[1],d=t[2],l=t[3],p=e[1],y=r[0],m=r[1],h=s,g=0,S=e[2],b=t[4],E=t[5],P=t[6],x=t[7],w=e[3],k=i,T=c,R=u,H=d,C=l,K=p,U=y,I=m,N=h,O=g,F=S,W=b,v=E,Z=P,re=x,se=w;for(let Ce=0;Ce<o;Ce+=2)C^=B(k+v|0,7),N^=B(C+k|0,9),v^=B(N+C|0,13),k^=B(v+N|0,18),O^=B(K+T|0,7),Z^=B(O+K|0,9),T^=B(Z+O|0,13),K^=B(T+Z|0,18),re^=B(F+U|0,7),R^=B(re+F|0,9),U^=B(R+re|0,13),F^=B(U+R|0,18),H^=B(se+W|0,7),I^=B(H+se|0,9),W^=B(I+H|0,13),se^=B(W+I|0,18),T^=B(k+H|0,7),R^=B(T+k|0,9),H^=B(R+T|0,13),k^=B(H+R|0,18),U^=B(K+C|0,7),I^=B(U+K|0,9),C^=B(I+U|0,13),K^=B(C+I|0,18),W^=B(F+O|0,7),N^=B(W+F|0,9),O^=B(N+W|0,13),F^=B(O+N|0,18),v^=B(se+re|0,7),Z^=B(v+se|0,9),re^=B(Z+v|0,13),se^=B(re+Z|0,18);let z=0;n[z++]=i+k|0,n[z++]=c+T|0,n[z++]=u+R|0,n[z++]=d+H|0,n[z++]=l+C|0,n[z++]=p+K|0,n[z++]=y+U|0,n[z++]=m+I|0,n[z++]=h+N|0,n[z++]=g+O|0,n[z++]=S+F|0,n[z++]=b+W|0,n[z++]=E+v|0,n[z++]=P+Z|0,n[z++]=x+re|0,n[z++]=w+se|0}function Ha(e,t,r,n){let s=e[0],o=t[0],i=t[1],c=t[2],u=t[3],d=e[1],l=r[0],p=r[1],y=r[2],m=r[3],h=e[2],g=t[4],S=t[5],b=t[6],E=t[7],P=e[3];for(let w=0;w<20;w+=2)u^=B(s+S|0,7),y^=B(u+s|0,9),S^=B(y+u|0,13),s^=B(S+y|0,18),m^=B(d+o|0,7),b^=B(m+d|0,9),o^=B(b+m|0,13),d^=B(o+b|0,18),E^=B(h+l|0,7),i^=B(E+h|0,9),l^=B(i+E|0,13),h^=B(l+i|0,18),c^=B(P+g|0,7),p^=B(c+P|0,9),g^=B(p+c|0,13),P^=B(g+p|0,18),o^=B(s+c|0,7),i^=B(o+s|0,9),c^=B(i+o|0,13),s^=B(c+i|0,18),l^=B(d+u|0,7),p^=B(l+d|0,9),u^=B(p+l|0,13),d^=B(u+p|0,18),g^=B(h+m|0,7),y^=B(g+h|0,9),m^=B(y+g|0,13),h^=B(m+y|0,18),S^=B(P+E|0,7),b^=B(S+P|0,9),E^=B(b+S|0,13),P^=B(E+b|0,18);let x=0;n[x++]=s,n[x++]=d,n[x++]=h,n[x++]=P,n[x++]=l,n[x++]=p,n[x++]=y,n[x++]=m}var sn,on;var $s=_(()=>{Xs();Tt();Qs();cr();sn=js(Ta,{counterRight:!0,extendNonceFn:Ha}),on=qs({blockSize:64,nonceLength:24,tagLength:16},(e,t)=>({encrypt(r,n){n=tn(r.length+32,n,!1);let s=n.subarray(0,32),o=n.subarray(32);n.set(r,32),Be(s),sn(e,t,n,n);let i=nn(o,s);return n.set(i,16),Be(n.subarray(0,16),i),n.subarray(16)},decrypt(r,n){ce(r),n=tn(r.length+32,n,!1);let s=n.subarray(0,32),o=n.subarray(32,48),i=n.subarray(48);n.set(r,32),Be(s);let c=sn(e,t,s,s),u=nn(i,c);if(!Ls(o,u))throw Error("invalid tag");return sn(e,t,n.subarray(16),n.subarray(16)),Be(s,o,u),i}}))});function Ka(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Kt(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function Ze(e,...t){if(!Ka(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function Vt(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function dr(e,t){Ze(e);let r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}function zs(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function dt(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function lt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ot(e,t){return e<<32-t|e>>>t}function Js(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Va(e){for(let t=0;t<e.length;t++)e[t]=Js(e[t]);return e}function Oa(e){if(typeof e!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ft(e){if(typeof e==="string")e=Oa(e);return Ze(e),e}class an{}function eo(e){let t=(n,s)=>e(s).update(ft(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=(n)=>e(n),t}var Ys,Zs,me;var lr=_(()=>{/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ys=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();Zs=Ys?(e)=>e:(e)=>Js(e);me=Ys?(e)=>e:Va});var to;var ro=_(()=>{to=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});function cn(e,t=!1){if(t)return{h:Number(e&fr),l:Number(e>>no&fr)};return{h:Number(e>>no&fr)|0,l:Number(e&fr)|0}}var fr,no;var so=_(()=>{fr=BigInt(4294967295),no=BigInt(32)});function He(e,t,r,n,s){return e=e+t+s|0,n=Ot(n^e,16),r=r+n|0,t=Ot(t^r,12),{a:e,b:t,c:r,d:n}}function Ke(e,t,r,n,s){return e=e+t+s|0,n=Ot(n^e,8),r=r+n|0,t=Ot(t^r,7),{a:e,b:t,c:r,d:n}}var oo=_(()=>{lr()});function dn(e,t,r,n,s,o,i,c,u,d,l,p,y,m,h,g,S,b,E,P){let x=0;for(let w=0;w<n;w++)({a:s,b:u,c:y,d:S}=He(s,u,y,S,r[t+e[x++]])),{a:s,b:u,c:y,d:S}=Ke(s,u,y,S,r[t+e[x++]]),{a:o,b:d,c:m,d:b}=He(o,d,m,b,r[t+e[x++]]),{a:o,b:d,c:m,d:b}=Ke(o,d,m,b,r[t+e[x++]]),{a:i,b:l,c:h,d:E}=He(i,l,h,E,r[t+e[x++]]),{a:i,b:l,c:h,d:E}=Ke(i,l,h,E,r[t+e[x++]]),{a:c,b:p,c:g,d:P}=He(c,p,g,P,r[t+e[x++]]),{a:c,b:p,c:g,d:P}=Ke(c,p,g,P,r[t+e[x++]]),{a:s,b:d,c:h,d:P}=He(s,d,h,P,r[t+e[x++]]),{a:s,b:d,c:h,d:P}=Ke(s,d,h,P,r[t+e[x++]]),{a:o,b:l,c:g,d:S}=He(o,l,g,S,r[t+e[x++]]),{a:o,b:l,c:g,d:S}=Ke(o,l,g,S,r[t+e[x++]]),{a:i,b:p,c:y,d:b}=He(i,p,y,b,r[t+e[x++]]),{a:i,b:p,c:y,d:b}=Ke(i,p,y,b,r[t+e[x++]]),{a:c,b:u,c:m,d:E}=He(c,u,m,E,r[t+e[x++]]),{a:c,b:u,c:m,d:E}=Ke(c,u,m,E,r[t+e[x++]]);return{v0:s,v1:o,v2:i,v3:c,v4:u,v5:d,v6:l,v7:p,v8:y,v9:m,v10:h,v11:g,v12:S,v13:b,v14:E,v15:P}}var un;var io=_(()=>{oo();lr();un=class un extends an{constructor(e,t){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Kt(e),Kt(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=dt(this.buffer)}update(e){Vt(this),e=ft(e),Ze(e);let{blockLen:t,buffer:r,buffer32:n}=this,s=e.length,o=e.byteOffset,i=e.buffer;for(let c=0;c<s;){if(this.pos===t)me(n),this.compress(n,0,!1),me(n),this.pos=0;let u=Math.min(t-this.pos,s-c),d=o+c;if(u===t&&!(d%4)&&c+u<s){let l=new Uint32Array(i,d,Math.floor((s-c)/4));me(l);for(let p=0;c+t<s;p+=n.length,c+=t)this.length+=t,this.compress(l,p,!1);me(l);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){Vt(this),dr(e,this);let{pos:t,buffer32:r}=this;this.finished=!0,lt(this.buffer.subarray(t)),me(r),this.compress(r,0,!0),me(r);let n=dt(e);this.get().forEach((s,o)=>n[o]=Zs(s))}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){let{buffer:t,length:r,finished:n,destroyed:s,outputLen:o,pos:i}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(t),e.destroyed=s,e.finished=n,e.length=r,e.pos=i,e.outputLen=o,e}clone(){return this._cloneInto()}}});var ve,Ve,ao,ln,fn;var co=_(()=>{ro();so();io();lr();ve={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},Ve=to.slice(),ao=(()=>{let e=Array.from({length:16},(n,s)=>s),t=(n)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((s)=>n[s]),r=[];for(let n=0,s=e;n<7;n++,s=t(s))r.push(...s);return Uint8Array.from(r)})();ln=class ln extends un{constructor(e={},t=0){super(64,e.dkLen===void 0?32:e.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:r,context:n}=e,s=n!==void 0;if(r!==void 0){if(s)throw Error('Only "key" or "context" can be specified at same time');let o=ft(r).slice();Ze(o,32),this.IV=dt(o),me(this.IV),this.flags=t|ve.KEYED_HASH}else if(s){let o=ft(n),i=new ln({dkLen:32},ve.DERIVE_KEY_CONTEXT).update(o).digest();this.IV=dt(i),me(this.IV),this.flags=t|ve.DERIVE_KEY_MATERIAL}else this.IV=Ve.slice(),this.flags=t;this.state=this.IV.slice(),this.bufferOut=zs(this.bufferOut32)}get(){return[]}set(){}b2Compress(e,t,r,n=0){let{state:s,pos:o}=this,{h:i,l:c}=cn(BigInt(e),!0),{v0:u,v1:d,v2:l,v3:p,v4:y,v5:m,v6:h,v7:g,v8:S,v9:b,v10:E,v11:P,v12:x,v13:w,v14:k,v15:T}=dn(ao,n,r,7,s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],Ve[0],Ve[1],Ve[2],Ve[3],i,c,o,t);s[0]=u^S,s[1]=d^b,s[2]=l^E,s[3]=p^P,s[4]=y^x,s[5]=m^w,s[6]=h^k,s[7]=g^T}compress(e,t=0,r=!1){let n=this.flags;if(!this.chunkPos)n|=ve.CHUNK_START;if(this.chunkPos===15||r)n|=ve.CHUNK_END;if(!r)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,n,e,t),this.chunkPos+=1,this.chunkPos===16||r){let s=this.state;this.state=this.IV.slice();for(let o,i=this.chunksDone+1;r||!(i&1);i>>=1){if(!(o=this.stack.pop()))break;this.buffer32.set(o,0),this.buffer32.set(s,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|ve.PARENT,this.buffer32,0),s=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(s)}this.pos=0}_cloneInto(e){e=super._cloneInto(e);let{IV:t,flags:r,state:n,chunkPos:s,posOut:o,chunkOut:i,stack:c,chunksDone:u}=this;return e.state.set(n.slice()),e.stack=c.map((d)=>Uint32Array.from(d)),e.IV.set(t),e.flags=r,e.chunkPos=s,e.chunksDone=u,e.posOut=o,e.chunkOut=i,e.enableXOF=this.enableXOF,e.bufferOut32.set(this.bufferOut32),e}destroy(){this.destroyed=!0,lt(this.state,this.buffer32,this.IV,this.bufferOut32),lt(...this.stack)}b2CompressOut(){let{state:e,pos:t,flags:r,buffer32:n,bufferOut32:s}=this,{h:o,l:i}=cn(BigInt(this.chunkOut++));me(n);let{v0:c,v1:u,v2:d,v3:l,v4:p,v5:y,v6:m,v7:h,v8:g,v9:S,v10:b,v11:E,v12:P,v13:x,v14:w,v15:k}=dn(ao,0,n,7,e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],Ve[0],Ve[1],Ve[2],Ve[3],i,o,t,r);s[0]=c^g,s[1]=u^S,s[2]=d^b,s[3]=l^E,s[4]=p^P,s[5]=y^x,s[6]=m^w,s[7]=h^k,s[8]=e[0]^g,s[9]=e[1]^S,s[10]=e[2]^b,s[11]=e[3]^E,s[12]=e[4]^P,s[13]=e[5]^x,s[14]=e[6]^w,s[15]=e[7]^k,me(n),me(s),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,lt(this.buffer.subarray(this.pos));let e=this.flags|ve.ROOT;if(this.stack.length)e|=ve.PARENT,me(this.buffer32),this.compress(this.buffer32,0,!0),me(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else e|=(!this.chunkPos?ve.CHUNK_START:0)|ve.CHUNK_END;this.flags=e,this.b2CompressOut()}writeInto(e){Vt(this,!1),Ze(e),this.finish();let{blockLen:t,bufferOut:r}=this;for(let n=0,s=e.length;n<s;){if(this.posOut>=t)this.b2CompressOut();let o=Math.min(t-this.posOut,s-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(e)}xof(e){return Kt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(dr(e,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}};fn=eo((e)=>new ln(e))});function uo(e){if(e.byteLength!==La)return a(10);return f(e)}function fo(e){let t=0n;for(let r=e.length-1;r>=0;r--)t=t<<8n|BigInt(e[r]);return t}function Na(e){let t=new Uint8Array(32),r=(e%G+G)%G;for(let n=0;n<32;n++)t[n]=Number(r&0xffn),r>>=8n;return t}function _a(e){let t=e.slice();return t[31]&=127,fo(t)}function Fa(e){let t=e.slice();return t[0]&=248,t[31]&=127,t[31]|=64,t}function pr(e,t,r){let n=-e,s=(t^r)&n;return[t^s,r^s]}function Wa(e){let t=G-2n,r=(e%G+G)%G,n=1n;while(t>0n){if(t&1n)n=n*r%G;r=r*r%G,t>>=1n}return n}function pn(e,t){let r=Fa(e),n=_a(t),s=1n,o=0n,i=n,c=1n,u=0n,d=fo(r);for(let l=254;l>=0;l--){let p=d>>BigInt(l)&1n;u^=p,[s,i]=pr(u,s,i),[o,c]=pr(u,o,c),u=p;let y=(s+o)%G,m=y*y%G,h=(s-o+G)%G,g=h*h%G,S=(m-g+G)%G,b=(i+c)%G,P=(i-c+G)%G*y%G,x=b*h%G,w=(P+x)%G,k=(P-x+G)%G;i=w*w%G,c=n*k*k%G,s=m*g%G,o=S*(m+qa*S)%G}return[s,i]=pr(u,s,i),[o,c]=pr(u,o,c),r.fill(0),Na(s*Wa(o)%G)}function po(e){return pn(e,lo)}var La=32,Yd,G,qa=121665n,lo;var yo=_(()=>{D();M();Yd=Symbol("X25519Sk");G=(1n<<255n)-19n,lo=new Uint8Array(32);lo[0]=9});function mo(e){let t=new Uint8Array(yn.length+32);return t.set(yn),t.set(e.subarray(0,32),yn.length),t}function ho(e){let t=new Uint8Array(mn.length+32);return t.set(mn),t.set(e.subarray(0,32),mn.length),t}function go(e){return typeof e==="string"?new TextEncoder().encode(e):e}function Oe(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}async function ja(e){return Ht(e)}async function hn(){return Ht(32)}async function pt(e,t){let r=Ht(24),s=on(t,r).encrypt(e);return new Uint8Array([...r,...s])}async function et(e,t){let r=e.slice(0,24),n=e.slice(24);return on(t,r).decrypt(n)}async function yr(e){let t=e,r=mo(t),n=Oe(r),s;try{let d=await globalThis.crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]);s=await globalThis.crypto.subtle.exportKey("jwk",d)}finally{r.fill(0),new Uint8Array(n).fill(0)}if(typeof s.x!=="string")throw Error("Ed25519 JWK missing x");let o=s.x;s.d=void 0;let i=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:o},{name:"Ed25519"},!0,["verify"]),c=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",i)),u=new Uint8Array(64);return u.set(t,0),u.set(c,32),{keyType:"ed25519",privateKey:u,publicKey:c}}async function Xa(e){let t=e.subarray(0,32),r=mo(t),n=Oe(r);try{return await globalThis.crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!1,["sign"])}finally{r.fill(0),new Uint8Array(n).fill(0)}}async function Ga(e){return await globalThis.crypto.subtle.importKey("raw",Oe(e),{name:"Ed25519"},!1,["verify"])}async function gn(e,t){let r=go(e),n=await Xa(t),s=await globalThis.crypto.subtle.sign({name:"Ed25519"},n,Oe(r));return new Uint8Array(s)}async function Qa(e,t,r){let n=go(t);try{return await globalThis.crypto.subtle.verify({name:"Ed25519"},r,Oe(e),Oe(n))}catch{return!1}}async function Lt(e,t){if(t===void 0)return fn(e);return fn(e,t)}async function Sn(){let e=await Ht(32);e[0]&=248,e[31]&=127,e[31]|=64;let[t,r]=uo(e);if(r!==0||t===void 0)throw e.fill(0),Error("X25519 scalar brand failed");let n=po(t),s=ho(t),o=Oe(s);try{let i=await globalThis.crypto.subtle.importKey("pkcs8",o,{name:"X25519"},!0,["deriveBits"]),c=await globalThis.crypto.subtle.exportKey("jwk",i);if(typeof c.x!=="string")throw Error("X25519 JWK missing x");let u=Us(c.x);if(c.d=void 0,!Q(u,n))throw Error("X25519 WebCrypto pub != RFC 7748");return{priv:t,pub:n}}catch(i){throw t.fill(0),i}finally{s.fill(0),new Uint8Array(o).fill(0)}}async function So(e,t){let r=ho(e),n=Oe(r);try{let s=await globalThis.crypto.subtle.importKey("pkcs8",n,{name:"X25519"},!1,["deriveBits"]),o=await globalThis.crypto.subtle.importKey("raw",Oe(t),{name:"X25519"},!1,[]),i=await globalThis.crypto.subtle.deriveBits({name:"X25519",public:o},s,256);return new Uint8Array(i)}catch{return pn(e,t)}finally{r.fill(0),new Uint8Array(n).fill(0)}}function $a(e){return Object.freeze(e),e}var yn,mn,bo;var yt=_(()=>{Ns();$s();co();ae();D();yo();yn=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);mn=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);bo=$a({genRandomBytes:ja,gen256BitSecureRandomSeed:hn,encryptXSalsa20Poly1305Combined:pt,decryptXSalsa20Poly1305Combined:et,deriveEd25519KeyPair:yr,signEd25519:gn,importVerifyKey:Ga,checkSigEd25519:Qa,blake3:Lt})});function za(e,t){return e}function Io(e){return e}function Ne(e,t){if(e.byteLength!==oe)return a(10);return f(Io(e))}function _e(e){return Ne(e,te.HostRLM)}function Ya(e){if(e instanceof Uint8Array)return f(e);let t=new q,r=Hs.encode(t,e);if(r!==0)return a(r);return f(t.result())}async function wo(e,t){try{return f(await Lt(e,t))}catch{return a(29)}}async function Ja({parent:e,purpose:t}){let[r,n]=await wo(e,{context:t});if(n!==0)return a(n);return f(za(r,t))}async function Za({pdk:e,kdm:t}){let[r,n]=Ya(t);if(n!==0)return a(n);let[s,o]=await wo(r,{key:e});if(o!==0)return a(o);return f(Io(s))}async function he({parent:e,purpose:t,kdm:r}){let[n,s]=await Ja({parent:e,purpose:t});if(s!==0)return a(s);try{return await Za({pdk:n,kdm:r})}finally{n.fill(0)}}var te,ll,fl,j;var fe=_(()=>{ee();sr();D();M();yt();te={Identity:"diplomatic.identity.v1",Cipher:"diplomatic.cipher.v1",Bind:"diplomatic.bind.v1",BindTag:"diplomatic.bindtag.v1",Fingerprint:"diplomatic.fingerprint.v1",Pair:"diplomatic.qrpair.v1",BagKdm:"diplomatic.bagkdm.v1",RealmKey:"diplomatic.realmKey.v1",RealmID:"diplomatic.realmID.v1",HostRLM:"diplomatic.hostRLM.v1"},ll=Symbol("PurposeDerivedKey"),fl=Symbol("ChildKey"),j=Object.freeze({label:"",index:0})});function tt(e){if(e.byteLength!==Oo)return a(10);return f(e)}var Fp,Wp,Ae=32,Oo;var Wt=_(()=>{D();M();Fp=Symbol("MasterSeed"),Wp=Symbol("SealedMasterKey"),Oo=24+Ae+16});var Ur;var _n=_(()=>{D();M();Ur={encode(e,t){let r=e.writeVarString(t.handle);if(r!==0)return r;let n=e.writeVarString(t.label);if(n!==0)return n;return e.writeVarInt(t.idx??0)},decode(e){let[t,r]=e.readVarString();if(r!==0)return a(r);let[n,s]=e.readVarString();if(s!==0)return a(s);let[o,i]=e.readVarInt();if(i!==0)return a(i);return f({handle:t,label:n,idx:o})}}});var Fn;var li=_(()=>{D();M();_n();_n();Fn={encode(e,t){let r=e.writeVarInt(t.hosts.length);if(r!==0)return r;for(let n of t.hosts){let s=e.writeStruct(Ur,n);if(s!==0)return s}return 0},decode(e){let[t,r]=e.readVarInt();if(r!==0)return a(r);if(t===void 0||t<0)return a(10);let n=[];for(let s=0;s<t;s++){let[o,i]=e.readStruct(Ur);if(i!==0)return a(i);if(o===void 0)return a(14);n.push(o)}return f({hosts:n})}}});function fi(e){if(e.byteLength!==Et)return a(10);return f(e)}function pi(e){if(e.byteLength<Ic)return a(10);return f(e)}async function yi(e,t,r,n){if(t.byteLength!==Et)return a(10);let s;try{s=await So(e,t)}catch{return a(29)}try{if(s.byteLength!==Et||s.every((i)=>i===0))return a(10);let o=ut(r,n);try{let[i,c]=await he({parent:s,purpose:te.Pair,kdm:o});if(c!==0)return a(c);return f(i)}finally{o.fill(0)}}finally{s.fill(0)}}async function mi(e){let t;try{t=await Sn()}catch{return a(29)}try{let[r,n]=await yi(t.priv,e,e,t.pub);if(n!==0)return a(n);return f({key:r,pub:t.pub})}finally{t.priv.fill(0)}}function hi(e){for(let t of Object.getOwnPropertyNames(e)){if(wc.has(t))continue;let r=Object.getOwnPropertyDescriptor(e,t);if(r===void 0||typeof r.value!=="function")continue;Object.defineProperty(e,t,{value:r.value,writable:!1,configurable:!1})}}class At{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(){let e;try{let t=await Sn();e=t.priv;let[r,n]=fi(t.pub);if(n!==0)return a(n);let s=new At(e,r);return e=void 0,f(s)}catch{return a(29)}finally{e?.fill(0)}}wipe(){this.#e.fill(0)}dhkeReq(){let e=this.#t.slice(),[t,r]=fi(e);if(r!==0)return a(r);return f(t)}async finish(e){let t=e.subarray(0,Et),r=e.subarray(Et),[n,s]=await yi(this.#e,t,this.#t,t);if(s!==0)return a(s);let o;try{try{o=await et(r,n)}catch{return a(20)}let{fromSeedHosts:i}=await Promise.resolve().then(() => ($t(),Si)),c=i(o);if(c[1]===0)this.wipe();return c}finally{n.fill(0),o?.fill(0)}}}var Et=32,Ic,Kh,Vh,wc;var gi=_(()=>{ae();D();M();fe();yt();Ic=Et+24+16,Kh=Symbol("DHKEReq"),Vh=Symbol("DHKEResp");wc=new Set(["constructor","prototype","length","name"]);hi(At);hi(At.prototype)});function Me(e){let t=new Uint8Array(e);if(e>0)crypto.getRandomValues(t);return t}function Ac(e){return e.trim().toLowerCase().replace(/\.$/,"")||"localhost"}function Ue(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function Tr(e){if(e instanceof ArrayBuffer)return new Uint8Array(e).slice();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice()}function je(e){if(e?.rpId!==void 0)return f(e.rpId);if(typeof location>"u")return a(9);return f(Ac(location.hostname))}function De(e){if(e instanceof Error){bi=e.message===""?e.name:`${e.name}: ${e.message}`;return}bi=String(e)}function Hr(e){if(!(e instanceof Error))return!1;return e.name==="NotAllowedError"&&e.message.toLowerCase().includes("does not have focus")}function Ii(){if(typeof document>"u")return!0;return document.visibilityState!=="hidden"}function kt(){if(typeof globalThis.focus!=="function")return;try{globalThis.focus()}catch{}}function Kr(e=2500){if(Ii())return kt(),Promise.resolve();return new Promise((t)=>{let r=()=>{clearTimeout(s),document.removeEventListener("visibilitychange",n),kt(),t()},n=()=>{if(Ii())r()},s=setTimeout(r,e);document.addEventListener("visibilitychange",n),n()})}async function Vr(e){await Kr();try{return await navigator.credentials.create(e)}catch(t){if(!Hr(t))throw t;return kt(),await navigator.credentials.create(e)}}async function Or(e){await Kr();try{return await navigator.credentials.get(e)}catch(t){if(!Hr(t))throw t;return kt(),await navigator.credentials.get(e)}}function Xe(){if(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")return 24;return 0}function Ge(e){if(e===null||e.type!==ke||!("rawId"in e)||typeof e.getClientExtensionResults!=="function")return a(27);return f(e)}function jn(e){if(e==="platform"||e==="cross-platform")return e;return}function xi(e){if(/iPhone|iPad|iPod/i.test(e))return"ios";if(/Android/i.test(e))return"android";if(/Mac OS X|Macintosh/i.test(e))return"macos";if(/Windows/i.test(e))return"windows";if(/Linux/i.test(e))return"linux";return"other"}function Xn(e){let t=e.response;if(!("getTransports"in t))return;let r=t.getTransports;if(typeof r!=="function")return;let n=r.call(t);if(!Array.isArray(n))return;let s=[];for(let o of n)if(typeof o==="string"&&o.length>0)s.push(o);return s.length===0?void 0:s}function Pi(e){let t=e.response;if(!("getAuthenticatorData"in t))return;let r=t.getAuthenticatorData;if(typeof r!=="function")return;let n=r.call(t);if(!(n instanceof ArrayBuffer))return;let s=new Uint8Array(n);if(s.byteLength<Wn+wi)return;let o=s[kc];if(o===void 0||(o&Dc)===0)return;return s.slice(Wn,Wn+wi)}var We=32,Cr="DIPLOMATIC",ke="public-key",xc=-7,Pc=-8,Ec=-257,Rr,bi="",kc=32,Dc=64,Wn=37,wi=16;var Dt=_(()=>{D();M();Rr=[{type:ke,alg:xc},{type:ke,alg:Pc},{type:ke,alg:Ec}]});async function Ei(e){let t=Xe();if(t!==0)return a(t);let[r,n]=je(e);if(n!==0)return a(n);if(r===void 0)return a(9);let s=e?.userName??e?.rpName??r,o={residentKey:"required",requireResidentKey:!0,userVerification:"required"};if(e?.authenticatorAttachment!==void 0)o.authenticatorAttachment=e.authenticatorAttachment;let i={largeBlob:{support:"required"}},c;try{c=await Vr({publicKey:{challenge:Me(We),rp:{id:r,name:e?.rpName??Cr},user:{id:Me(16),name:s,displayName:s},pubKeyCredParams:Rr,authenticatorSelection:o,extensions:i,...e?.hints!==void 0?{hints:e.hints}:{}}})}catch(p){return De(p),a(30)}let[u,d]=Ge(c);if(d!==0)return a(d);if(u===void 0)return a(27);if(u.getClientExtensionResults().largeBlob?.supported!==!0)return a(30);return f(new Uint8Array(u.rawId))}async function Gn(e,t,r,n){let s={challenge:Me(We),rpId:e,userVerification:"preferred"};if(t?.hints!==void 0)s.hints=t.hints;if(r!==void 0)s.allowCredentials=[{type:ke,id:Ue(r)}];if(n!==void 0)s.extensions=n;let o;try{o=await Or({publicKey:s})}catch(u){return De(u),a(30)}let[i,c]=Ge(o);if(c!==0)return a(c);if(i===void 0)return a(27);return f(i)}async function Ai(e,t){let r=Xe();if(r!==0)return a(r);let[n,s]=je(t);if(s!==0)return a(s);if(n===void 0)return a(9);let o=e;if(o===void 0){let[p,y]=await Gn(n,t);if(y!==0&&t?.hints!==void 0)[p,y]=await Gn(n,{rpId:t.rpId,rpName:t.rpName});if(y!==0)return a(y);if(p===void 0)return a(27);o=new Uint8Array(p.rawId)}let[i,c]=await Gn(n,t,o,{largeBlob:{read:!0}});if(c!==0)return a(c);if(i===void 0)return a(27);let d=i.getClientExtensionResults().largeBlob;if(d===void 0||d.blob===void 0)return a(7);let l=Tr(d.blob);if(l.byteLength===0)return a(7);return f({blob:l,credId:new Uint8Array(i.rawId)})}var Qn=_(()=>{D();M();Dt()});var Lr="";function vc(){if(typeof Lr!=="string"||Lr.length===0)throw Error("[DIPLOMATIC] worker source not embedded; run pkg build before spawn");return atob(Lr)}function Mc(){if(qr!==void 0)return qr;let e=new Blob([vc()],{type:"text/javascript"});return qr=URL.createObjectURL(e),qr}function ki(){if(Nr===void 0)throw Error("[DIPLOMATIC] Worker API unavailable; cannot spawn sync worker");return new Nr(Mc(),{type:"module"})}function Di(e,t,r){if($n===void 0)throw Error("[DIPLOMATIC] Worker API unavailable; cannot post to sync worker");if(r!==void 0&&r.length>0)$n.call(e,t,{transfer:r});else $n.call(e,t)}var Nr,$n,qr;var Bi=_(()=>{Nr=typeof globalThis.Worker==="function"?globalThis.Worker:void 0,$n=Nr===void 0?void 0:Nr.prototype.postMessage});async function vi(e){if(e?.credId!==void 0)return f(e.credId);return Ei(e)}async function zn(e,t,r){let n=Xe();if(n!==0)return n;let[s,o]=je(r);if(o!==0)return o;if(s===void 0)return 9;await Kr();let i=new Uint8Array(t.byteLength);i.set(t);let c={largeBlob:{write:i.buffer}},u={publicKey:{challenge:Me(We),rpId:s,allowCredentials:[{type:ke,id:Ue(e)}],userVerification:"required",extensions:c,...r?.hints!==void 0?{hints:r.hints}:{}}},d;try{try{d=await navigator.credentials.get(u)}catch(m){if(!Hr(m))return De(m),30;kt();try{d=await navigator.credentials.get(u)}catch(h){return De(h),30}}}catch(m){return De(m),30}finally{i.fill(0)}let[l,p]=Ge(d);if(p!==0)return p;if(l===void 0)return 27;if(l.getClientExtensionResults().largeBlob?.written!==!0)return 30;return 0}function Mi(e,t){return zn(e,new Uint8Array(Ae),t)}var Ui=_(()=>{D();Wt();M();Dt();Qn()});var Yn,zt="diplomatic-prf";var Jn=_(()=>{Dt();Yn=new TextEncoder().encode("diplomatic.prf.v1")});function Uc(e){if(e===void 0)return[];if(e instanceof Uint8Array)return[e];return e.filter((t)=>t.byteLength>0)}function Cc(e){if(!(e instanceof Error))return!1;return e.name==="NotSupportedError"||e.name==="TypeError"}function Ci(e){if(e===void 0)return;let t=Tr(e);if(t.byteLength<Zn){t.fill(0);return}if(t.byteLength===Zn)return t;let r=t.slice(0,Zn);return t.fill(0),r}async function Rc(e){let t=Xe();if(t!==0)return a(t);let[r,n]=je(e);if(n!==0)return a(n);let s=e?.userName??zt,o=e?.displayName??s,i=Me(16),c=e?.authenticatorAttachment==="cross-platform",u={residentKey:c?"discouraged":"required",requireResidentKey:!c,userVerification:c?"preferred":"required"};if(e?.authenticatorAttachment!==void 0)u.authenticatorAttachment=e.authenticatorAttachment;let d={challenge:Me(We),rp:{id:r,name:e?.rpName??Cr},user:{id:i,name:s,displayName:o},pubKeyCredParams:Rr,authenticatorSelection:u,...e?.hints!==void 0?{hints:e.hints}:{},...e?.excludeCredentials!==void 0&&e.excludeCredentials.length>0?{excludeCredentials:e.excludeCredentials.map((E)=>({type:ke,id:Ue(E)}))}:{}},l=e?.salt!==void 0?Ue(e.salt):void 0,p=(E)=>Vr({publicKey:{...d,extensions:E&&l!==void 0?{prf:{eval:{first:l}}}:{prf:{}}}}),y;try{y=await p(l!==void 0)}catch(E){if(l===void 0||!Cc(E))return De(E),a(30);try{y=await p(!1)}catch(P){return De(P),a(30)}}let[m,h]=Ge(y);if(h!==0)return a(h);let g=m.getClientExtensionResults(),S=Ci(g.prf?.results?.first),b=g.prf?.enabled===!0||S!==void 0;if(c&&S!==void 0)S.fill(0);return f({credId:new Uint8Array(m.rawId),userId:new Uint8Array(i),prfEnabled:b,prf:c?void 0:S,attachment:jn(m.authenticatorAttachment),transports:Xn(m),aaguid:Pi(m)})}async function Ri(e){let t=Xe();if(t!==0)return a(t);let[r,n]=je(e);if(n!==0)return a(n);let s=e?.salt??Yn,i={eval:{first:Ue(s)}},c=e?.salts;if(c!==void 0&&c.length>0){let g={};for(let S of c){if(S.credId.byteLength===0)continue;g[Ms(S.credId)]={first:Ue(S.salt)}}i.evalByCredential=g}let u={challenge:Me(We),rpId:r,userVerification:"preferred",extensions:{prf:i}};if(e?.hints!==void 0)u.hints=e.hints;let d=Uc(e?.credId);if(d.length>0)u.allowCredentials=d.map((g)=>({type:ke,id:Ue(g)}));let l;try{l=await Or({publicKey:u})}catch(g){return De(g),a(30)}let[p,y]=Ge(l);if(y!==0)return a(y);let m=p.getClientExtensionResults().prf?.results;if(m?.first===void 0)return a(7);let h=Ci(m.first);if(h===void 0)return a(27);return f({prf:h,credId:new Uint8Array(p.rawId),attachment:jn(p.authenticatorAttachment),transports:Xn(p)})}async function Ti(e){let t=e?.salt??Yn,r=e?.credId,n=r,s=e?.createCredIfNeeded===!0&&(r===void 0||!(r instanceof Uint8Array)&&r.length===0),o,i;if(s){let[l,p]=await Rc({rpId:e?.rpId,rpName:e?.rpName,userName:e?.userName??zt,displayName:e?.displayName,authenticatorAttachment:e?.authenticatorAttachment,hints:e?.hints,excludeCredentials:e?.excludeCredentials,salt:t});if(p!==0)return a(p);if(!l.prfEnabled)return a(30);n=l.credId,o=l,i=l.prf}let c=(l,p,y,m)=>f({prf:l,salt:t.slice(),credId:p.slice(),userId:o?.userId===void 0?void 0:o.userId.slice(),attachment:y??o?.attachment,transports:m??o?.transports,aaguid:o?.aaguid===void 0?void 0:o.aaguid.slice()});if(i!==void 0&&o!==void 0)return c(i,o.credId,o.attachment,o.transports);let[u,d]=await Ri({rpId:e?.rpId,rpName:e?.rpName,credId:n,salt:t,hints:e?.hints});if(d!==0)return a(d);return c(u.prf,u.credId,u.attachment,u.transports)}async function Hi(e,t){let r=[],n=[],s=!1;for(let d of e){if(d.credId.byteLength===0)continue;r.push(d.credId);let l=d.salt??t.salt;if(!Q(l,t.salt))s=!0;n.push({credId:d.credId,salt:l})}let[o,i]=await Ri({rpId:t.rpId,rpName:t.rpName,hints:t.hints,credId:r.length>0?r:void 0,salt:t.salt,salts:s?n:void 0});if(i!==0)return a(i);let c=e.find((d)=>Q(d.credId,o.credId)),u=c===void 0?e:[c,...e.filter((d)=>d!==c)];return f({prf:o.prf,credId:o.credId.slice(),order:u})}var Zn=32;var Ki=_(()=>{ae();D();M();Dt();Jn()});async function Vi(e,t){return he({parent:e,purpose:te.RealmKey,kdm:t})}async function Oi(e,t){return he({parent:e,purpose:te.RealmID,kdm:t})}async function Li(e,t){return he({parent:e,purpose:te.HostRLM,kdm:t})}var qi=_(()=>{fe()});function Ni(e){return e}class Bt{publicKey;idnt;realm;rlm;idKDM;realmKDM;constructor(e,t,r,n,s,o){this.publicKey=e;this.idnt=t;this.realm=r;this.rlm=n;this.idKDM=s;this.realmKDM=o}static async init(e,t,r,n,s){try{let o=await yr(Ni(e)),i=o.publicKey;o.privateKey.fill(0);let c=Object.freeze({...n}),u=Object.freeze({...s}),d=new Bt(i,e,t,r,c,u);return f(d)}catch{return e.fill(0),t.fill(0),r.fill(0),a(29)}}async sign(e){let t;try{t=await yr(Ni(this.idnt))}catch{return a(29)}try{return f(await gn(e,t.privateKey))}catch{return a(29)}finally{t.privateKey.fill(0)}}async bagKDM(e){let[t,r]=await he({parent:this.idnt,purpose:te.BagKdm,kdm:e});if(r!==0)return a(r);try{return f(t.slice(0,Le))}finally{t.fill(0)}}async encrypt(e,t){let[r,n]=await this.#e(e.slice());if(n!==0)return a(n);try{return f(await pt(t,r))}catch{return a(29)}finally{r.fill(0)}}async decrypt(e,t){let[r,n]=await this.#e(e.slice());if(n!==0)return a(n);try{return f(await et(t,r))}catch{return a(20)}finally{r.fill(0)}}async#e(e){return he({parent:this.realm,purpose:te.Cipher,kdm:e})}}function _i(e){for(let t of Object.getOwnPropertyNames(e)){if(Tc.has(t))continue;let r=Object.getOwnPropertyDescriptor(e,t);if(r===void 0||typeof r.value!=="function")continue;Object.defineProperty(e,t,{value:r.value,writable:!1,configurable:!1})}}var Tc;var Fi=_(()=>{D();M();fe();yt();Tc=new Set(["constructor","prototype","length","name"]);_i(Bt);_i(Bt.prototype)});var Si={};wa(Si,{Enclave:()=>pe,MUSEC_MIN_LEN:()=>Fr,asMasterSeed:()=>_r,fromSeedHosts:()=>ji});function ji(e){if(e.byteLength===0||e.every((c)=>c===0))return a(22);if(e.byteLength<Ae+1)return a(14);let t=e.subarray(0,Ae);if(t.every((c)=>c===0))return a(22);let r=new L(e.subarray(Ae)),[n,s]=r.readStruct(Fn);if(s!==0)return a(s);if(n===void 0)return a(14);if(!r.done())return a(14);let[o,i]=pe.fromBytes(t);if(i!==0)return a(i);return f({enclave:o,hosts:n.hosts.map((c)=>({...c}))})}function _r(e){if(e.byteLength!==Ae)return a(10);return[e,0]}async function Wi(e){if(e.byteLength<Kc)return a(10);let t=te.Bind;return he({parent:e,purpose:t,kdm:j})}class Qe{#e;constructor(e){this.#e=e}static async mix(e){let t,r,n;try{if(e.byteLength<Fr)return a(10);t=await hn(),r=new Uint8Array(t.byteLength+e.byteLength),r.set(t,0),r.set(e,t.byteLength),n=await Lt(r);let[s,o]=_r(n);if(o!==0)return a(o);let i=new Qe(s);return n=void 0,f(i)}finally{t?.fill(0),r?.fill(0),e.fill(0),n?.fill(0)}}static importSeed(e){let[t,r]=_r(e);if(r!==0)return a(r);let[n,s]=_r(t.slice());if(s!==0)return a(s);return f(new Qe(n))}static async unseal(e,t){let[,r]=tt(e);if(r!==0)return a(r);let[n,s]=await Wi(t);if(s!==0)return a(s);let o;try{try{o=await et(e,n)}catch{return a(20)}return Qe.importSeed(o)}finally{n.fill(0),o?.fill(0)}}async idnt(e){let t=te.Identity;return he({parent:this.#e,purpose:t,kdm:e})}async realmKey(e){return Vi(this.#e,e)}async realmID(e){return Oi(this.#e,e)}async fingerprint(e){let t=te.Fingerprint;return await he({parent:this.#e,purpose:t,kdm:e})}async bindTag(e){let t=te.BindTag;return await he({parent:this.#e,purpose:t,kdm:e})}async seal(e){let[t,r]=await Wi(e);if(r!==0)return a(r);try{let n=await pt(this.#e,t);return tt(n)}catch{return a(12)}finally{t.fill(0)}}async sealSeedHosts(e,t){let[r,n]=this.#t(t);if(n!==0)return a(n);try{return f(await pt(r,e))}catch{return a(12)}finally{r.fill(0)}}#t(e){let t=new q,r=t.writeStruct(Fn,{hosts:e.map((o)=>({handle:o.handle,label:o.label,idx:o.idx??0}))});if(r!==0)return a(r);let n=t.result(),s=new Uint8Array(Ae+n.byteLength);return s.set(this.#e,0),s.set(n,Ae),[s,0]}async persistToLargeBlob(e,t){let[r,n]=await vi(t);if(n!==0)return a(n);let[s,o]=this.#t(e);if(o!==0)return a(o);try{let i=await zn(r,s,t);if(i!==0)return a(i);return f(r)}finally{s.fill(0)}}async dumpToTTY(){return 21}copyForWorker(){return this.#e.slice()}}class pe{#e;constructor(e){this.#e=e}static async fromRandom(e){try{let[t,r]=await Qe.mix(e);if(r!==0)return a(r);return f(new pe(t))}finally{e.fill(0)}}static fromBytes(e){let[t,r]=Qe.importSeed(e);if(r!==0)return a(r);return f(new pe(t))}async sealWithPasskey(e){let[t,r]=await Ti(e);if(r!==0)return a(r);try{let[n,s]=await this.#e.seal(t.prf);if(s!==0)return a(s);return f({sealedMaster:n,salt:t.salt,credId:t.credId,userId:t.userId,attachment:t.attachment,transports:t.transports,aaguid:t.aaguid})}finally{t.prf.fill(0)}}async bind(e,t){if(t!==void 0)for(let i of t){if(i.tag.byteLength!==Hc)return a(10);let[c,u]=await this.#e.bindTag(i.credId);if(u!==0)return a(u);try{if(!tr(c,i.tag))return a(10)}finally{c.fill(0)}}let[r,n]=await this.sealWithPasskey(e);if(n!==0)return a(n);let[s,o]=await this.#e.bindTag(r.credId);if(o!==0)return a(o);return f({...r,tag:s})}static async unsealWithPasskey(e,t){if(e.length===0)return a(22);let[r,n]=await Hi(e,t);if(n!==0)return a(n);try{for(let s of r.order){let[o,i]=await Qe.unseal(s.sealedMaster,r.prf);if(i===0)return f({enclave:new pe(o),credId:r.credId})}return a(20)}finally{r.prf.fill(0)}}async sealWithIKM(e){try{return await this.#e.seal(e)}finally{e.fill(0)}}static async unsealWithIKM(e,t){try{let[r,n]=await Qe.unseal(e,t);if(n!==0)return a(n);return f(new pe(r))}finally{t.fill(0)}}async persistToLargeBlob(e=[],t){return this.#e.persistToLargeBlob(e,t)}static async fromLargeBlob(e){let[t,r]=await Ai(e?.credId,e);if(r!==0)return a(r);try{let[n,s]=ji(t.blob);if(s!==0)return a(s);return f({...n,credId:t.credId})}finally{t.blob.fill(0)}}static clearLargeBlob(e,t){return Mi(e,t)}async dumpToTTY(){return this.#e.dumpToTTY()}static pairRequest(){return At.create()}async pairAccept(e,t,r){if(r.userControlsBothSidesOfPair!==!0)return a(10);let[n,s]=await mi(e);if(s!==0)return a(s);try{let[o,i]=await this.#e.sealSeedHosts(n.key,t);if(i!==0)return a(i);return pi(ut(n.pub,o))}finally{n.key.fill(0)}}spawnSyncWorker(e){let t=ki(),r=this.#e.copyForWorker();return Di(t,{id:e.id,op:"setSeed",seed:r,persist:e.persist},[r.buffer]),t}async bagman(e,t){let[r,n]=await this.#e.idnt(e);if(n!==0)return a(n);let[s,o]=await this.#e.realmKey(t);if(o!==0)return r.fill(0),a(o);let[i,c]=await this.#e.realmID(t);if(c!==0)return r.fill(0),s.fill(0),a(c);try{let[u,d]=await Li(i,e);if(d!==0)return r.fill(0),s.fill(0),a(d);return Bt.init(r,s,u,e,t)}finally{i.fill(0)}}async fingerprint(e=j){return this.#e.fingerprint(e)}}function Xi(e){for(let t of Object.getOwnPropertyNames(e)){if(Vc.has(t))continue;let r=Object.getOwnPropertyDescriptor(e,t);if(r===void 0||typeof r.value!=="function")continue;Object.defineProperty(e,t,{value:r.value,writable:!1,configurable:!1})}}var Hc=32,Kc=16,Fr=32,Vc;var $t=_(()=>{ae();ee();li();D();Wt();M();fe();yt();gi();Qn();Bi();Ui();Ki();qi();Fi();Vc=new Set(["constructor","prototype","length","name"]);Xi(pe);Xi(pe.prototype)});D();function Bs(e){if(!e||typeof e!=="object")return!1;if(!("op"in e)||!("id"in e))return!1;return typeof e.op==="string"&&typeof e.id==="number"}class Ut{listeners=new Map;addEventListener(e,t){let r=this.listeners.get(e);if(!r)r=new Set,this.listeners.set(e,r);return r.add(t),()=>{this.removeEventListener(e,t)}}removeEventListener(e,t){let r=this.listeners.get(e);if(r){if(r.delete(t),r.size===0)this.listeners.delete(e)}}emit(e,t){let r=this.listeners.get(e);if(r){let n=Array.from(r);for(let s of n)s(t)}}emitAll(e){let t=Array.from(this.listeners.keys());for(let r of t)this.emit(r,e)}}class ze{getter;static eventName="update";emitter;constructor(e){this.getter=e;this.emitter=new Ut}get=()=>this.getter();async emit(){let e=await this.getter();queueMicrotask(()=>this.emitter.emit(ze.eventName,e))}listen(e){return this.emitter.addEventListener(ze.eventName,e),()=>{this.emitter.removeEventListener(ze.eventName,e)}}}ee();D();M();async function Qr(e,t){let r=new q,n=r.writeDate(t);if(n!==0)return a(n);let s=r.result(),[o,i]=await e.sign(s);if(i!==0)return a(i);return f({pubKey:e.publicKey,sig:o,timestamp:t})}async function qe(e,t,r){let n=r.now().getTime(),s=e.timestamp.getTime();if(Math.abs(n-s)>ks)return 4;let i=new q;i.writeDate(e.timestamp);let c=i.result(),u;try{u=await t.importVerifyKey(e.pubKey)}catch{return 29}if(!await t.checkSigEd25519(e.sig,c,u))return 3;return 0}ee();ee();D();ee();D();M();var ie={encode(e,t){let r=e.writeVarBytes(t.id);if(r!==0)return r;let n=e.writeDate(t.ts);if(n!==0)return n;return 0},decode(e){let[t,r]=e.readVarBytes();if(r!==0)return a(r);let[n,s]=e.readDate();if(s!==0)return a(s);return f({id:t,ts:n})}};function ct(e){let t=new q,r=t.writeStruct(ie,e);if(r!==0)return a(r);let n=t.result();return f(n)}M();var Ie={encode(e,t){let r=e.writeVarString(t.typ??"");if(r!==0)return r;let n=e.writeVarBytes(t.eid);if(n!==0)return n;let s=e.writeVarInt(t.off);if(s!==0)return s;let o=e.writeVarInt(t.ctr);if(o!==0)return o;let i=e.writeVarInt(t.len);if(i!==0)return i;if(t.hsh)e.writeBytes(t.hsh);return 0},decode(e){let[t,r]=e.readVarString();if(r!==0)return a(r);let[n,s]=e.readVarBytes();if(s!==0)return a(s);let o=new L(n),[,i]=ie.decode(o);if(i!==0)return a(i);let[c,u]=e.readVarInt();if(u!==0)return a(u);let[d,l]=e.readVarInt();if(l!==0)return a(l);let[p,y]=e.readVarInt();if(y!==0)return a(y);let m;if(p>0){let[h,g]=e.readBytes(er);if(g!==0)return a(g);m=h}return f({typ:t,eid:n,off:c,ctr:d,len:p,hsh:m})}};D();ae();M();function rr(e,t){return ut(e,t)}function Cs(e,t,r){if(e.rlm.byteLength!==oe)return Promise.resolve(!1);return r.checkSigEd25519(e.sig,rr(e.rlm,e.headCph),t)}async function Rs(e,t,r){let n;if(e.bod&&e.len>0)n=await r.blake3(e.bod);let s=new q,o=Ie.encode(s,{...e,hsh:n});if(o!==0)return a(o);let i=s.result(),[c,u]=await t.bagKDM(i);if(u!==0)return a(u);let d=t.rlm,[l,p]=await t.encrypt(c,i);if(p!==0)return a(p);let y=new Uint8Array(0);if(e.bod){let[S,b]=await t.encrypt(c,e.bod);if(b!==0)return a(b);y=S}let m=rr(d,l),[h,g]=await t.sign(m);if(g!==0)return a(g);return f({rlm:d,sig:h,kdm:c,headCph:l,bodyCph:y})}async function $r(e,t,r,n,s){let o=new L(e),[i,c]=Ie.decode(o);if(c!==0)return a(14);let u;if(t&&t.length>0){let[y,m]=await r.decrypt(t);if(m!==0)return a(m);u=y}let d=i.hsh&&u===void 0,l=i.hsh===void 0&&u!==void 0;if(d||l)return a(19);if(i.hsh&&u){let y=await n.blake3(u);if(!Q(y,i.hsh))return a(19)}let p=s??await n.blake3(e);return f({msgHead:i,bod:u,headHash:p})}class zr{now(){return new Date}}function Ts(e,t,r,n){let s=t.getTime()-e.getTime(),o=r.getTime()-n.getTime();return(s+o)/2}ee();sr();D();M();D();M();var Rt={encode(e,t){if(e.writeVarInt(t.quota),t.quota>0){if(t.usage===void 0)return 9;e.writeVarInt(t.usage)}return 0},decode(e){let[t,r]=e.readVarInt();if(r!==0)return a(r);let n;if(t>0){let[s,o]=e.readVarInt();if(o!==0)return a(o);n=s}return f({quota:t,usage:n})}};var Yr={encode(e,t){e.writeBytes(new Uint8Array([t.status]));let r=e.writeDate(t.timeRcvd);if(r!==0)return r;let n=e.writeDate(t.timeSent);if(n!==0)return n;let s=e.writeVarInt(t.subscription.term);if(s!==0)return s;let o=e.writeVarInt(t.subscription.elapsed);if(o!==0)return o;let i=e.writeStruct(Rt,t.subscription.stat);if(i!==0)return i;let c=e.writeStruct(Rt,t.subscription.dyn);if(c!==0)return c;return 0},decode(e){let[t,r]=e.readBytes(1);if(r!==0)return a(r);let n=t[0],[s,o]=e.readDate();if(o!==0)return a(o);let[i,c]=e.readDate();if(c!==0)return a(c);let[u,d]=e.readVarInt();if(d!==0)return a(d);let[l,p]=e.readVarInt();if(p!==0)return a(p);let[y,m]=e.readStruct(Rt);if(m!==0)return a(m);let[h,g]=e.readStruct(Rt);if(g!==0)return a(g);return f({status:n,timeRcvd:s,timeSent:i,subscription:{term:u,elapsed:l,stat:y,dyn:h}})}};D();fe();ee();D();D();D();M();var bn={encode(e,t){let r=e.writeVarBytes(t.headCph);if(r!==0)return r;let n=e.writeVarInt(t.seq);if(n!==0)return n;return 0},decode(e){let[t,r]=e.readVarBytes();if(r!==0)return a(r);let[n,s]=e.readVarInt();if(s!==0)return a(s);return f({headCph:t,seq:n})}};D();M();var ge={encode(e,t){e.writeBytes(t.pubKey),e.writeBytes(t.sig);let r=e.writeDate(t.timestamp);if(r!==0)return r;return 0},decode(e){let[t,r]=e.readBytes(As);if(r!==0)return a(r);let[n,s]=e.readBytes(Re);if(s!==0)return a(s);let[o,i]=e.readDate();if(i!==0)return a(i);return f({pubKey:t,sig:n,timestamp:o})}};fe();M();var xo={encode(e,t){if(t.rlm.byteLength!==oe)return 10;return e.writeBytes(t.rlm),e.writeVarInt(t.seq)},decode(e){let[t,r]=e.readBytes(oe);if(r!==0)return a(r);let[n,s]=_e(t);if(s!==0)return a(s);let[o,i]=e.readVarInt();if(i!==0)return a(i);return f({rlm:n,seq:o})}},Po={async encodeReq(e,t,r,n,s){let o=s.writeStruct(ge,r);if(o!==0)return o;return s.writeStruct(xo,n)},async handleReq(e,t,r){let{clock:n,crypto:s,storage:o}=e,[i,c]=t.readStruct(ge);if(c!==0)return c;let u=await qe(i,s,n);if(u!==0)return u;let{pubKey:d}=i,[l,p]=await o.hasUser(d);if(p!==0)return p;if(!l)return 5;let[y,m]=t.readStruct(xo);if(m!==0)return m;if(!t.done())return 8;let[h,g]=await o.listHeads(d,y.rlm,y.seq);if(g!==0)return g;return r.writeStructs(bn,h)},decodeResp(e){return e.readStructs(bn)}};D();M();var In={encode(e,t){e.writeVarInt(t.seq);let r=e.writeVarBytes(t.bodyCph);if(r!==0)return r;return 0},decode(e){let[t,r]=e.readVarInt();if(r!==0)return a(r);let[n,s]=e.readVarBytes();if(s!==0)return a(s);return f({seq:t,bodyCph:n})}};D();fe();M();var Eo={encode(e,t){if(t.rlm.byteLength!==oe)return 10;e.writeBytes(t.rlm);for(let r of t.seqs){let n=e.writeVarInt(r);if(n!==0)return n}return 0},decode(e){let[t,r]=e.readBytes(oe);if(r!==0)return a(r);let[n,s]=_e(t);if(s!==0)return a(s);let o=[];while(!e.done()){let[i,c]=e.readVarInt();if(c!==0)return a(c);o.push(i)}return f({rlm:n,seqs:o})}},Ao={async encodeReq(e,t,r,n,s){let o=s.writeStruct(ge,r);if(o!==0)return o;return s.writeStruct(Eo,n)},async handleReq(e,t,r){let{clock:n,crypto:s,storage:o}=e,[i,c]=t.readStruct(ge);if(c!==0)return c;let u=await qe(i,s,n);if(u!==0)return u;let{pubKey:d}=i,[l,p]=await o.hasUser(d);if(p!==0)return p;if(!l)return 5;let[y,m]=t.readStruct(Eo);if(m!==0)return m;console.info(`PULL: ${y.seqs.length} bags`);let[h,g]=await o.getBodies(d,y.rlm,y.seqs);if(g!==0)return g;if(!h)return 17;for(let{seq:S,bodyCph:b}of h){let E={seq:S,bodyCph:b},P=r.writeStruct(In,E);if(P!==0)return P}return 0},decodeResp(e){return e.readStructs(In)}};ee();D();fe();M();var wn={encode(e,t){if(t.rlm.byteLength!==oe)return 10;if(t.sig.byteLength!==Re)return 10;e.writeBytes(t.sig),e.writeBytes(t.rlm),e.writeBytes(t.kdm);let r=e.writeVarBytes(t.headCph);if(r!==0)return r;let n=e.writeVarBytes(t.bodyCph);if(n!==0)return n;return 0},decode(e){let[t,r]=e.readBytes(Re);if(r!==0)return a(r);let[n,s]=e.readBytes(oe);if(s!==0)return a(s);let[o,i]=_e(n);if(i!==0)return a(i);let[c,u]=e.readBytes(Le);if(u!==0)return a(u);let[d,l]=e.readVarBytes();if(l!==0)return a(l);let[p,y]=e.readVarBytes();if(y!==0)return a(y);return f({rlm:o,sig:t,kdm:c,headCph:d,bodyCph:p})}};D();fe();M();var mr={encode(e,t){let r=e.writeVarInt(t.seq);if(r!==0)return r;if(t.rlm.byteLength!==oe)return 10;e.writeBytes(t.rlm);let n=e.writeVarBytes(t.headCph);if(n!==0)return n;let s=t.bodyCph?t.bodyCph.length:0,o=e.writeVarInt(s);if(o!==0)return o;if(s>0){if(!t.bodyCph)return 10;e.writeBytes(t.bodyCph)}return 0},decode(e){let[t,r]=e.readVarInt();if(r!==0)return a(r);let[n,s]=e.readBytes(oe);if(s!==0)return a(s);let[o,i]=_e(n);if(i!==0)return a(i);let[c,u]=e.readVarBytes();if(u!==0)return a(u);let[d,l]=e.readVarInt();if(l!==0)return a(l);let p;if(d>0){let[y,m]=e.readBytes(d);if(m!==0)return a(m);p=y}return f({seq:t,rlm:o,headCph:c,bodyCph:p})}};D();M();var hr={encode(e,t){e.writeBytes(t.sig),e.writeBytes(t.kdm);let r=e.writeVarBytes(t.headCph);if(r!==0)return r;return 0},decode(e){let[t,r]=e.readBytes(Re);if(r!==0)return a(r);let[n,s]=e.readBytes(Le);if(s!==0)return a(s);let[o,i]=e.readVarBytes();if(i!==0)return a(i);return f({sig:t,kdm:n,headCph:o})}};D();M();var qt={encode(e,t){if(e.writeVarInt(t.idx),e.writeBytes(new Uint8Array([t.status])),t.status===0)e.writeVarInt(t.seq);return 0},decode(e){let[t,r]=e.readVarInt();if(r!==0)return a(r);let[n,s]=e.readBytes(1);if(s!==0)return a(s);let o=n[0];if(o!==0)return f({idx:t,status:o});let[i,c]=e.readVarInt();if(c!==0)return a(c);return f({idx:t,status:o,seq:i})}};D();var ko={encode(e,t){return e.writeStructs(wn,t)},decode(e){return e.readStructs(wn)}},Do={async encodeReq(e,t,r,n,s){let o=s.writeStruct(ge,r);if(o!==0)return o;return s.writeStruct(ko,n)},async handleReq(e,t,r){let{clock:n,crypto:s,storage:o,notifier:i}=e,[c,u]=t.readStruct(ge);if(u!==0)return u;let d=await qe(c,s,n);if(d!==0)return d;let{pubKey:l}=c,[p,y]=await o.hasUser(l);if(y!==0)return y;if(!p)return 5;let[m,h]=t.readStruct(ko);if(h!==0)return h;console.info(`PUSH: ${m.length} bags`);let g;try{g=await s.importVerifyKey(l)}catch{return 29}let S=[],b=[];for(let w=0;w<m.length;w++){let k=m[w];if(!await Cs(k,g,s)){let R={idx:w,status:3},H=r.writeStruct(qt,R);if(H!==0)return H;continue}S.push(w),b.push(k)}let[E,P]=await o.setBags(l,b);if(P!==0)return P;if(!E||E.length!==b.length)return 17;let x=[];for(let w=0;w<b.length;w++){let k=b[w],T=S[w],R=E[w];if(R.status!==0){let F={idx:T,status:R.status},W=r.writeStruct(qt,F);if(W!==0)return W;continue}let H=R.seq,C=new q,K=C.writeStruct(hr,k);if(K!==0)return K;let U=C.result(),I={seq:H,rlm:k.rlm,headCph:U};if(m.length===1&&k.bodyCph.length<=Ds)I.bodyCph=k.bodyCph;x.push(I);let N={idx:T,status:0,seq:H},O=r.writeStruct(qt,N);if(O!==0)return O}if(x.length>0){let w=new q,k=w.writeStructs(mr,x);if(k!==0)return k;let T=w.result();await Promise.resolve(i.push(l,T))}return 0},decodeResp(e){return e.readStructs(qt)}};D();M();var Bo={async encodeReq(e,t,r,n,s){return s.writeStruct(ge,r)},async handleReq(e,t,r){let{clock:n,crypto:s,storage:o}=e,[i,c]=t.readStruct(ge);if(c!==0)return c;let u=await qe(i,s,n);if(u!==0)return u;let{pubKey:d}=i;if(!t.done())return 8;let[l,p]=await o.addUser(d);if(p!==0)return p;return 0},decodeResp(e){return f(void 0)}};ae();ee();D();class xn{url;websocket;constructor(e){this.url=e}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(e,t,r=()=>{},n=()=>{}){let{url:s}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let o=new q;o.writeStruct(ge,e);let i=o.result(),c=Ye(i);return s.searchParams.set("t",c),this.websocket=new WebSocket(s),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),n()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,r()},this.websocket.onmessage=(u)=>{let d=new Uint8Array(u.data);t(d)},this.websocket.onerror=(u)=>{console.log(`ERROR: ${JSON.stringify(u)}`),this.websocket=void 0,r()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}M();var le={user:{path:"/user",endpoint:Bo,name:0},push:{path:"/push",endpoint:Do,name:2},peek:{path:"/peek",endpoint:Po,name:1},pull:{path:"/pull",endpoint:Ao,name:3}},ec={0:le.user,2:le.push,1:le.peek,3:le.pull},Hf={[le.user.path]:le.user,[le.push.path]:le.push,[le.peek.path]:le.peek,[le.pull.path]:le.pull};class vo{url;listener;constructor(e){this.url=e;this.listener=new xn(e)}async call(e,t){let{path:r}=ec[e],n=new URL(r,this.url);try{return await tc(n,t)}catch{return a(25)}}}var Mo=(e)=>new vo(e.handle);async function tc(e,t){let r=await fetch(e,{method:"POST",body:t.result().slice()});if(!r.ok)return a(24);let n=await L.fromResponse(r);return f(n)}M();class gr{crypto;clock;transport;updateHostMeta;#e;constructor(e,t,r,n,s){this.crypto=t;this.clock=r;this.transport=n;this.updateHostMeta=s;this.#e=e}async call(e,t){let{clock:r,transport:n}=this,{endpoint:s,name:o}=e,[i,c]=await this.identity();if(c!==0)return a(c);let u=r.now(),[d,l]=await Qr(i,u);if(l!==0)return a(l);let p=new q,y=await s.encodeReq(this,i,d,t,p);if(y!==0)return a(y);let m=r.now(),[h,g]=await n.call(o,p),S=r.now();if(g!==0)return a(g);let[b,E]=h.readStruct(Yr);if(E!==0)return a(E);if(b.status!==0)return a(b.status);let x={clockOffset:Ts(m,b.timeRcvd,b.timeSent,S),subscription:b.subscription},w=await this.updateHostMeta(x);if(w!==0)return a(w);return s.decodeResp(h)}bagMgrFor(e=j){return this.#e.find((t)=>nr(e,t.realmKDM))}bagMgrs(){return this.#e}add(e){if(this.bagMgrFor(e.realmKDM)!==void 0)return;this.#e.push(e)}identity=()=>{let e=this.bagMgrFor(j)??this.#e[0];if(e===void 0)return Promise.resolve(a(13));return Promise.resolve(f(e))};hostRlm=(e=j)=>{let t=this.bagMgrFor(e);if(t===void 0)return Promise.resolve(a(13));return Promise.resolve(f(t.rlm))};seal=async(e,t=j)=>{let r=this.bagMgrFor(t);if(r===void 0)return a(13);return Rs(e,r,this.crypto)};register=()=>this.call(le.user,void 0);peek=async(e,t=j)=>{let[r,n]=await this.hostRlm(t);if(n!==0)return a(n);return this.call(le.peek,{rlm:r,seq:e})};push=(e)=>this.call(le.push,e);pull=async(e,t=j)=>{let[r,n]=await this.hostRlm(t);if(n!==0)return a(n);return this.call(le.pull,{rlm:r,seqs:e})};listen=async(e,t,r)=>{let{clock:n,transport:s}=this,{listener:o}=s,[i,c]=await this.identity();if(c!==0)return c;let u=n.now(),[d,l]=await Qr(i,u);if(l!==0)return l;return await o.connect(d,e,t,r)};isConnected(){let e=this.transport?.listener;if(e&&typeof e.connected==="function")return e.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}ee();ee();D();M();var rc=new Uint8Array(0),Nt={encode(e,t){if(t.body!==void 0&&!(t.body instanceof Uint8Array))return 10;let r=e.writeVarBytes(t.pid??rc);if(r!==0)return r;let n=e.writeVarStrings(t.tags??[]);if(n!==0)return n;if(t.body!==void 0&&t.body.length>0)e.writeBytes(t.body);return 0},decode(e){let[t,r]=e.readVarBytes();if(r!==0)return a(r);let n;if(t.length>0){let u=new L(t),[d,l]=u.readStruct(ie);if(l!==0)return a(l);if(!u.done())return a(14);let[p,y]=ct(d);if(y!==0)return a(y);n=p}let[s,o]=e.readVarStrings();if(o!==0)return a(o);let i=e.readRest(),c={};if(n!==void 0)c.pid=n;if(s.length>0)c.tags=s;if(i.length>0)c.body=i;return f(c)}};function mt(e){let t=new q,r=t.writeStruct(Nt,e);if(r!==0)return a(r);return f(t.result())}D();fe();fe();var op=Symbol("DownloadKey");function Sr(e){if(e===void 0)return!0;return e.label===j.label&&e.index===j.index}function Uo(e,t){return e.label===t.label&&e.index===t.index}function ht(e){return`${e.label}\x00${e.index}`}function _t(e,t=j){if(Sr(t))return e.lastSeq;return e.seqs?.find((n)=>n.label===t.label&&n.index===t.index)?.lastSeq??0}function gt(e){let t=[j],r=new Set([ht(j)]),n=(s,o)=>{let i=s===""&&o===0?j:{label:s,index:o},c=ht(i);if(r.has(c))return;r.add(c),t.push(i)};for(let s of e){if(n(s.label,s.index),s.prior===void 0)continue;for(let o of s.prior)n(s.label,o)}return t}function Co(e,t){if(e===void 0||e==="")return j;for(let r of t)if(r.label===e)return{label:r.label,index:r.index};return{label:e,index:0}}function br(e){if(Sr(e))return;return e}function Pn(e,t,r){let n=r??j;return Sr(n)?`${e}:${t}`:`${e}:${n.label}:${n.index}:${t}`}function Ro(e,t){if(t.setLastSeq!==void 0)return t.setLastSeq;if(t.lastSeq!==void 0&&t.lastSeq>e)return t.lastSeq;return}function To(e){let t=0,r=[];for(let n of e)if(Sr(n))t=n.lastSeq;else r.push(n);if(r.length===0)return{lastSeq:t};return{lastSeq:t,seqs:r}}D();M();function Fe(e){if(e===void 0)return f("");if(typeof e!=="string")return a(10);return f(e.trim())}function Ho(e,t,r){let[n,s]=Fe(t);if(s!==0||n===void 0)return a(10);if(r&&e!==void 0&&e!==n)return a(10);return f(n)}ae();ee();D();M();D();M();var En={encode(e,t){let r=e.writeVarString(t.lbl);if(r!==0)return r;let n=e.writeVarInt(t.idx);if(n!==0)return n;let s=e.writeVarInt(t.num);if(s!==0)return s;return e.writeBytes(t.hsh),e.writeBytes(t.sig),0},decode(e){let[t,r]=e.readVarString();if(r!==0)return a(r);let[n,s]=e.readVarInt();if(s!==0)return a(s);let[o,i]=e.readVarInt();if(i!==0)return a(i);let[c,u]=e.readBytes(er);if(u!==0)return a(u);let[d,l]=e.readBytes(Re);if(l!==0)return a(l);return f({lbl:t,idx:n,num:o,hsh:c,sig:d})}};var An={encode(e,t){let r=e.writeStruct(En,t.head);if(r!==0)return r;let n=e.writeVarBytes(t.indexEnc);if(n!==0)return n;let s=e.writeVarBytes(t.bodyEnc);if(s!==0)return s;return 0},decode(e){let[t,r]=e.readStruct(En);if(r!==0)return a(r);let[n,s]=e.readVarBytes();if(s!==0)return a(s);let[o,i]=e.readVarBytes();if(i!==0)return a(i);return f({head:t,indexEnc:n,bodyEnc:o})}};D();M();var kn={encode(e,t){e.writeBytes(t.kdm);let r=e.writeVarBytes(t.headCph);if(r!==0)return r;let n=e.writeVarInt(t.lenBody);if(n!==0)return n;if(t.lenBody>0&&t.offBody!==void 0){let s=e.writeVarInt(t.offBody);if(s!==0)return s}return 0},decode(e){let[t,r]=e.readBytes(Le);if(r!==0)return a(r);let[n,s]=e.readVarBytes();if(s!==0)return a(s);let[o,i]=e.readVarInt();if(i!==0)return a(i);let c;if(o>0){let[u,d]=e.readVarInt();if(d!==0)return a(d);c=u}return f({kdm:t,headCph:n,lenBody:o,offBody:c})}};D();M();var Ir;((Ko)=>{Ko.defaultFileExtension="dpl";async function t(s,o,i){let c=i.idKDM,u=new q,d=new q,l=0,p=0;for(let x of s){let w=new q,k=w.writeStruct(Ie,x.head);if(k!==0)return a(k);let T=w.result(),[R,H]=await i.bagKDM(T);if(H!==0)return a(H);let[C,K]=await i.encrypt(R,T);if(K!==0)return a(K);let U=new Uint8Array(0);if(x.body){let[F,W]=await i.encrypt(R,x.body);if(W!==0)return a(W);U=F}let I=x.head.len>0&&x.head.hsh!==void 0?U.length:0,N={kdm:R,headCph:C,lenBody:I,offBody:I>0?p:void 0},O=u.writeStruct(kn,N);if(O!==0)return a(O);if(x.body)d.writeBytes(U),p+=U.length;l++}let y=d.result(),m=u.result(),h=await o.blake3(m),[g,S]=await i.sign(h);if(S!==0)return a(S);let b={lbl:c.label,idx:c.index,num:l,hsh:h,sig:g},E=new q;E.writeStruct(An,{head:b,indexEnc:m,bodyEnc:y});let P=E.result();return f(P)}Ko.encodeFile=t;async function r(s,o,i){let[c,u]=An.decode(new L(s));if(u!==0)return a(u);let{head:d,indexEnc:l,bodyEnc:p}=c,y=i.idKDM;if(d.lbl!==y.label||d.idx!==y.index)return a(10);let m;try{m=await o.importVerifyKey(i.publicKey)}catch{return a(29)}if(!await o.checkSigEd25519(d.sig,d.hsh,m))return a(3);let g=await o.blake3(l);if(!Q(g,d.hsh))return a(19);let S=new L(l),b=[];for(let P=0;P<d.num;P++){let[x,w]=S.readStruct(kn);if(w!==0)return a(w);b.push(x)}if(b.length!==d.num)return a(14);let E=[];for(let P of b){let[x,w]=await i.decrypt(P.kdm,P.headCph);if(w!==0)return a(w);let[k,T]=Ie.decode(new L(x));if(T!==0)return a(T);let R;if(P.lenBody>0&&P.offBody!==void 0){if(k.hsh===void 0)return a(14);let H=p.slice(P.offBody,P.offBody+P.lenBody),[C,K]=await i.decrypt(P.kdm,H);if(K!==0)return a(K);R=C;let U=await o.blake3(R);if(!Q(U,k.hsh))return a(19)}E.push({head:k,body:R})}return f(E)}Ko.decodeFile=r;async function n(s,o,i,c,u){let[d,l]=await r(s,o,i);if(l!==0)return a(l);let p=await u(d);return t(p,o,c)}Ko.migrateFile=n})(Ir||={});ee();D();M();async function Vo({now:e,bod:t,crypto:r,typ:n=""}){let s=await r.genRandomBytes(8),o=new q,i=o.writeStruct(ie,{id:s,ts:e});if(i!==0)return a(i);let c=o.result();return wr({now:e,eid:c,ctr:0,typ:n,bod:t,crypto:r})}async function wr({now:e,eid:t,ctr:r,typ:n="",bod:s,crypto:o}){let i=new L(t),[c,u]=ie.decode(i);if(u!==0)return a(u);let d=e.getTime()-c.ts.getTime(),l,p=s?.length??0;if(s&&p>0)l=await o.blake3(s);return f({eid:t,off:d,ctr:r,typ:n,len:p,hsh:l})}ae();ee();D();M();function nc(e,t){let r=e.length<t.length?e.length:t.length;for(let n=0;n<r;n++)if(e[n]!==t[n])return e[n]-t[n];return e.length-t.length}async function Ft(e,t){let r=Array.from(e);r.sort(nc);let n=0;for(let i of r)n+=i.length;let s=new Uint8Array(n),o=0;for(let i of r)s.set(i,o),o+=i.length;return t.blake3(s)}function sc(e){let t=new q,r=t.writeVarBytes(e.eid);if(r!==0)return a(r);let n=t.writeDate(e.updatedAt);if(n!==0)return a(n);let s=t.writeVarInt(e.ctr);if(s!==0)return a(s);return f(t.result())}async function xr(e,t){let r=[];for(let n of e){let[s,o]=sc(n);if(o!==0||!s)return a(o);r.push(s)}return f(await Ft(r,t))}ee();D();M();Wt();var Xp=Symbol("EntityID");function Lo(e){return"type"in e}var Gp=Symbol("DerivationSeed"),Qp=Symbol("PublicKey"),$p=Symbol("PrivateKey"),zp=Symbol("HostSpecificKeyPair"),Yp=Symbol("Hash");ee();D();M();function oc(e){if(!e.bod||e.bod.length===0){let o={off:e.off,ctr:e.ctr,eid:e.eid};return f(o)}let t=new L(e.bod),[r,n]=t.readStruct(Nt);if(n!==0)return a(n);let s={off:e.off,ctr:e.ctr,eid:e.eid,type:e.typ??"",body:r.body};if(r.pid!==void 0)s.pid=r.pid;if(r.tags!==void 0)s.tags=r.tags;return f(s)}class Pr{applier;emitter=new Ut;clearer;onDirtyEids;cacheDriven;peerIngest;constructor(e,t,r,n){this.applier=e;this.clearer=t,this.onDirtyEids=r,this.cacheDriven=n?.cacheDriven??!1,this.peerIngest=n?.peerIngest}apply=async(e)=>{let t=[],r=[];for(let c of e){let[u,d]=oc(c);if(r.push(d),d!==0)continue;t.push(u)}let{stats:n,types:s,eids:o}=await this.applier(t),i=[];for(let c=0;c<e.length;c++){let u=r[c],d=n[c];if(u!==0){i.push(u);continue}if(d!==0){i.push(d);continue}i.push(0)}if(!this.cacheDriven)for(let c of s)this.emitter.emit(c,null);if(o.length>0)this.onDirtyEids?.(o);return i};clear=async()=>{let e=await this.clearer();if(e!==0)return e;return this.emitter.emitAll(null),e};notify=(e)=>{for(let t of e)this.emitter.emit(t,null)};refresh=async(e)=>{if(this.peerIngest){await this.peerIngest(e);return}};on=(e,t)=>{this.emitter.addEventListener(e,t)};off=(e,t)=>{this.emitter.removeEventListener(e,t)}}function Y(e){return"type"in e}function ic(e,t){let r=t.excludeStart?e>t.start:e>=t.start,n=t.excludeEnd?e<t.end:e<=t.end;return r&&n}function jt(e){if(e instanceof Date)return f(!0);if(e.range.start>e.range.end)return a(10);return f(!0)}function Dn(e,t){if(t instanceof Date)return e.getTime()===t.getTime();return ic(e,t.range)}function ac(e,t){let r=t.excludeStart?e>t.start:e>=t.start,n=t.excludeEnd?e<t.end:e<=t.end;return r&&n}function Xt(e){if(typeof e==="string")return f(e.length>0);if("range"in e){if(e.range.start>e.range.end)return a(10);return f(!0)}return f(e.prefix.length>0)}function Bn(e,t){if(typeof t==="string")return e===t;if("range"in t)return ac(e,t.range);if(t.prefix.length===0)return!1;return e.startsWith(t.prefix)}function cc(e){if(!Array.isArray(e)||e.length===0)return;let t=new Set,r=[];for(let n of e){if(typeof n!=="string"||n.length===0)continue;if(t.has(n))continue;t.add(n),r.push(n)}return r.length>0?r:void 0}function Er(e){return{eid:e.eid,ctr:e.ctr,updatedAt:e.updatedAt}}function qo(e){let t=new L(e.eid),[r,n]=t.readStruct(ie);if(n!==0)return a(n);return f({eid:e.eid,ctr:e.ctr,updatedAt:new Date(r.ts.getTime()+e.off)})}function St(e,t){let r=new L(t.eid),[n,s]=r.readStruct(ie);if(s!==0)return a(s);let o=new Date(n.ts.getTime()+t.off);if(e!==void 0&&o<=e.updatedAt)return a(15);if(Lo(t)){let i=cc(t.tags);return f({eid:t.eid,pid:t.pid,...i!==void 0?{tags:i}:{},type:t.type,createdAt:n.ts,updatedAt:o,ctr:t.ctr,body:t.body})}return f({eid:t.eid,updatedAt:o,ctr:t.ctr})}function bt(e,t){let r=new Set;if(e!==void 0&&Y(e))r.add(e.type);if(Y(t))r.add(t.type);return[...r]}M();class Ar{inflight=null;again=!1;run(e){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain(e),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain(e){try{this.again=!1;let t=await e();while(this.again)this.again=!1,t=await e();return t}finally{this.inflight=null}}}var No=100;class vn{timer=null;delayMs;work;tail=new Ar;constructor(e,t){this.delayMs=e<0?0:e,this.work=t}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 _o=!1;function Fo(e){_o=e===!0}function X(e,t){if(!_o)return;let r=Math.round(performance.now());if(t!==void 0)console.warn(`[dip ${r}ms] ${e}`,t);else console.warn(`[dip ${r}ms] ${e}`)}ee();D();function Wo(e){let t=new L(e.eid),[r,n]=ie.decode(t);if(n!==0)return;return r.ts.getTime()+e.off}function uc(e,t){let r=Wo(e),n=Wo(t);if(r===void 0&&n===void 0)return 0;if(r===void 0)return 1;if(n===void 0)return-1;if(n!==r)return n-r;return t.ctr-e.ctr}function It(e,t){return e.slice().sort((r,n)=>uc(t(r),t(n)))}var Mn={phase:"idle"},Gt=50;function Un(e,t,r){if(e<=0||t<=0)return!1;if(e===1||e===t)return!0;return e%r===0}ee();D();M();var Cn="blob:";function jo(e){return Cn+e}function Xo(e){return e!==void 0&&e.startsWith(Cn)}function dc(e){if(!Xo(e))return;let t=e.slice(Cn.length);if(t.length===0)return;return t}function Go(e){return new L(e).readStruct(Nt)}function lc(e,t){let r={};if(e!==void 0&&e.pid!==void 0)r.pid=e.pid;if(e!==void 0&&e.tags!==void 0&&e.tags.length>0)r.tags=e.tags;if(t.length>0)r.body=t;return r}function fc(e,t,r){let n={},s=r!==void 0&&Object.hasOwn(r,"pid")?r.pid:e.pid,o=r!==void 0&&Object.hasOwn(r,"tags")?r.tags:e.tags;if(s!==void 0)n.pid=s;if(o!==void 0&&o.length>0)n.tags=o;if(t.length>0)n.body=t;return n}function pc(e){let t=new L(e.eid),[r,n]=t.readStruct(ie);if(n!==0)return a(n);return f({eid:e.eid,ctr:e.ctr,updatedAt:new Date(r.ts.getTime()+e.off)})}function Qo(e,t,r){if(e.length===0)return a(10);let[n,s]=mt(lc(r,t));if(s!==0)return a(s);return f({typ:jo(e),bod:n})}function $o(e,t,r){if(e===void 0||e.bod===void 0||e.bod.length===0)return a(13);let n=dc(e.typ);if(n===void 0)return a(10);let[s,o]=pc(e);if(o!==0)return a(o);let[i,c]=Go(e.bod);if(c!==0)return a(c);let u=r?.mime??n;if(u.length===0)return a(10);let[d,l]=mt(fc(i,t,r));if(l!==0)return a(l);return f({typ:jo(u),bod:d,prior:s})}function zo(e){if(e===void 0||e.bod===void 0||e.bod.length===0)return a(13);if(!Xo(e.typ))return a(13);let[t,r]=Go(e.bod);if(r!==0)return a(r);if(t.body===void 0)return f(new Uint8Array);return f(t.body.slice())}function Yo(e,t){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(e,t);return}let r=URL.createObjectURL(e),n=document.createElement("a");n.href=r,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}function Jo(e,t,r){let n=[],s=[],o=0;for(let i of e){let c=t(i);if(s.length>0&&o+c>r)n.push(s),s=[],o=0;if(s.push(i),o+=c,o>=r)n.push(s),s=[],o=0}if(s.length>0)n.push(s);return n}async function Rn(e,t,r){let n=e.length;if(n<1)return[];let s=Array(n),o=0,i=Math.min(Math.max(1,t),n),c=async()=>{while(!0){let d=o;if(o+=1,d>=n)return;s[d]=await r(e[d],d)}},u=[];for(let d=0;d<i;d++)u.push(c());return await Promise.all(u),s}ee();sr();D();fe();ee();D();M();async function kr(e,t,r,n){let s=r.rlm;if(s.byteLength!==oe)return a(10);let o=new L(e.headCph),[i,c]=o.readStruct(hr);if(c!==0)return a(c);let{sig:u,kdm:d,headCph:l}=i;if(!await n.checkSigEd25519(u,rr(s,l),t))return a(3);let[y,m]=await r.decrypt(d,l);if(m!==0)return a(m);return f({kdm:d,headEnc:y})}D();M();var Yy=Symbol("EntRlm");function rt(e){if(typeof e!=="string"||e==="")return;return e}function Dr(e){if(e.rlm!==void 0&&e.rlm!=="")return e;if(e.rlm===void 0)return e;let t={...e};return delete t.rlm,t}function Tn(e){return typeof e==="number"&&Number.isInteger(e)&&e>=0}function yc(e){return e!==null&&typeof e==="object"}function Br(e){if(!yc(e)||typeof e.label!=="string")return;if(!Tn(e.index))return;let t={label:e.label,index:e.index};if(e.prior===void 0)return t;if(!Array.isArray(e.prior))return;let r=[];for(let n of e.prior){if(!Tn(n))return;r.push(n)}if(r.length>0)t.prior=r;return t}function Zo(e,t,r){if(typeof e!=="string"||!Tn(r))return a(10);if(t!==void 0&&r<t.index)return a(10);let n=t?.prior!==void 0?t.prior.slice():void 0;if(t!==void 0&&r>t.index){let s=n!==void 0?n:[];return s.push(t.index),f({label:e,index:r,prior:s})}return f({label:e,index:r,...n!==void 0?{prior:n}:{}})}M();ae();D();var xt="f",vr="t",wt="e";function mc(e){if(e===!0||e===vr)return vr;if(e===wt)return wt;return xt}function ei(e){return e!==0&&e!==15&&e!==18&&e!==17}function Hn(e,t,r){if(e.apld=t,t===wt&&r!==void 0)e.err=r;else delete e.err}async function Mr(e,t,r,n){let s=n?.body!==!1,o=mc(t.apld),i=t.body,c=i?.length??0,u;if(s&&i&&c>0)u=await r.blake3(i);let d={eid:t.eid,off:t.off??0,ctr:t.ctr??0,typ:t.typ??"",len:c,hsh:u},l={hash:e,head:d,apld:o};if(s&&i!==void 0)l.body=i;if(o===wt&&t.err!==void 0)l.err=t.err;let p=rt(t.rlm);if(p!==void 0)l.rlm=p;return l}var Kn=1048576,Vn=1048576,ri=64;function hc(e){return e.sig.length+e.kdm.length+e.headCph.length+e.bodyCph.length}function Qt(e,t,r,n){let s=`${t}\x00${ht(n??j)}`,o=e.get(s);if(o){o.seqs.push(r);return}e.set(s,{host:t,realm:n,seqs:[r]})}async function ni(e,t){for(let r of t.values())await e.downloads.deq(r.host,r.seqs,r.realm)}async function gc(e,t,r,n,s,o=j){if(n.length<1)return 0;let[i,c]=await e.push(n);if(c!==0)return c;if(!i)return 27;for(let d of i){if(d.status!==0){console.error("push err",d);continue}let l=s[d.idx];if(!l){console.error("no hash",d);continue}await t.uploads.deq(r,[l])}let u=await t.hosts.get(r);if(u){let d=_t(u,o),l=d,p=[];for(let y of i)if(y.status===0)p.push(y.seq);p.sort((y,m)=>y-m);for(let y of p)if(y===d+1)d=y;if(d>l)await t.hosts.touch(r,d,o)}return 0}async function ti(e,t){if(t.length<1)return f([]);let r=new Map;for(let s of t){let o=s.realm??j,i=ht(o),c=r.get(i);if(!c)c={realm:o,dls:new Map,seqs:[]},r.set(i,c);c.dls.set(s.seq,s),c.seqs.push(s.seq)}let n=[];for(let s of r.values()){let[o,i]=await e.pull(s.seqs,s.realm);if(i!==0)return a(i);if(!o)return a(27);for(let{seq:c,bodyCph:u}of o){let d=s.dls.get(c);if(!d)continue;n.push({dl:d,bodyCph:u})}}return f(n)}async function Sc(e,t,r,n){if(n.length<1)return f({parts:[],hashes:[]});let s=[],o=[],i=[],c=new Map;for(let{dl:d,bodyCph:l}of n){let{head:p,kdm:y,seq:m,host:h}=d,g=d.realm??j,[S,b]=await si(d,r);if(b!==0){Qt(c,h,m,d.realm);continue}let{headEnc:E,headEncHash:P}=S,x=t.find((H)=>nr(g,H.realmKDM));if(x===void 0){Qt(c,h,m,d.realm);continue}let[w,k]=await $r(E,l,{decrypt:(H)=>x.decrypt(y,H)},r,P);if(k!==0){Qt(c,h,m,d.realm);continue}let T={head:p,body:w.bod},R=w.headHash;i.push({key:R,data:ai(T,g)}),s.push(T),o.push(R),Qt(c,h,m,d.realm)}let u=await e.messages.add(i);await ni(e,c);for(let d=0;d<u.length;d++){let l=u[d];if(l!==0&&l!==15)console.error("ERR storing",A[l],"for message",d)}return f({parts:s,hashes:o})}async function si(e,t){let r=e.headEnc;if(!r){let s=new q,o=s.writeStruct(Ie,e.head);if(o!==0)return a(o);r=s.result()}if(e.headEncHash)return f({headEnc:r,headEncHash:e.headEncHash});let n=await t.blake3(r);return f({headEnc:r,headEncHash:n})}async function oi(e,t,r){let n=new Set;for(let i of t)n.add(V(i));if(n.size<1)return;let s=Array.from(await e.downloads.list());if(s.length<1)return;let o=new Map;for(let i of s){let c;if(i.headEncHash)c=V(i.headEncHash);else{let[u,d]=await si(i,r);if(d!==0)continue;c=V(u.headEncHash)}if(!n.has(c))continue;Qt(o,i.host,i.seq,i.realm)}await ni(e,o)}async function On({conn:e,store:t,host:r,crypto:n,onProgress:s,peekProgressEvery:o,peekConcurrency:i,realm:c}){let u=c??j,d=e.bagMgrFor(u);if(d===void 0)return 13;let[l,p]=await e.identity();if(p!==0)return p;let y;try{y=await n.importVerifyKey(l.publicKey)}catch{return 29}let m=[],[h,g]=await e.peek(_t(r,u),u);if(g!==0)return g;let S=h.length,b=o??Gt,E=i??ri;if(s&&S>0)s({phase:"peek",host:r.label,done:0,total:S});let P=0,x=await Rn(h,E,async(k)=>{let[T,R]=await kr(k,y,d,n),H;if(R!==0)H={ok:!1,seq:k.seq,stat:R};else{let C=await n.blake3(T.headEnc);H={ok:!0,seq:k.seq,kdm:T.kdm,headEnc:T.headEnc,headEncHash:C}}if(P+=1,s&&Un(P,S,b))s({phase:"peek",host:r.label,done:P,total:S});return H}),w=new Set;for(let k of x){if(!k.ok){console.error("peek: decrypting item head",k.stat);continue}let T=V(k.headEncHash);if(await t.messages.has(k.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await t.uploads.deq(r.label,[k.headEncHash]),await t.downloads.deq(r.label,[k.seq],u);continue}if(w.has(T)){await t.downloads.deq(r.label,[k.seq],u);continue}let H=new L(k.headEnc),[C,K]=H.readStruct(Ie);if(K!==0){console.error("peek: reading item head",K);continue}w.add(T);let U={kdm:k.kdm,head:C,seq:k.seq,host:r.label,headEnc:k.headEnc,headEncHash:k.headEncHash},I=br(u);if(I!==void 0)U.realm=I;m.push(U)}if(await t.downloads.enq(m),h.length>0){let k=Math.max(...h.map((T)=>T.seq));await t.hosts.recordSeqs(r.label,{lastSeq:k},u)}if(s)s({phase:"peek",host:r.label,done:S,total:S});return 0}async function ii({conn:e,store:t,host:r,maxPushBytes:n,onProgress:s}){let o=n??Kn,i=await t.uploads.list(r.label),c=i.length,u=0;if(s&&c>0)s({phase:"push",host:r.label,done:0,total:c});let d=[],l=[],p=0,y=j,m=async()=>{if(d.length<1)return 0;let S=d.length,b=await gc(e,t,r.label,d,l,y);if(d=[],l=[],p=0,b===0){if(u+=S,s)s({phase:"push",host:r.label,done:u,total:c})}return b},h=[],g=await t.realms.list();for(let S of i){let b=await t.messages.get(S);if(!b){u+=1;continue}h.push({hash:S,realm:Co(b.rlm,g),msg:{...b.head,bod:b.body}})}h.sort((S,b)=>{if(S.realm.label<b.realm.label)return-1;if(S.realm.label>b.realm.label)return 1;return S.realm.index-b.realm.index});for(let S of h){if(d.length>0&&!Uo(y,S.realm)){let x=await m();if(x!==0)return x}let[b,E]=await e.seal(S.msg,S.realm);if(E!==0)return E;let P=hc(b);if(d.length>0&&p+P>o){let x=await m();if(x!==0)return x}if(d.length<1)y=S.realm;if(d.push(b),l.push(S.hash),p+=P,p>=o){let x=await m();if(x!==0)return x}}return m()}async function Ln({conn:e,store:t,host:r,crypto:n,maxPullBytes:s,onProgress:o},i){let c=s??Vn,u=await t.downloads.list(),d=Array.from(u).filter((g)=>g.host===r.label);if(d.length<1)return 15;let l=It(d,(g)=>g.head),p=Jo(l,(g)=>g.head.len,c),y=l.length,m=0;if(o)o({phase:"pull",host:r.label,done:0,total:y});let h=ti(e,p[0]);for(let g=0;g<p.length;g++){let[S,b]=await h;if(b!==0)return b;if(m+=p[g].length,o)o({phase:"pull",host:r.label,done:m,total:y});let E=p[g+1];if(E)h=ti(e,E);if(o)o({phase:"open",host:r.label,done:m,total:y});let P=It(S,(w)=>w.dl.head),[,x]=await Sc(t,e.bagMgrs(),n,P);if(x!==0)return x;if(i){if(o)o({phase:"exec",host:r.label,done:m,total:y});await i()}}return 0}function ai({head:e,body:t},r){let n={eid:e.eid,body:t,apld:xt};if(e.off!==0)n.off=e.off;if(e.ctr!==0)n.ctr=e.ctr;if(e.typ)n.typ=e.typ;let s=rt(r?.label);if(s!==void 0)n.rlm=s;return n}async function ci(e,{conn:t,store:r,host:n,crypto:s,onProgress:o},i){let c=n.label,[u,d]=await t.identity();if(d!==0)return;let l;try{l=await s.importVerifyKey(u.publicKey)}catch(w){console.error("Failed importing host verify key",w);return}let p=new L(e),[y,m]=p.readStructs(mr);if(m!==0){console.error("Failed decoding notif",A[m]);return}let h=!1,g=await r.hosts.get(c),S=new Map,b=[],E=!1;for(let w of y){let k=t.bagMgrs().find((F)=>Q(F.rlm,w.rlm));if(k===void 0){console.error("notif: realm",A[13]);continue}let T=k.realmKDM,[R,H]=await kr({seq:w.seq,headCph:w.headCph},l,k,s);if(H!==0){console.error("Failed decrypting notif",A[H]);continue}let C=await s.blake3(R.headEnc);if(await r.messages.has(C))continue;let K=new L(R.headEnc),[U,I]=K.readStruct(Ie);if(I!==0){console.error("Failed to parse head",A[I]);continue}if(!w.bodyCph&&U.len>0){E=!0;let F={seq:w.seq,host:c,kdm:R.kdm,head:U,headEnc:R.headEnc,headEncHash:C},W=br(T);if(W!==void 0)F.realm=W;await r.downloads.enq([F])}else b.push({...R,head:U,bodyCph:w.bodyCph,headEncHash:C,realm:T,bagMgr:k});if(!g){console.log("out of seq",w.seq,void 0),h=!0;continue}let N=ht(T),O=S.get(N);if(!O)O={realm:T,seq:_t(g,T)},S.set(N,O);if(w.seq!==O.seq+1)console.log("out of seq",w.seq,O.seq),h=!0;else O.seq=w.seq}if(g){for(let w of S.values())if(w.seq>_t(g,w.realm))await r.hosts.touch(n.label,w.seq,w.realm)}let P=[];for(let w of b){let[k,T]=await $r(w.headEnc,w.bodyCph,{decrypt:(R)=>w.bagMgr.decrypt(w.kdm,R)},s);if(T!==0){console.error("Failed to open body",A[T]);continue}P.push({key:w.headEncHash,data:ai({head:w.head,body:k.bod},w.realm)})}let x=await r.messages.add(P);for(let w=0;w<x.length;w++){let k=x[w];if(k!==0&&k!==15)console.error("ERR storing",A[k],"for message",w)}if(o&&P.length>0)o({phase:"open",host:n.label,done:P.length,total:P.length});if(h||E||P.length>0)i()}async function qn(e,t={}){let r=t.pull!==!1,n=t.push===!0,{conn:s,store:o,host:i,crypto:c,onProgress:u,peekProgressEvery:d,peekConcurrency:l}=e,[p,y]=await s.identity();if(y!==0)return a(y);let m;try{m=await c.importVerifyKey(p.publicKey)}catch{return a(29)}let h=new Map,g=0,S=d??Gt,b=l??ri,E=gt(await o.realms.list());for(let C of E){let K=s.bagMgrFor(C);if(K===void 0)return a(13);let[U,I]=await s.peek(0,C);if(I!==0)return a(I);g+=U.length;let N=U.length;if(u&&N>0)u({phase:"peek",host:i.label,done:0,total:N});let O=0,F=await Rn(U,b,async(v)=>{let[Z,re]=await kr(v,m,K,c),se;if(re!==0)se={ok:!1,seq:v.seq,stat:re};else{let z=await c.blake3(Z.headEnc);se={ok:!0,seq:v.seq,kdm:Z.kdm,headEnc:Z.headEnc,headEncHash:z}}if(O+=1,u&&Un(O,N,S))u({phase:"peek",host:i.label,done:O,total:N});return se});for(let v of F){if(!v.ok)continue;let Z=V(v.headEncHash),re=h.get(Z);if(re)re.count+=1;else h.set(Z,{hash:v.headEncHash,count:1,sample:v,realm:C})}let W=U.length>0?Math.max(...U.map((v)=>v.seq)):0;if(await o.hosts.recordSeqs(i.label,{setLastSeq:W},C),u)u({phase:"peek",host:i.label,done:N,total:N})}let P=0,x=[];for(let C of h.values()){if(C.count>1)P+=C.count-1;x.push(C.hash)}let w=h.size,k=await Ft(x,c),T=[],R=0;for(let C of h.values()){if(await o.messages.has(C.hash)){await o.uploads.deq(i.label,[C.hash]);continue}if(R+=1,!r)continue;let U=C.sample,I=new L(U.headEnc),[N,O]=I.readStruct(Ie);if(O!==0){console.error("reconcile: reading msg header",O);continue}let F={kdm:U.kdm,head:N,seq:U.seq,host:i.label,headEnc:U.headEnc,headEncHash:U.headEncHash},W=br(C.realm);if(W!==void 0)F.realm=W;T.push(F)}if(T.length>0)await o.downloads.enq(T);let H=0;if(n){let C=await o.messages.listKeys(),K=new Set(h.keys()),U=[];for(let I of C)if(!K.has(V(I)))H+=1,U.push(I);if(U.length>0)await o.uploads.enq(i.label,U)}else{let C=await o.messages.listKeys(),K=new Set(h.keys());for(let U of C)if(!K.has(V(U)))H+=1}return f({msgcheck:k,numBags:g,uniqueMsgs:w,numDupes:P,missingLocal:R,missingHost:H})}var ui=Object.freeze({label:"export",index:0});function bc(e){return e.map(({head:t,body:r})=>({...t,bod:r}))}class Nn{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;#e;applyChain=Promise.resolve();syncRuns=new Ar;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=Gt;lastProgress=Mn;scheduledSync;constructor(e,t,r,n,s,o=!0,i=Kn,c=Vn,u){this.clock=e;this.state=t;this.store=r;this.transport=n;this.crypto=s;this.forceSkewHandlingByDefault=o;this.onScheduleSync=u;this.maxPushBytes=i,this.maxPullBytes=c,this.clientState=new ze(()=>this.getClientState()),this.xferState=new ze(()=>this.getXferState()),this.scheduledSync=new vn(No,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(d){console.error("Debounced sync failed:",d)}})}emitProgress=(e)=>{this.lastProgress=e,this.xferState.emit()};selected(){return this.#e}async setSeed(e,t){let[r,n]=Fe(t?.label);if(n!==0||r===void 0)return 10;let[,s]=await this.store.account.save(e,t);if(s!==0)return s;let o=await this.#i(r,e);if(o!==0)return o;return this.clientState.emit(),0}async adopt(e,t=""){let r=await this.#i(t,e);if(r!==0)return r;return this.clientState.emit(),0}#t(){return this.#e?.enclave}async#n(){return Array.from(await this.store.hosts.list())}async#s(){if(this.#e===void 0)return;this.#e.hosts=await this.#n()}async#r(){if(this.#e===void 0)return;this.#e.realms=await this.store.realms.list()}async#i(e,t){let r=await this.store.bind(e);if(r!==0)return r;return this.#e={label:e,enclave:t,hosts:await this.#n(),realms:await this.store.realms.list()},0}async getClientState(){let{store:e,connections:t}=this,r=this.#t(),n=await e.hosts.list(),s=!1;for(let o of t.values())if(o.isConnected()){s=!0;break}return{hasSeed:r!==void 0,hasHost:Array.from(n).length>0,connected:s}}async getXferState(){let{uploads:e,downloads:t}=this.store,r=await e.count();return{numDownloads:await t.count(),numUploads:r,progress:this.lastProgress}}apply=(e,t)=>{X("apply kick",{n:e.length});let r=this.state.apply(bc(e));return this.enqueueApplyJob(()=>this.doApply(e,t,r))};async doApply(e,t={enqueueUpload:!0,triggerUpload:!0},r){let n=[],s=[];for(let{head:i,body:c}of e){let u=new q;u.writeStruct(Ie,i);let d=u.result(),l=await this.crypto.blake3(d),p={eid:i.eid,body:c,apld:xt};if(i.off!==0)p.off=i.off;if(i.ctr!==0)p.ctr=i.ctr;if(i.typ)p.typ=i.typ;n.push(l),s.push({key:l,data:p})}X("doApply archive start"),await this.store.messages.add(s),X("doApply archive done"),await oi(this.store,n,this.crypto),X("doApply await persist");let o=await r;if(X("doApply persist done"),await this.markApplyStats(n,o),t.enqueueUpload){let i=[];for(let c=0;c<n.length;c++){let u=o[c];if(u===0||u===15)i.push(n[c])}if(i.length>0){let c=await this.store.hosts.list();for(let u of c)await this.store.uploads.enq(u.label,i);this.xferState.emit()}}if(t.triggerUpload)this.scheduleSync();return o}enqueueApplyJob(e){let t=this.applyChain.then(e,e);return this.applyChain=t.then(()=>{return},()=>{return}),t}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let e=await this.store.messages.list({apld:xt});if(e.length<1)return[];let t=It(e,(r)=>r.head);return this.applyStored(t)}applyHashes=(e)=>this.enqueueApplyJob(()=>this.doApplyHashes(e));async doApplyHashes(e){let t=[];for(let s of e){let o=await this.store.messages.get(s);if(o)t.push(o)}let r=await this.applyStored(t),n=new Map;for(let s=0;s<t.length;s++)n.set(V(t[s].hash),r[s]??12);return e.map((s)=>n.get(V(s))??13)}async applyStored(e){if(e.length<1)return[];let t=e.map((n)=>({...n.head,bod:n.body})),r=await this.state.apply(t);return await this.markApplyStats(e.map((n)=>n.hash),r),r}async markApplyStats(e,t){let r=[],n=[];for(let s=0;s<e.length;s++){let o=t[s];if(o===0||o===15)r.push(e[s]);else if(o!==void 0&&ei(o))n.push({key:e[s],err:o})}if(r.length>0)await this.store.messages.markApplied(r);if(n.length>0)await this.store.messages.markFailed(n)}async insertRaw(e,t=""){X("insertRaw");let{clock:r,crypto:n}=this,s=r.now(),[o,i]=await Vo({now:s,bod:e,typ:t,crypto:n});if(i!==0)return a(i);let u=(await this.apply([{head:o,body:e}]))[0];if(u!==0&&u!==15)return a(u??12);return f(o)}async makeUpdate(e,t,r=""){let{clock:n,crypto:s}=this,o=n.now();if(e.updatedAt.getTime()>o.getTime())return a(4);let i=e.ctr+1,[c,u]=await wr({now:o,eid:e.eid,ctr:i,typ:r,bod:t,crypto:s});if(u!==0)return a(u);return f({head:c,body:t})}async updateWithSkew(e,t,r,n=""){if(r===!1)return a(4);let{clock:s,crypto:o}=this,i=s.now(),c=new L(e.eid),[u,d]=c.readStruct(ie);if(d!==0)return a(d);let l=e.updatedAt.getTime()-u.ts.getTime(),p={eid:e.eid,off:l+1,ctr:e.ctr+1,typ:"",len:0},m=(await this.apply([{head:p,body:void 0}]))[0];if(m!==0&&m!==15)return a(m??12);if(t===void 0)return f(p);let[h,g]=ct({id:u.id,ts:i});if(g!==0)return a(g);let[S,b]=await wr({now:i,eid:h,ctr:0,typ:n,bod:t,crypto:o});if(b!==0)return a(b);let P=(await this.apply([{head:S,body:t}]))[0];if(P!==0&&P!==15)return a(P??12);return f(S)}async updateRaw(e,t,r=this.forceSkewHandlingByDefault,n=""){if(X("updateRaw"),e.updatedAt.getTime()>this.clock.now().getTime())return this.updateWithSkew(e,t,r,n);let[s,o]=await this.makeUpdate(e,t,n);if(o!==0)return a(o);let c=(await this.apply([s]))[0];if(c!==0&&c!==15)return a(c??12);return f(s.head)}async insert(e){let[t,r]=mt(e);if(r!==0)return a(r);return this.insertRaw(t,e.type)}async update(e){let[t,r]=mt(e);if(r!==0)return a(r);return this.updateRaw(e.prior,t,e.force??this.forceSkewHandlingByDefault,e.type)}async delete(e){let t=e.force??!0;if("prior"in e)return this.updateRaw(e.prior,void 0,t);let[r,n]=await this.revFromArchive(e.eid);if(n!==0)return a(n);return this.updateRaw(r,void 0,t)}async insertBlob(e,t,r){let[n,s]=Qo(e,t,r);if(s!==0)return a(s);return this.insertRaw(n.bod,n.typ)}async updateBlob(e,t,r){let[n,s]=$o(await this.lastMsg(e),t,r);if(s!==0)return a(s);return this.updateRaw(n.prior,n.bod,void 0,n.typ)}deleteBlob(e){return this.delete({eid:e})}async readBlob(e){return zo(await this.lastMsg(e))}async lastMsg(e){let t=await this.store.messages.last(e);if(t===void 0)return;let r={...t.head};if(t.body!==void 0)r.bod=t.body;return r}async revFromArchive(e){let t=await this.store.messages.last(e);if(t)return qo(t.head);let r=new L(e),[n,s]=r.readStruct(ie);if(s!==0)return a(s);return f({eid:e,ctr:-1,updatedAt:n.ts})}async genEID(e){let{clock:t,crypto:r}=this,n=t.now();if(e!==void 0)return ct({id:e,ts:n});let s=await r.genRandomBytes(8);return ct({id:s,ts:n})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:e,crypto:t,store:r}=this;if(!this.#t())return 22;await this.drainApplyQueue(),await this.#r();let s=gt(this.#e?.realms??[]);for(let[o,i]of e){let c=await r.hosts.get(o);if(!c)continue;let u=await this.#o(i,c);if(u!==0)return this.emitProgress({phase:"idle"}),u;let d={conn:i,store:r,host:c,crypto:t,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};for(let y of s){let m=await On({...d,realm:y});if(m!==0)return console.error(`Failed to peek: ${m}`),this.emitProgress({phase:"idle"}),m;this.xferState.emit()}let l=await ii(d);if(l!==0)return console.error(`Failed to push: ${l}`),this.emitProgress({phase:"idle"}),l;this.xferState.emit();let p=await Ln(d,async()=>{await this.drainApplyQueue()});if(p!==0&&p!==15)return console.error(`Failed to pull: ${p}`),this.emitProgress({phase:"idle"}),p;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async rebuild(e){if(this.scheduledSync.cancel(),await this.syncRuns.flush(),e?.checkHost??!0){let r=await this.repull();if(r!==0)return r}return this.enqueueApplyJob(()=>this.replay())}async msgcheck(){let e=await this.store.messages.listKeys();return Ft(e,this.crypto)}listMsgs(e){return this.store.messages.list(e)}countMsgs(e){return this.store.messages.count(e)}async reconcile(e,t){this.scheduledSync.cancel(),await this.syncRuns.flush();let{connections:r,crypto:n,store:s}=this;if(!this.#t())return a(22);let i=await s.hosts.get(e);if(!i)return a(13);let c=r.get(e);if(!c||!c.isConnected()){if(await this.connectToHost(i,!1,!1),i=await s.hosts.get(e),!i)return a(13);c=r.get(e)}if(!c)return a(12);let u=await this.#o(c,i);if(u!==0)return a(u);let d={conn:c,store:s,crypto:n,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},[l,p]=await qn({...d,host:i},t);if(this.xferState.emit(),p!==0)return this.emitProgress({phase:"idle"}),a(p);if(!l)return this.emitProgress({phase:"idle"}),a(12);if(t?.sync===!1)return this.emitProgress({phase:"idle"}),f(l);let y=await this.sync();if(y!==0)return a(y);let m=await s.hosts.get(e);if(!m)return a(13);let[h,g]=await qn({...d,host:m},{pull:!1,push:!1});if(this.xferState.emit(),this.emitProgress({phase:"idle"}),g!==0)return a(g);if(!h)return a(12);return f(h)}async repull(){let{connections:e,crypto:t,store:r}=this;if(!this.#t())return 22;let s=Array.from(await r.hosts.list());if(s.length<1)return 0;await this.#r();let o=gt(this.#e?.realms??[]);for(let i of s){let c=e.get(i.label);if(!c||!c.isConnected())await this.connectToHost(i,!1,!1)}for(let[i,c]of e){let u=await r.hosts.get(i);if(!u)continue;let d=await this.#o(c,u);if(d!==0)return this.emitProgress({phase:"idle"}),d;let l={conn:c,store:r,host:{...u,lastSeq:0,seqs:void 0},crypto:t,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};for(let y of o){let m=await On({...l,realm:y});if(m!==0)return console.error(`rebuild: failed to peek: ${m}`),this.emitProgress({phase:"idle"}),m;this.xferState.emit()}let p=await Ln(l);if(p!==0&&p!==15)return console.error(`rebuild: failed to pull: ${p}`),this.emitProgress({phase:"idle"}),p;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async replay(){let e=await this.state.clear();if(e!==0)return e;let t=await this.store.messages.list(),r=It(t,(o)=>o.head),n=r.length;if(n<1)return this.emitProgress({phase:"idle"}),0;let s=0;while(s<r.length){let o=0,i=0,c=s;for(let d=s;d<r.length&&i<100&&o<102400;d++)o+=r[d].head.len,i++,c=d+1;let u=r.slice(s,c);await this.applyStored(u),this.emitProgress({phase:"exec",done:c,total:n}),s=c}return this.emitProgress({phase:"idle"}),0}async wipe(e){let t=e?.msgs!==!1,r=e?.ents!==!1,n=e?.meta!==!1,s=e?.seed===!0;this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush();let{store:o}=this;if(n)await o.hosts.wipe(),await o.uploads.wipe(),await o.downloads.wipe();if(t)await o.messages.wipe();if(r)await this.state.clear();if(s)await o.account.wipe(),await o.realms.wipe(),this.#e=void 0;else if(n)await this.#s(),await this.#r();this.lastProgress=Mn,this.clientState.emit(),this.xferState.emit()}import=async(e,t)=>{let{crypto:r}=this,n=t?.onProgress,s=this.#t();if(!s)return 22;console.time("import: decoding file...");let o=await e.bytes(),[i,c]=await s.bagman(ui,j);if(c!==0)return c;let[u,d]=await Ir.decodeFile(o,r,i);if(d!==0)return d;console.timeEnd("import: decoding file...");let l=0;while(l<u.length){let p=0,y=0,m=l;for(let S=l;S<u.length&&y<100&&p<102400;S++)p+=u[S].head.len,y++,m=S+1;let h=u.slice(l,m);console.time(`import: applying [${l}, ${m}]`);let g=await this.apply(h,{enqueueUpload:!0,triggerUpload:!1});console.timeEnd(`import: applying [${l}, ${m}]`);for(let S=0;S<h.length;S++){let b=g[S];if(b!==0&&b!==15)console.warn(`failed to import msg ${l+S}: ${A[b]}`)}if(n)queueMicrotask(()=>n(m,u.length,0));this.emitProgress({phase:"import",done:m,total:u.length}),l=m}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:e,store:t}=this,r=this.#t();if(!r)return a(22);let[n,s]=await r.bagman(ui,j);if(s!==0)return a(s);let o=await t.messages.list();return Ir.encodeFile(o,e,n)}async export(e){let[t,r]=await this.exportBytes();if(r!==0)return r;if(!t)return 12;let n=new Blob([t.slice()]);return Yo(n,e),0}async link(e,t=!0){if(await this.store.hosts.add(e),await this.#s(),await this.#r(),this.clientState.emit(),t){let r=await this.store.hosts.get(e.label);if(r)await this.connectToHost(r)}}async unlink(e){await this.store.hosts.del(e),await this.#s(),await this.#r(),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async(e,t=!0,r=!0)=>{let{clock:n,connections:s,crypto:o,store:i,transport:c}=this,u=s.get(e.label);if(u){if(u.isConnected())return;try{u.closeListener()}catch{}s.delete(e.label)}if(!this.#t())return;console.info(`Connecting to ${e.handle} (${e.label})`);let l=new gr([],o,n,c(e),async(y)=>{let m=await i.hosts.set(e.label,y);return await this.#s(),await this.#r(),m});if(await this.#o(l,e)!==0)return;if(await l.register(),t)await l.listen(async(y)=>{if(await this.#o(l,e)!==0)return;let h={conn:l,store:i,host:e,crypto:o,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return ci(y,h,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(s.set(e.label,l),this.clientState.emit(),r)this.scheduleSync()};async#o(e,t){let r=this.#t();if(!r)return 22;let n={label:t.label,index:t.idx??0},s=gt(await this.store.realms.list());for(let o of s){if(e.bagMgrFor(o)!==void 0)continue;let[i,c]=await r.bagman(n,o);if(c!==0)return c;e.add(i)}return 0}async connect(e=!0,t=!0){let{connectToHost:r,scheduleSync:n,store:s}=this;if(!this.#t())return;await this.drainApplyQueue();let i=await s.hosts.list();for(let c of i)await r(c,e,!1);if(t)n()}disconnect=async()=>{for(let e of this.connections.values())try{e.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}yt();var Pt=bo;ae();D();function di(e,t){if(e===null||t===null||typeof e!=="object"||typeof t!=="object")return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}M();ae();D();$t();M();$t();fe();D();ae();Wt();M();Jn();Dt();var Oc=8;class Wr{#e;#t;#n;#s;#r;#i;#o;constructor(e){this.#r=e.persistKeyring,this.#n={rpId:e.rpId,rpName:e.rpName},this.#s=e.userName??e.rpId??e.rpName??zt,this.#i=e.unlockAccount}static open(e){let t=new Wr(e);if(e.keyring===void 0)return f(t);let[r,n]=Yt(e.keyring);if(n!==0)return a(n);return t.#t=r,f(t)}get keyring(){if(this.#t===void 0)return;let[e,t]=Yt(this.#t);if(t!==0)return;return e}list(){if(this.#t===void 0)return[];return this.#t.entries.map(_c)}async save(e,t){let r=this.#e!==void 0||this.#t!==void 0&&this.#t.entries.length>0,[n,s]=Ho(this.#o,t?.label,r);if(s!==0||n===void 0)return a(10);if(t?.persist===!0)return a(10);return this.#o=n,this.#e=e,f(this.#e)}async bindAndSave(e,t){let r=this.#t,n=t?.credId,s=n instanceof Uint8Array?n.byteLength>0:n!==void 0&&n.length>0;if(!s&&r!==void 0&&r.entries.length>=Oc)return a(26);let o=Gi(t?.nick),i=t?.excludeCredentials??(s?void 0:Fc(r)),c=t?.salt??r?.salt,u=r===void 0?void 0:r.entries.map((b)=>({credId:b.credId,tag:b.tag})),[d,l]=await e.bind({...this.#n,salt:c,credId:n,createCredIfNeeded:t?.createCredIfNeeded??!s,excludeCredentials:i,userName:this.#s,displayName:o??this.#n.rpName??this.#s,authenticatorAttachment:t?.authenticatorAttachment,hints:t?.hints},u);if(l!==0)return a(l);let p=Date.now(),y={type:"prf",sealedMaster:d.sealedMaster,credId:d.credId,tag:d.tag,userId:d.userId,nick:o,enrolledAt:p,lastUsedAt:p,attachment:d.attachment,transports:d.transports,aaguid:d.aaguid,enrolledOs:Lc()},m=r===void 0?{salt:d.salt.slice(),entries:[]}:r,[h,g]=Wc(m,y);if(g!==0)return a(g);let S=await this.#r(h);if(S!==0)return a(S);return this.#t=h,this.#e=e,f(this.#e)}async load(){return this.#e}async unlock(){let e=this.#i;if(e!==void 0){let[i,c]=await e();if(c!==0)return a(c);if(i===void 0)return a(13);if(i.keyring===void 0)this.#t=void 0;else{let[u,d]=Yt(i.keyring);if(d!==0)return a(d);this.#t=u}return this.#e=i.enclave,f(i.enclave)}let t=this.#t;if(t===void 0||t.entries.length===0)return a(22);let[r,n]=await pe.unsealWithPasskey(t.entries.map((i)=>({sealedMaster:i.sealedMaster,credId:i.credId})),{...this.#n,salt:t.salt});if(n!==0)return a(n);this.#e=r.enclave;let[s,o]=es(t,r.credId);if(o!==0)return a(o);if(s!==void 0){let i=await this.#r(s);if(i!==0)return a(i);this.#t=s}return f(r.enclave)}async rename(e,t){let r=this.#t;if(r===void 0)return a(22);let n=r.entries.findIndex((l)=>Q(l.credId,e));if(n<0)return a(13);let[s,o]=Jt(r.entries);if(o!==0)return a(o);let i=s[n];if(i===void 0)return a(13);let c=Gi(t);s[n]={...i,nick:c};let u={salt:r.salt.slice(),entries:s},d=await this.#r(u);if(d!==0)return a(d);return this.#t=u,f(void 0)}async remove(e){let t=this.#t;if(t===void 0)return a(22);let r=t.entries.filter((c)=>!Q(c.credId,e));if(r.length===t.entries.length)return a(13);if(r.length===0){let c=await this.#r(void 0);if(c!==0)return a(c);return this.#t=void 0,f(void 0)}let[n,s]=Jt(r);if(s!==0)return a(s);let o={salt:t.salt.slice(),entries:n},i=await this.#r(o);if(i!==0)return a(i);return this.#t=o,f(void 0)}async wipe(){this.#e=void 0,this.#t=void 0,this.#o=void 0,await this.#r(void 0)}}function Gi(e){if(e===void 0)return;let t=e.trim();return t===""?void 0:t}function Lc(){if(typeof navigator>"u")return;return xi(navigator.userAgent)}function qc(e){let[t,r]=tt(e.sealedMaster.slice());if(r!==0)return a(r);let[n,s]=Ne(e.tag.slice(),te.BindTag);if(s!==0)return a(s);return f({type:"prf",sealedMaster:t,credId:e.credId.slice(),tag:n,userId:e.userId===void 0?void 0:e.userId.slice(),nick:e.nick,enrolledAt:e.enrolledAt,lastUsedAt:e.lastUsedAt,attachment:e.attachment,transports:e.transports===void 0?void 0:[...e.transports],aaguid:e.aaguid===void 0?void 0:e.aaguid.slice(),enrolledOs:e.enrolledOs})}function Jt(e){let t=[];for(let r of e){let[n,s]=qc(r);if(s!==0)return a(s);t.push(n)}return f(t)}function Yt(e){let[t,r]=Jt(e.entries);if(r!==0)return a(r);return f({salt:e.salt.slice(),entries:t})}function Qi(e){return e!==null&&typeof e==="object"}function Nc(e){if(!Qi(e)||e.type!=="prf")return;if(!(e.sealedMaster instanceof Uint8Array)||!(e.credId instanceof Uint8Array)||!(e.tag instanceof Uint8Array)||typeof e.enrolledAt!=="number"||!Number.isFinite(e.enrolledAt))return;let[t,r]=tt(e.sealedMaster);if(r!==0)return;let[n,s]=Ne(e.tag.slice(),te.BindTag);if(s!==0)return;let o=e.attachment==="platform"||e.attachment==="cross-platform"?e.attachment:void 0,i=e.enrolledOs,c=i==="ios"||i==="macos"||i==="android"||i==="windows"||i==="linux"||i==="other"?i:void 0,u=Array.isArray(e.transports)?e.transports.filter((d)=>typeof d==="string"):void 0;return{type:"prf",sealedMaster:t,credId:e.credId.slice(),tag:n,userId:e.userId instanceof Uint8Array?e.userId.slice():void 0,nick:typeof e.nick==="string"?e.nick:void 0,enrolledAt:e.enrolledAt,lastUsedAt:typeof e.lastUsedAt==="number"&&Number.isFinite(e.lastUsedAt)?e.lastUsedAt:void 0,attachment:o,transports:u===void 0||u.length===0?void 0:u,aaguid:e.aaguid instanceof Uint8Array?e.aaguid.slice():void 0,enrolledOs:c}}function $i(e){if(!Qi(e))return;if(!(e.salt instanceof Uint8Array)||!Array.isArray(e.entries))return;let t=[];for(let r of e.entries){let n=Nc(r);if(n!==void 0)t.push(n)}if(t.length===0)return;return{salt:e.salt.slice(),entries:t}}function _c(e){return{type:"prf",credId:e.credId.slice(),userId:e.userId===void 0?void 0:e.userId.slice(),nick:e.nick,enrolledAt:e.enrolledAt,lastUsedAt:e.lastUsedAt,attachment:e.attachment,transports:e.transports===void 0?void 0:[...e.transports],aaguid:e.aaguid===void 0?void 0:e.aaguid.slice(),enrolledOs:e.enrolledOs}}function Fc(e){if(e===void 0)return[];return e.entries.filter((t)=>t.credId.byteLength>0).map((t)=>t.credId.slice())}function Wc(e,t){let[r,n]=Jt(e.entries);if(n!==0)return a(n);let s=r.findIndex((o)=>Q(o.credId,t.credId));if(s>=0){let o=r[s];r[s]={...t,enrolledAt:o?.enrolledAt??t.enrolledAt,nick:t.nick??o?.nick}}else r.push(t);return f({salt:e.salt.slice(),entries:r})}function es(e,t){if(t.byteLength===0)return f(void 0);let r=e.entries.findIndex((i)=>Q(i.credId,t));if(r<0)return f(void 0);let[n,s]=Jt(e.entries);if(s!==0)return a(s);let o=n[r];if(o===void 0)return a(13);return n[r]={...o,lastUsedAt:Date.now()},f({salt:e.salt.slice(),entries:n})}var jg=jr("fbfc3007154e4ecc8c0b6e020557d7bd"),Xg=jr("ea9b8d664d011d213ce4b6b48cb575d4"),Gg=jr("08987058cadc4b81b6e130de50dcbe96"),Qg=jr("2fc0579f811347eab116bb5a8db9202a");function jr(e){let t=new Uint8Array(16);for(let r=0;r<16;r++)t[r]=Number.parseInt(e.slice(r*2,r*2+2),16);return t}D();fe();M();async function zi(e,t){let[r,n]=await e.fingerprint(t);if(n!==0)return a(n);return Ne(r.slice(),te.Fingerprint)}async function Yi(e,t){let r=await e.gen256BitSecureRandomSeed(),[n,s]=await zi(t,r);if(s!==0)return a(s);return f({n:r,h:n})}async function ts(e,t){let[r,n]=await zi(e,t.n);if(n!==0)return!1;return jc(r,t.h)}function Ji(e){if(e===void 0||e===null||typeof e!=="object")return;let t=e;if(!(t.n instanceof Uint8Array)||!(t.h instanceof Uint8Array))return;if(t.n.byteLength<1)return;let[r,n]=Ne(t.h.slice(),te.Fingerprint);if(n!==0)return;return{n:t.n.slice(),h:r}}function Zi(e){let t=e.n.slice(),[r,n]=Ne(e.h.slice(),te.Fingerprint);if(n!==0)return{n:t,h:e.h};return{n:t,h:r}}function jc(e,t){if(e.byteLength!==t.byteLength)return!1;let r=0;for(let n=0;n<e.byteLength;n++)r|=e[n]^t[n];return r===0}function rs(e){if(e===""||typeof indexedDB>"u")return Promise.resolve();return new Promise((t,r)=>{let n=indexedDB.deleteDatabase(e);n.onsuccess=()=>t(),n.onerror=()=>r(n.error??Error(`[DIPLOMATIC] deleteDatabase failed (${e})`)),n.onblocked=()=>{console.warn(`[DIPLOMATIC] deleteDatabase blocked (${e})`)}})}function ns(e,t,r){return new Promise((n,s)=>{let o=indexedDB.open(e,t);o.onupgradeneeded=()=>{let{result:i,transaction:c}=o;if(c===null){s(Error(`[DIPLOMATIC] missing upgrade transaction (${e})`));return}try{r(i,c)}catch(u){s(u instanceof Error?u:Error(String(u)))}},o.onblocked=()=>{console.warn(`[DIPLOMATIC] IDB upgrade blocked (${e} → v${t})`)},o.onsuccess=()=>{let i=o.result;i.onversionchange=()=>{i.close()},n(i)},o.onerror=()=>{s(o.error??Error(`[DIPLOMATIC] IDB open failed (${e})`))}})}ae();var ea="meta",ta=1,ra=9;function Xc(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Ye(e)}function Gc(e){return`data-${e}`}function Qc(e){return`ents-${e}`}function ss(e,t){let r=e!==void 0&&e!==""?e:Xc();if(t!==void 0&&t!=="")return{acct:r,data:t};return{acct:r,data:Gc(r)}}function na(e,t){if(t!==void 0&&t!=="")return t;return Qc(e)}D();M();class os{db;constructor(e){this.db=e}async enq(e){let t=[...e];if(t.length===0)return;let r=this.db.transaction(Se,"readwrite"),n=r.objectStore(Se);return new Promise((s,o)=>{r.oncomplete=()=>s(),r.onerror=()=>o(r.error);for(let i of t)n.put(i,Pn(i.host,i.seq,i.realm))})}async deq(e,t,r){let n=[...t];if(n.length===0)return;let s=this.db.transaction(Se,"readwrite"),o=s.objectStore(Se);return new Promise((i,c)=>{s.oncomplete=()=>i(),s.onerror=()=>c(s.error);for(let u of n)o.delete(Pn(e,u,r))})}async list(){let t=this.db.transaction(Se,"readonly").objectStore(Se);return new Promise((r,n)=>{let s=t.getAll();s.onsuccess=()=>r(s.result),s.onerror=()=>n(s.error)})}async count(){let t=this.db.transaction(Se,"readonly").objectStore(Se);return new Promise((r,n)=>{let s=t.count();s.onsuccess=()=>r(s.result),s.onerror=()=>n(s.error)})}async wipe(){let e=this.db.transaction(Se,"readwrite"),t=e.objectStore(Se);return new Promise((r,n)=>{e.oncomplete=()=>r(),e.onerror=()=>n(e.error),t.clear()})}}D();fe();function is(e){return e!==null&&typeof e==="object"}function as(e){if(!is(e))return!1;return typeof e.host==="string"&&typeof e.label==="string"&&typeof e.index==="number"&&Number.isInteger(e.index)&&typeof e.lastSeq==="number"&&Number.isInteger(e.lastSeq)&&e.lastSeq>=0}function $c(e){let t=[];if(!Array.isArray(e))return t;for(let r of e){if(!as(r))continue;t.push({label:r.label,index:r.index,lastSeq:r.lastSeq})}return t}function zc(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!as(r))continue;let n=t.get(r.host)??[];n.push({label:r.label,index:r.index,lastSeq:r.lastSeq}),t.set(r.host,n)}return t}function sa(e,t){let r=To(t),n={label:e.label,handle:new URL(e.handle),idx:e.idx,lastSeq:r.lastSeq,clockOffset:e.clockOffset,subscription:e.subscription};if(r.seqs!==void 0)n.seqs=r.seqs;return n}function oa(e){let t={label:e.label,handle:e.handle.toString()};if(e.idx!==void 0)t.idx=e.idx;if(e.clockOffset!==void 0)t.clockOffset=e.clockOffset;if(e.subscription!==void 0)t.subscription=e.subscription;return t}class cs{db;constructor(e){this.db=e}async add(e){let t=await this.get(e.label),r=t!==void 0&&t.handle.href===e.handle.href&&(t.idx??0)===(e.idx??0),n=oa(r&&t!==void 0?{...e,clockOffset:t.clockOffset,subscription:t.subscription}:e),s=this.db.transaction([ue,ye],"readwrite"),o=s.objectStore(ue),i=s.objectStore(ye);return new Promise((c,u)=>{if(s.oncomplete=()=>c(),s.onerror=()=>u(s.error),r){o.put(n);return}let d=i.index("host").getAllKeys(e.label);d.onsuccess=()=>{for(let l of d.result)i.delete(l);o.put(n)}})}async touch(e,t,r){return this.recordSeqs(e,{lastSeq:t},r)}async recordSeqs(e,t,r){let n=r??j,s=this.db.transaction([ue,ye],"readwrite"),o=s.objectStore(ue),i=s.objectStore(ye),c=[e,n.label,n.index];return new Promise((u,d)=>{s.oncomplete=()=>u(),s.onerror=()=>d(s.error);let l=o.get(e);l.onsuccess=()=>{if(!l.result)return;let p=i.get(c);p.onsuccess=()=>{let y=p.result,m=as(y)?y.lastSeq:0,h=Ro(m,t);if(h===void 0)return;i.put({host:e,label:n.label,index:n.index,lastSeq:h})}}})}async get(e){let t=this.db.transaction([ue,ye],"readonly"),r=t.objectStore(ue),n=t.objectStore(ye);return new Promise((s,o)=>{t.onerror=()=>o(t.error);let i,c,u=2,d=()=>{if(u-=1,u>0)return;if(!is(i)){s(void 0);return}s(sa(i,$c(c)))},l=r.get(e);l.onsuccess=()=>{i=l.result,d()};let p=n.index("host").getAll(e);p.onsuccess=()=>{c=p.result,d()}})}async set(e,t){let r=await this.get(e);if(!r)return 13;try{return await this.put(oa({...r,...t})),0}catch{return 18}}async del(e){let t=this.db.transaction([ue,ye],"readwrite"),r=t.objectStore(ue),n=t.objectStore(ye);return new Promise((s,o)=>{t.oncomplete=()=>s(),t.onerror=()=>o(t.error),r.delete(e);let i=n.index("host").getAllKeys(e);i.onsuccess=()=>{for(let c of i.result)n.delete(c)}})}async list(){let e=this.db.transaction([ue,ye],"readonly"),t=e.objectStore(ue),r=e.objectStore(ye);return new Promise((n,s)=>{e.onerror=()=>s(e.error);let o,i,c=2,u=()=>{if(c-=1,c>0)return;let p=zc(i),y=[];if(Array.isArray(o))for(let m of o){if(!is(m)||typeof m.label!=="string")continue;y.push(sa(m,p.get(m.label)??[]))}n(y)},d=t.getAll();d.onsuccess=()=>{o=d.result,u()};let l=r.getAll();l.onsuccess=()=>{i=l.result,u()}})}async wipe(){let e=this.db.transaction([ue,ye],"readwrite"),t=e.objectStore(ue),r=e.objectStore(ye);return new Promise((n,s)=>{e.oncomplete=()=>n(),e.onerror=()=>s(e.error),t.clear(),r.clear()})}put(e){let t=this.db.transaction(ue,"readwrite"),r=t.objectStore(ue);return new Promise((n,s)=>{t.oncomplete=()=>n(),t.onerror=()=>s(t.error),r.put(e)})}}function ds(){return ns(ea,ta,(e)=>{if(!e.objectStoreNames.contains(we))e.createObjectStore(we,{keyPath:"label"})})}function ls(e){return ns(e,ra,Yc)}function Yc(e,t){if(!e.objectStoreNames.contains(ue))e.createObjectStore(ue,{keyPath:"label"});if(!e.objectStoreNames.contains(be))e.createObjectStore(be,{keyPath:["host","hash"]});if(!e.objectStoreNames.contains(Se))e.createObjectStore(Se);let r;if(!e.objectStoreNames.contains(J))r=e.createObjectStore(J);else r=t.objectStore(J);if(!r.indexNames.contains(vt))r.createIndex(vt,"apld",{unique:!1});if(!r.indexNames.contains(us))r.createIndex(us,"rlm",{unique:!1});if(!e.objectStoreNames.contains(xe))e.createObjectStore(xe,{keyPath:"label"});if(!e.objectStoreNames.contains(ye))e.createObjectStore(ye,{keyPath:["host","label","index"]}).createIndex("host","host",{unique:!1})}ae();D();class fs{db;crypto;constructor(e,t){this.db=e;this.crypto=t}async add(e){let t=this.db.transaction(J,"readwrite"),r=t.objectStore(J);return new Promise((n)=>{if(e.length===0){n([]);return}let s=Array(e.length).fill(0);t.oncomplete=()=>n(s),t.onerror=()=>{for(let o=0;o<s.length;o++)s[o]=18;n(s)};for(let o=0;o<e.length;o++){let{key:i,data:c}=e[o],u=V(i),d=r.put(Dr(c),u);d.onerror=(l)=>{l.preventDefault(),s[o]=18}}})}async del(e){let t=[...e];if(t.length===0)return;let r=this.db.transaction(J,"readwrite"),n=r.objectStore(J);return new Promise((s,o)=>{r.oncomplete=()=>s(),r.onerror=()=>o(r.error);for(let i of t){let c=V(i);n.delete(c)}})}async get(e){let r=this.db.transaction(J,"readonly").objectStore(J);return new Promise((n,s)=>{let o=V(e),i=r.get(o);i.onsuccess=async()=>{let c=i.result;if(c)n(await Mr(e,c,this.crypto));else n(void 0)},i.onerror=()=>s(i.error)})}async has(e){return await this.get(e)!==void 0}async list(e){let t=e?.apld,r=e?.body!==!1,s=this.db.transaction(J,"readonly").objectStore(J);return new Promise((o,i)=>{let c=[],u=t===void 0?s.openCursor():s.index(vt).openCursor(IDBKeyRange.only(t));u.onsuccess=(d)=>{let l=d.target.result;if(l){let p=t===void 0?l.key:l.primaryKey,y=l.value;c.push({hash:Ee(p),data:y}),l.continue()}else Promise.all(c.map(({hash:p,data:y})=>Mr(p,y,this.crypto,{body:r}))).then(o).catch(i)},u.onerror=()=>i(u.error)})}async count(e){let r=this.db.transaction(J,"readonly").objectStore(J);return new Promise((n,s)=>{let o=e===void 0?r.count():r.index(vt).count(IDBKeyRange.only(e));o.onsuccess=()=>n(o.result),o.onerror=()=>s(o.error)})}async listKeys(){let t=this.db.transaction(J,"readonly").objectStore(J);return new Promise((r,n)=>{let s=[],o=t.openKeyCursor();o.onsuccess=(i)=>{let c=i.target.result;if(c)s.push(Ee(c.key)),c.continue();else r(s)},o.onerror=()=>n(o.error)})}async last(e){let r=this.db.transaction(J,"readonly").objectStore(J);return new Promise((n,s)=>{let o,i=r.openCursor();i.onsuccess=async(c)=>{let u=c.target.result;if(u){let{key:d,value:l}=u;if(Q(e,l.eid)){if(!o||(l.ctr??0)>(o.data.ctr??0)||(l.ctr??0)===(o.data.ctr??0)&&(l.off??0)>(o.data.off??0))o={key:d,data:l}}u.continue()}else if(o){let d=Ee(o.key);n(await Mr(d,o.data,this.crypto))}else n(void 0)},i.onerror=()=>s(i.error)})}async markApplied(e){let t=[...e];if(t.length===0)return;let r=this.db.transaction(J,"readwrite"),n=r.objectStore(J);return new Promise((s,o)=>{r.oncomplete=()=>s(),r.onerror=()=>o(r.error);for(let i of t){let c=V(i),u=n.get(c);u.onsuccess=()=>{let d=u.result;if(!d)return;Hn(d,vr),n.put(d,c)},u.onerror=(d)=>{d.preventDefault()}}})}async markFailed(e){let t=[...e];if(t.length===0)return;let r=this.db.transaction(J,"readwrite"),n=r.objectStore(J);return new Promise((s,o)=>{r.oncomplete=()=>s(),r.onerror=()=>o(r.error);for(let{key:i,err:c}of t){let u=V(i),d=n.get(u);d.onsuccess=()=>{let l=d.result;if(!l)return;Hn(l,wt,c),n.put(l,u)},d.onerror=(l)=>{l.preventDefault()}}})}async wipe(){let e=this.db.transaction(J,"readwrite"),t=e.objectStore(J);return new Promise((r,n)=>{e.oncomplete=()=>r(),e.onerror=()=>n(e.error),t.clear()})}}D();class ps{db;constructor(e){this.db=e}async list(){let t=this.db.transaction(xe,"readonly").objectStore(xe);return new Promise((r,n)=>{let s=t.getAll();s.onsuccess=()=>{let o=s.result,i=[];if(Array.isArray(o))for(let c of o){let u=Br(c);if(u!==void 0)i.push(u)}r(i)},s.onerror=()=>n(s.error)})}async get(e){let r=this.db.transaction(xe,"readonly").objectStore(xe);return new Promise((n,s)=>{let o=r.get(e);o.onsuccess=()=>n(Br(o.result)),o.onerror=()=>s(o.error)})}async put(e,t){let r=this.db.transaction(xe,"readwrite"),n=r.objectStore(xe);return new Promise((s,o)=>{let i=0;r.oncomplete=()=>s(i),r.onerror=()=>o(r.error);let c=n.get(e);c.onsuccess=()=>{let[u,d]=Zo(e,Br(c.result),t);if(d!==0){i=d;return}n.put(u)}})}async wipe(){let e=this.db.transaction(xe,"readwrite"),t=e.objectStore(xe);return new Promise((r,n)=>{e.oncomplete=()=>r(),e.onerror=()=>n(e.error),t.clear()})}}ae();class ys{db;constructor(e){this.db=e}async enq(e,t){let r=[...t];if(r.length===0)return;let n=this.db.transaction(be,"readwrite"),s=n.objectStore(be);return new Promise((o,i)=>{n.oncomplete=()=>o(),n.onerror=()=>i(n.error);for(let c of r){let u=Ye(c);s.put({host:e,hash:u})}})}async deq(e,t){let r=[...t];if(r.length===0)return;let n=this.db.transaction(be,"readwrite"),s=n.objectStore(be);return new Promise((o,i)=>{n.oncomplete=()=>o(),n.onerror=()=>i(n.error);for(let c of r){let u=Ye(c);s.delete([e,u])}})}async list(e){let r=this.db.transaction(be,"readonly").objectStore(be);return new Promise((n,s)=>{let o=r.getAll();o.onsuccess=()=>{let c=o.result.filter((u)=>u.host===e).map((u)=>u.hash);n(c.map((u)=>vs(u)))},o.onerror=()=>s(o.error)})}async count(){let t=this.db.transaction(be,"readonly").objectStore(be);return new Promise((r,n)=>{let s=t.count();s.onsuccess=()=>r(s.result),s.onerror=()=>n(s.error)})}async wipe(){let e=this.db.transaction(be,"readwrite"),t=e.objectStore(be);return new Promise((r,n)=>{e.oncomplete=()=>r(),e.onerror=()=>n(e.error),t.clear()})}}var we="accounts",ue="hosts",ye="host_seqs",be="uploadQueue",Se="downloadQueue",J="messages",vt="apld",us="rlm",xe="realms";function Jc(e,t){return{realms:new ps(e),hosts:new cs(e),uploads:new ys(e),downloads:new os(e),messages:new fs(e,t)}}function ia(){return{realms:{async list(){return[]},async get(){return},async put(){return 13},async wipe(){}},hosts:{async add(){},async get(){return},async del(){},async set(){return 13},async list(){return[]},async wipe(){},async touch(){},async recordSeqs(){}},uploads:{async enq(){},async deq(){},async list(){return[]},async count(){return 0},async wipe(){}},downloads:{async enq(){},async deq(){},async list(){return[]},async count(){return 0},async wipe(){}},messages:{async add(e){return e.map(()=>18)},async get(){return},async has(){return!1},async del(){},async list(){return[]},async count(){return 0},async listKeys(){return[]},async last(){return},async markApplied(){},async markFailed(){},async wipe(){}}}}class aa{account;realms;hosts;uploads;downloads;messages;#e;#t;#n;constructor(e,t,r,n){this.account=e,this.#t=t,this.#n=r;let s=ia();if(this.realms=s.realms,this.hosts=s.hosts,this.uploads=s.uploads,this.downloads=s.downloads,this.messages=s.messages,n!==void 0)this.#s(n)}#s(e){let t=this.#e;if(this.#e=e,e.onversionchange=()=>{if(this.#e!==e)return;this.#r()},this.#i(Jc(e,this.#t)),t!==void 0&&t!==e)t.close()}#r(){let e=this.#e;if(this.#e=void 0,this.#i(ia()),e!==void 0)e.close()}#i(e){this.realms=e.realms,this.hosts=e.hosts,this.uploads=e.uploads,this.downloads=e.downloads,this.messages=e.messages}async bind(e){if(this.#n===void 0)return this.#e===void 0?13:0;let t=await this.#n(e);if(t===void 0)return 13;if(this.#e!==void 0&&this.#e.name===t)return 0;let r=await ls(t);return this.#s(r),0}async prepareWorker(e){let t=await this.#n?.(e);if(t===void 0)return a(13);if(!(this.account instanceof Zt))return a(10);let r=await this.account.ensureEnts(e);return f({data:t,ents:r})}close(){this.#r()}async wipe(){await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function ca(e,t){let r=await ls(t);return new aa({async save(){return a(10)},async wipe(){}},e,void 0,r)}function ua(e){return e!==null&&typeof e==="object"}function ms(e,t){let r=e[t];if(typeof r!=="string"||r==="")return;return r}function Zc(e,t){if(e===void 0)return t;if(t.acct===void 0)t.acct=e.acct;if(t.data===void 0)t.data=e.data;if(t.ents===void 0)t.ents=e.ents;return t}function hs(e){if(!ua(e)||typeof e.label!=="string")return;let t={label:e.label},r=ms(e,"acct"),n=ms(e,"data"),s=ms(e,"ents");if(r!==void 0)t.acct=r;if(n!==void 0)t.data=n;if(s!==void 0)t.ents=s;let o=Ji(e.keyTag),i=$i(e.keyring);if(o!==void 0)t.keyTag=o;if(i!==void 0)t.keyring=i;return t}function eu(e){let t=[];for(let r of e){let n=r.keyring;if(n===void 0)continue;for(let s of n.entries){if(s.credId.byteLength===0)continue;let o=!1;for(let i of t){if(!Q(i.credId,s.credId))continue;if(i.label!==r.label)return a(10);o=!0;break}if(o)continue;t.push({label:r.label,salt:n.salt,sealedMaster:s.sealedMaster,credId:s.credId})}}return f(t)}function tu(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){let n=hs(r);if(n!==void 0)t.push(n)}return t}function ru(e,t,r,n){let s={label:t.label};if(t.acct!==void 0)s.acct=t.acct;if(t.data!==void 0)s.data=t.data;if(t.ents!==void 0)s.ents=t.ents;if(r!==void 0)s.keyTag=r;if(n!==void 0)s.keyring=n;e.put(s)}class Zt{db;#e;#t;constructor(e,t){this.db=e,this.#e=t}setCloser(e){this.#t=e}async create(e,t){let[r,n]=Fe(e);if(n!==0||r===void 0)return t.fill(0),a(10);if((await this.#r(r))?.keyTag!==void 0)return t.fill(0),a(19);if(t.byteLength<Fr)return t.fill(0),a(10);let[o,i]=await pe.fromRandom(t);if(i!==0)return a(i);return this.save(o,{label:r})}async save(e,t){let[r,n]=Fe(t?.label);if(n!==0||r===void 0)return a(10);let s=await this.#n(e,r);if(s!==0)return a(s);return f(e)}async dataName(e){let t=await this.#r(e);if(t===void 0)return;if(t.data!==void 0&&t.data!=="")return t.data;return await this.#o(e,(n)=>{if(n===void 0)return;return{...n}}),(await this.#r(e))?.data}async ensureEnts(e){let[t,r]=Fe(e);if(r!==0||t===void 0)throw Error("[DIPLOMATIC] invalid account label");let n=await this.#r(t),s=ss(n?.acct,n?.data),o=na(s.acct,n?.ents);return await this.#o(t,(i)=>({...i===void 0?{label:t}:{...i},acct:s.acct,data:s.data,ents:o})),o}async wipe(){let e=await this.#i();this.#t?.();for(let n of e){if(n.data!==void 0)await rs(n.data);if(n.ents!==void 0)await rs(n.ents)}let t=this.db.transaction(we,"readwrite"),r=t.objectStore(we);return new Promise((n,s)=>{t.oncomplete=()=>n(),t.onerror=()=>s(t.error),r.clear()})}async loadKeyring(e){let[t,r]=await this.#s(e);if(r!==0||t===void 0)return;return(await this.#r(t))?.keyring}async persistKeyring(e,t){let r;if(e!==void 0){let[o,i]=Yt(e);if(i!==0)return i;r=o}let[n,s]=await this.#s(t);if(s!==0)return s;if(n===void 0)return 13;return await this.#o(n,(o)=>{if(r===void 0){if(o?.keyTag===void 0)return;return{label:n,keyTag:o.keyTag}}let i={label:n,keyring:r};if(o?.keyTag!==void 0)i.keyTag=o.keyTag;return i}),0}async hasKeyring(e){let t=await this.loadKeyring(e);return t!==void 0&&t.entries.length>0}async unlock(e){let[t,r]=eu(await this.#i());if(r!==0)return a(r);if(t===void 0||t.length===0)return a(22);let n=t[0];if(n===void 0)return a(22);let[s,o]=await pe.unsealWithPasskey(t.map((y)=>({sealedMaster:y.sealedMaster,credId:y.credId,salt:y.salt})),{rpId:e.rpId,rpName:e.rpName,salt:n.salt});if(o!==0)return a(o);if(s===void 0)return a(20);let i=t.find((y)=>Q(y.credId,s.credId));if(i===void 0)return a(13);let c=await this.#r(i.label),u=c?.keyTag;if(u!==void 0){if(!await ts(s.enclave,u))return a(19)}let d=c?.keyring;if(d===void 0)return a(13);let[l,p]=es(d,s.credId);if(p!==0)return a(p);if(l!==void 0)await this.#o(i.label,(y)=>{let m={label:i.label,keyring:l};if(y?.keyTag!==void 0)m.keyTag=y.keyTag;return m});return f({enclave:s.enclave,label:i.label})}async openPrfStore(e,t){let[r,n]=await this.#s(t),s=n===0?await this.loadKeyring(r):void 0,o=n===0?r:void 0;return Wr.open({rpId:e.rpId,rpName:e.rpName,userName:e.userName,keyring:s,persistKeyring:(i)=>this.persistKeyring(i,o),unlockAccount:async()=>{let[i,c]=await this.unlock(e);if(c!==0)return a(c);if(i===void 0)return a(13);return o=i.label,f({enclave:i.enclave,keyring:await this.loadKeyring(i.label)})}})}async#n(e,t){let r=await this.#r(t);if(r?.keyTag!==void 0){if(!await ts(e,r.keyTag))return 19;return 0}let[n,s]=await Yi(this.#e,e);if(s!==0)return s;let o=Zi(n),i=!1;if(await this.#o(t,(c)=>{if(c?.keyTag!==void 0)return i=!0,c;let u={label:t,keyTag:o};if(c?.keyring!==void 0)u.keyring=c.keyring;return u}),!i)return 0;return this.#n(e,t)}async#s(e){if(e!==void 0){let[n,s]=Fe(e);if(s!==0||n===void 0)return a(10);return f(n)}let t=await this.#i(),r=t.length===1?t[0]:void 0;if(r!==void 0)return f(r.label);if(t.length===0)return a(13);return a(10)}#r(e){let r=this.db.transaction(we,"readonly").objectStore(we);return new Promise((n,s)=>{let o=r.get(e);o.onsuccess=()=>n(hs(o.result)),o.onerror=()=>s(o.error)})}#i(){let t=this.db.transaction(we,"readonly").objectStore(we);return new Promise((r,n)=>{let s=t.getAll();s.onsuccess=()=>r(tu(s.result)),s.onerror=()=>n(s.error)})}async#o(e,t){let r=this.db.transaction(we,"readwrite"),n=r.objectStore(we);return new Promise((s,o)=>{r.oncomplete=()=>s(),r.onerror=()=>o(r.error);let i=n.get(e);i.onsuccess=()=>{let c=ua(i.result)?i.result:void 0,u=hs(i.result),d=t(u);if(d===void 0){if(u!==void 0)n.delete(e);return}let l=Zc(u,d===u?{...d}:d),p=ss(l.acct,l.data);if(l.acct=p.acct,l.data=p.data,d===u&&u?.acct===l.acct&&u?.data===l.data&&u?.ents===l.ents)return;let y=void 0;if(l.keyTag!==void 0)y=l.keyTag===u?.keyTag&&c?.keyTag!==void 0?c.keyTag:l.keyTag;let m=void 0;if(l.keyring!==void 0)m=l.keyring===u?.keyring&&c?.keyring!==void 0?c.keyring:l.keyring;ru(n,l,y,m)}})}}async function da(e){let t=await ds();try{return await new Zt(t,Pt).ensureEnts(e)}finally{t.close()}}D();M();ae();var ne="entities",Xr="entity_type_created_at",Ss="entity_type_updated_at",bs="entity_type_parent_id",Is="entity_tags",la="entity_rlm",fa=15;function nu(e){return"typ"in e}function su(e){let t=rt(e.rlm),r={bod:e.body,crd:e.createdAt,...e.ctr!==0?{ctr:e.ctr}:{},eid:V(e.eid),pid:e.pid?V(e.pid):void 0,...t!==void 0?{rlm:t}:{},tgs:e.tags,typ:e.type,upd:e.updatedAt};if(r.pid===void 0)delete r.pid;if(r.tgs===void 0)delete r.tgs;if(r.ctr===void 0)delete r.ctr;return r}function ou(e){if(!Y(e))return{eid:V(e.eid),upd:e.updatedAt,...e.ctr!==0?{ctr:e.ctr}:{}};return su(e)}function Mt(e){let t=rt(e.rlm);return{body:e.bod,createdAt:e.crd,updatedAt:e.upd,ctr:e.ctr??0,type:e.typ,eid:Ee(e.eid),pid:e.pid?Ee(e.pid):void 0,...e.tgs!==void 0?{tags:e.tgs}:{},...t!==void 0?{rlm:t}:{}}}function gs(e){if(nu(e))return Mt(e);return{eid:Ee(e.eid),updatedAt:e.upd,ctr:e.ctr??0}}function iu(e,t){if(t instanceof Date)return IDBKeyRange.only([e,t]);let r=t.range;return IDBKeyRange.bound([e,r.start],[e,r.end],r.excludeStart===!0,r.excludeEnd===!0)}function au(e){if(typeof e==="string")return IDBKeyRange.only(e);if("range"in e){let t=e.range;return IDBKeyRange.bound(t.start,t.end,t.excludeStart===!0,t.excludeEnd===!0)}return IDBKeyRange.bound(e.prefix,e.prefix+"")}function cu(e,t,r){let n=[];if(typeof r==="string"){for(let i of e)if(i.typ===t)n.push(Mt(i));return n}let s=new Set,o="prefix"in r?r.prefix:void 0;for(let i of e){if(i.typ!==t)continue;if(s.has(i.eid))continue;if(o!==void 0){let c=i.tgs;if(!c||!c.some((u)=>u.startsWith(o)))continue}s.add(i.eid),n.push(Mt(i))}return n}class pa{name;db;opening;constructor(e){this.name=e}async init(){await this.ensureDb()}close(){let e=this.db;if(this.db=void 0,this.opening=void 0,e!==void 0)e.close()}async ensureDb(){if(this.db)return this.db;if(this.opening)return this.opening;return this.opening=du(this.name).then((e)=>(e.onversionchange=()=>{if(e.close(),this.db===e)this.db=void 0},this.db=e,this.opening=void 0,e),(e)=>{throw this.opening=void 0,e}),this.opening}apply=async(e)=>{let t=new Set,r=[],n=performance.now();X("idb apply start",{ops:e.length});let s;try{s=await this.ensureDb()}catch{return{stats:e.map(()=>16),types:t,eids:r}}let o=s.transaction(ne,"readwrite"),i=o.objectStore(ne);return new Promise((c)=>{let u=Array(e.length).fill(0);if(e.length<1){c({stats:[],types:t,eids:r});return}o.oncomplete=()=>{X("idb apply complete",{ops:e.length,ms:Math.round(performance.now()-n)}),c({stats:u,types:t,eids:r})},o.onerror=()=>{for(let l=0;l<u.length;l++)if(u[l]===void 0)u[l]=18;c({stats:u,types:t,eids:r})};let d=new Map;for(let l=0;l<e.length;l++){let p=e[l],y=V(p.eid),m={op:p,index:l},h=d.get(y);if(h)h.push(m);else d.set(y,[m])}for(let[l,p]of d){if(p.length<1)continue;let y=i.get(l);y.onsuccess=()=>{let m=y.result,h=m?gs(m):void 0,g=!1;for(let{op:S,index:b}of p){let[E,P]=St(h,S);if(P!==0){u[b]=P;continue}if(E===void 0){u[b]=12;continue}g=!0;for(let x of bt(h,E))t.add(x);h=E}if(g)r.push(p[0].op.eid);if(h){let S=i.put(ou(h));S.onerror=(b)=>{b.preventDefault();for(let{index:E}of p)u[E]=18}}},y.onerror=()=>{for(let{index:m}of p)u[m]=18}}})};async clear(){let e;try{e=await this.ensureDb()}catch{return 16}let t=e.transaction(ne,"readwrite"),r=t.objectStore(ne);return new Promise((n)=>{t.oncomplete=()=>n(0),t.onerror=()=>n(18),r.clear()})}async getRow(e){let t;try{t=await this.ensureDb()}catch{return a(16)}let r=V(e),s=t.transaction(ne,"readonly").objectStore(ne);return new Promise((o)=>{let i=s.get(r);i.onsuccess=()=>{let c=i.result;if(!c)o(f(void 0));else o(f(gs(c)))},i.onerror=()=>o(a(18))})}async getEnt(e){let[t,r]=await this.getRow(e);if(r!==0)return a(r);if(t===void 0||!Y(t))return f(void 0);return f(t)}async getByUpdatedAt(e,t){let[r,n]=jt(t);if(n!==0)return a(n);if(!r)return f([]);let s;try{s=await this.ensureDb()}catch{return a(16)}let i=s.transaction(ne,"readonly").objectStore(ne).index(Ss),c=iu(e,t);return new Promise((u)=>{let d=i.getAll(c);d.onsuccess=()=>{let l=d.result;u(f(l.map(Mt)))},d.onerror=()=>u(a(18))})}async getAllOfType(e){let t;try{t=await this.ensureDb()}catch{return a(16)}let n=t.transaction(ne,"readonly").objectStore(ne).index(Xr);return new Promise((s)=>{let o=n.getAll(IDBKeyRange.bound([e],[e,[]]));o.onsuccess=()=>{let i=o.result;s(f(i.map(Mt)))},o.onerror=()=>s(a(18))})}async getByTag(e,t){let[r,n]=Xt(t);if(n!==0)return a(n);if(!r)return f([]);let s;try{s=await this.ensureDb()}catch{return a(16)}let o=au(t),c=s.transaction(ne,"readonly").objectStore(ne).index(Is);return new Promise((u)=>{let d=c.getAll(o);d.onsuccess=()=>{let l=d.result;u(f(cu(l,e,t)))},d.onerror=()=>u(a(18))})}async getAllEntities(e){if("pid"in e){let t;try{t=await this.ensureDb()}catch{return a(16)}let r=V(e.pid),s=t.transaction(ne,"readonly").objectStore(ne).index(bs);return new Promise((o)=>{let i=s.getAll(IDBKeyRange.only([e.type,r]));i.onsuccess=()=>{let u=i.result.map(Mt);o(f(u))},i.onerror=()=>o(a(18))})}else if("tag"in e)return await this.getByTag(e.type,e.tag);else if("updatedAt"in e)return await this.getByUpdatedAt(e.type,e.updatedAt);return await this.getAllOfType(e.type)}async getEntities(e){let t=performance.now(),[r,n]=await this.getAllEntities(e);if(X("idb getEntities",{type:e.type,n:r?.length??0,ms:Math.round(performance.now()-t)}),n!==0)return a(n);return f(r)}async countEntities({type:e}){let t;try{t=await this.ensureDb()}catch{return a(16)}let n=t.transaction(ne,"readonly").objectStore(ne).index(Xr);return new Promise((s)=>{let o=IDBKeyRange.bound([e],[e,[]]),i=n.count(o);i.onsuccess=()=>s(f(i.result)),i.onerror=()=>s(a(18))})}async checksum(e){let t;try{t=await this.ensureDb()}catch{return a(16)}let n=t.transaction(ne,"readonly").objectStore(ne),s=[];return new Promise((o)=>{let i=n.openCursor();i.onsuccess=()=>{let c=i.result;if(c){let u=c.value;s.push(Er(gs(u))),c.continue()}else xr(s,e).then(o)},i.onerror=()=>o(a(18))})}}function uu(e,t){if(!e.objectStoreNames.contains(ne))e.createObjectStore(ne,{keyPath:"eid",autoIncrement:!1});let r=t.objectStore(ne);if(!r.indexNames.contains(Xr))r.createIndex(Xr,["typ","crd"],{unique:!1});if(!r.indexNames.contains(Ss))r.createIndex(Ss,["typ","upd"],{unique:!1});if(!r.indexNames.contains(bs))r.createIndex(bs,["typ","pid"],{unique:!1});if(!r.indexNames.contains(Is))r.createIndex(Is,"tgs",{unique:!1,multiEntry:!0});if(!r.indexNames.contains(la))r.createIndex(la,"rlm",{unique:!1})}function du(e){return new Promise((t,r)=>{let n=indexedDB.open(e,fa);n.onupgradeneeded=()=>{let{result:s,transaction:o}=n;if(!o){r(Error("Transaction is null during EntDB upgrade"));return}try{uu(s,o)}catch(i){r(i instanceof Error?i:Error(String(i)))}},n.onblocked=()=>{console.warn(`[DIPLOMATIC] EntDB IDB upgrade blocked (${e} → v${fa}); waiting for other connections to close`)},n.onsuccess=()=>t(n.result),n.onerror=()=>r(n.error??Error("EntDB IndexedDB open failed"))})}async function ya(e){let t=new pa(e);return await t.init(),t}ae();D();M();class ws{ents=new Map;useIndex;byType=new Map;byTypePid=new Map;byTypeTag=new Map;constructor(e=[],t){this.useIndex=t?.indexes!==!1;for(let r of e)this.put(r)}put(e){let t=Y(e)?Dr(e):e,r=V(t.eid),n=this.ents.get(r);if(n!==void 0&&Y(n))this.unindex(r,n);if(this.ents.set(r,t),Y(t))this.index(r,t)}del(e){let t=this.ents.get(e);if(t===void 0)return;if(Y(t))this.unindex(e,t);this.ents.delete(e)}index(e,t){if(!this.useIndex)return;let r=this.byType.get(t.type);if(!r)r=new Map,this.byType.set(t.type,r);if(r.set(e,t),t.pid){let n=V(t.pid),s=this.byTypePid.get(t.type);if(!s)s=new Map,this.byTypePid.set(t.type,s);let o=s.get(n);if(!o)o=new Map,s.set(n,o);o.set(e,t)}if(t.tags){let n=this.byTypeTag.get(t.type);if(!n)n=new Map,this.byTypeTag.set(t.type,n);for(let s of t.tags){let o=n.get(s);if(!o)o=new Map,n.set(s,o);o.set(e,t)}}}unindex(e,t){if(!this.useIndex)return;let r=this.byType.get(t.type);if(r){if(r.delete(e),r.size===0)this.byType.delete(t.type)}if(t.pid){let n=V(t.pid),s=this.byTypePid.get(t.type),o=s?.get(n);if(o){if(o.delete(e),o.size===0)s?.delete(n)}if(s&&s.size===0)this.byTypePid.delete(t.type)}if(t.tags){let n=this.byTypeTag.get(t.type);if(n){for(let s of t.tags){let o=n.get(s);if(o){if(o.delete(e),o.size===0)n.delete(s)}}if(n.size===0)this.byTypeTag.delete(t.type)}}}clearIndexes(){this.byType.clear(),this.byTypePid.clear(),this.byTypeTag.clear()}bucketList(e){if(!e||e.size===0)return[];let t=[];for(let r of e.values())t.push(r);return t}byTagSpec(e,t){let[r,n]=Xt(t);if(n!==0)return a(n);if(!r)return f([]);if(typeof t==="string")return f(this.bucketList(this.byTypeTag.get(e)?.get(t)));let s=this.byTypeTag.get(e);if(!s)return f([]);let o=new Set,i=[];for(let[c,u]of s){if(!Bn(c,t))continue;for(let[d,l]of u){if(o.has(d))continue;o.add(d),i.push(l)}}return f(i)}byDateSpec(e,t){let[r,n]=jt(t);if(n!==0)return a(n);if(!r)return f([]);let s=[],o=this.byType.get(e);if(o){for(let i of o.values())if(Dn(i.updatedAt,t))s.push(i)}return f(s)}async apply(e){let t=new Set,r=[],n=[];for(let s of e){let o=V(s.eid),i=this.ents.get(o),[c,u]=St(i,s);if(u!==0){n.push(u);continue}if(c===void 0){n.push(12);continue}for(let d of bt(i,c))t.add(d);this.put(c),r.push(s.eid),n.push(0)}return{stats:n,types:t,eids:r}}async clear(){return this.ents.clear(),this.clearIndexes(),0}async getRow(e){let t=V(e),r=this.ents.get(t);return f(r)}async getEnt(e){let[t,r]=await this.getRow(e);if(r!==0)return a(r);if(t===void 0||!Y(t))return f(void 0);return f(t)}async getAllEntities(e){let{type:t}=e;if(this.useIndex){if("pid"in e){let n=V(e.pid);return f(this.bucketList(this.byTypePid.get(t)?.get(n)))}if("tag"in e)return this.byTagSpec(t,e.tag);if("updatedAt"in e)return this.byDateSpec(t,e.updatedAt);return f(this.bucketList(this.byType.get(t)))}let r=[];if("pid"in e){for(let n of this.ents.values())if(Y(n)&&n.type===t&&n.pid&&Q(n.pid,e.pid))r.push(n)}else if("tag"in e){let n=e.tag,[s,o]=Xt(n);if(o!==0)return a(o);if(!s)return f(r);for(let i of this.ents.values())if(Y(i)&&i.type===t&&i.tags&&i.tags.some((c)=>Bn(c,n)))r.push(i)}else if("updatedAt"in e){let n=e.updatedAt,[s,o]=jt(n);if(o!==0)return a(o);if(!s)return f(r);for(let i of this.ents.values())if(Y(i)&&i.type===t&&Dn(i.updatedAt,n))r.push(i)}else for(let n of this.ents.values())if(Y(n)&&n.type===t)r.push(n);return f(r)}async getEntities(e){let[t,r]=await this.getAllEntities(e);if(r!==0)return a(r);return f(t)}async countEntities({type:e}){if(this.useIndex)return f(this.byType.get(e)?.size??0);let t=0;for(let r of this.ents.values())if(Y(r)&&r.type===e)t+=1;return f(t)}async checksum(e){let t=[];for(let r of this.ents.values())t.push(Er(r));return xr(t,e)}}function lu(e){let t=globalThis.requestAnimationFrame;if(typeof t!=="function"){queueMicrotask(e);return}t(()=>{t(e)})}async function ha(e){if(e?.verbose!==void 0)Fo(e.verbose);let t=e?.name??await da(e?.label??""),r=await ya(t);if(e?.cache===!1)return r;return new ga(r,void 0,{indexes:e?.indexes,optimistic:e?.optimistic})}class ga{mem;durable;warmed=new Set;listeners=new Set;chain=Promise.resolve();optimistic;inflight=0;warmP=new Map;constructor(e,t,r){if(this.durable=e,this.optimistic=r?.optimistic!==!1,X("CachedEntDB open",{optimistic:this.optimistic}),this.mem=new ws(t??[],{indexes:r?.indexes}),t)for(let n of t)this.warmed.add(n.type)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(e){if(e.size<1)return;let t=performance.now();X("emit start",{types:[...e],listeners:this.listeners.size});for(let r of this.listeners)r(e);X("emit done",{ms:Math.round(performance.now()-t)})}run(e){let t=this.chain.then(e,e);return this.chain=t.then(()=>{return},()=>{return}),t}apply(e){let t,r;if(this.optimistic){r=gu(this.mem,e).types,t=new Map;for(let s of e){let o=V(s.eid);t.set(o,ma(this.mem.ents.get(o)))}this.inflight+=1,X("apply mem patched",{ops:e.length,types:r?[...r]:[],inflight:this.inflight})}let n=this.run(async()=>{X("persist start",{ops:e.length});try{let s=performance.now(),o=await this.durable.apply(e);if(X("persist durable.apply done",{ms:Math.round(performance.now()-s)}),!this.optimistic){let{changed:c,status:u}=await this.pullEids(e.map((d)=>d.eid));if(this.emit(c),u!==0)return{stats:e.map(()=>u),types:o.types,eids:o.eids};return o}let i=[];for(let c=0;c<e.length;c++)if(o.stats[c]!==0)i.push(e[c].eid);if(i.length>0){X("persist pull rejected eids",{n:i.length});let{changed:c,status:u}=await this.pullEids(i,t);if(this.emit(c),u!==0)return{stats:e.map(()=>u),types:o.types,eids:o.eids}}return X("persist done"),o}finally{if(this.optimistic)this.inflight-=1}});if(r)lu(()=>{X("emit after paint"),this.emit(r)});return n}clear(){return this.run(async()=>{let e=await this.durable.clear();if(e!==0)return e;let t=this.mem.ents.size>0;return await this.mem.clear(),this.warmed.clear(),0})}ingestFromDurable(e){let t=[...e].length;return X("ingest queued",{eids:t}),this.run(async()=>{let r=performance.now();X("ingest start",{eids:t});let{changed:n,status:s}=await this.pullEids(e);return X("ingest done",{ms:Math.round(performance.now()-r),changed:[...n]}),this.emit(n),s})}async pullEids(e,t){let r=new Set,n=new Set;for(let s of e){let o=V(s);if(n.has(o))continue;n.add(o);let[i,c]=await this.durable.getRow(s);if(c!==0)return{changed:r,status:c};let u=this.mem.ents.get(o);if(u!==void 0&&i!==void 0&&xs(u,i))continue;if(t){if(!hu(ma(u),t.get(o)))continue}if(i){if(this.mem.put(i),!u||!fu(u,i)){if(Y(i))r.add(i.type);if(u!==void 0&&Y(u))r.add(u.type)}}else if(u!==void 0){if(this.mem.del(o),Y(u))r.add(u.type)}}return{changed:r,status:0}}async warmType(e){if(this.warmed.has(e))return 0;let t=performance.now();X("warmType start",{type:e});let[r,n]=await this.durable.getEntities({type:e});if(n!==0)return n;if(r)for(let s of r){let o=V(s.eid),i=this.mem.ents.get(o);if(!i||xs(s,i))this.mem.put(s)}return this.warmed.add(e),X("warmType done",{type:e,n:r?.length??0,ms:Math.round(performance.now()-t)}),0}beginWarm(e){if(this.warmed.has(e))return Promise.resolve(0);let t=this.warmP.get(e);if(t)return t;let r=this.warmType(e).finally(()=>{this.warmP.delete(e)});return this.warmP.set(e,r),r}ensureWarm(e){if(this.warmed.has(e))return;this.beginWarm(e).then((t)=>{if(t===0)this.emit(new Set([e]))})}async getRow(e){let t=V(e);if(this.mem.ents.has(t))return this.mem.getRow(e);let[r,n]=await this.durable.getRow(e);if(n!==0)return a(n);if(r){let s=this.mem.ents.get(t);if(!s||xs(r,s))this.mem.put(r)}return this.mem.getRow(e)}async getEnt(e){let[t,r]=await this.getRow(e);if(r!==0)return a(r);if(t===void 0||!Y(t))return f(void 0);return f(t)}async getEntities(e){if(this.warmed.has(e.type))return X("getEntities mem",{type:e.type}),this.mem.getEntities(e);if(this.inflight>0)return X("getEntities inflight-mem",{type:e.type}),this.ensureWarm(e.type),this.mem.getEntities(e);X("getEntities beginWarm",{type:e.type});let t=await this.beginWarm(e.type);if(t!==0)return a(t);return X("getEntities afterWarm",{type:e.type}),this.mem.getEntities(e)}async countEntities({type:e}){if(this.warmed.has(e))return this.mem.countEntities({type:e});if(this.inflight>0)return this.ensureWarm(e),this.mem.countEntities({type:e});let t=await this.beginWarm(e);if(t!==0)return a(t);return this.mem.countEntities({type:e})}async checksum(e){return this.durable.checksum(e)}}function fu(e,t){if(Y(e)!==Y(t))return!1;if(e.ctr!==t.ctr)return!1;if(e.updatedAt.getTime()!==t.updatedAt.getTime())return!1;if(!Q(e.eid,t.eid))return!1;if(!Y(e)||!Y(t))return!0;if(e.createdAt.getTime()!==t.createdAt.getTime())return!1;if(e.type!==t.type)return!1;if(!yu(e.pid,t.pid))return!1;if(!pu(e.tags,t.tags))return!1;return mu(e.body,t.body)}function pu(e,t){if(e===t)return!0;if(e===void 0||t===void 0)return!1;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function yu(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;return Q(e,t)}function mu(e,t){if(Object.is(e,t))return!0;if(e instanceof Uint8Array&&t instanceof Uint8Array)return Q(e,t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();return di(e,t)}function xs(e,t){let r=e.updatedAt.getTime(),n=t.updatedAt.getTime();if(r!==n)return r>n;return e.ctr>t.ctr}function ma(e){if(e===void 0)return;return{t:e.updatedAt.getTime(),ctr:e.ctr}}function hu(e,t){if(e===void 0||t===void 0)return e===t;return e.t===t.t&&e.ctr===t.ctr}function gu(e,t){let r=new Set,n=[];for(let s of t){let o=V(s.eid),i=e.ents.get(o),[c,u]=St(i,s);if(u!==0){n.push(u);continue}if(c===void 0){n.push(12);continue}for(let d of bt(i,c))r.add(d);e.put(c),n.push(0)}return{stats:n,types:r}}D();$t();function Su(e){return"close"in e&&typeof e.close==="function"}class Ps{client;store;entDB;boundLabel="";post;whenReady;resolveReady;rejectReady;constructor(e){this.post=e,this.whenReady=new Promise((t,r)=>{this.resolveReady=t,this.rejectReady=r})}async bindStores(e){if(this.client!==void 0)return;try{let t=await ca(Pt,e.data),r=await ha({cache:!1,name:e.ents}),n=new Pr(r.apply,()=>r.clear(),(i)=>{if(i.length<1)return;this.post({kind:"dirty",eids:i.map((c)=>c.slice())})}),s=n.clear;n.clear=async()=>{let i=await s();if(i===0)this.post({kind:"wiped"});return i};let o=new Nn(new zr,n,t,Mo,Pt);this.client=o,this.store=t,this.entDB=r,this.boundLabel=e.label,o.clientState.listen(()=>{this.emitClientState()}),o.xferState.listen(()=>{this.emitXferState()}),await this.emitXferState(),this.post({kind:"ready"}),this.markReady()}catch(t){let r=t instanceof Error?t:Error(String(t));throw this.post({kind:"initError",message:r.message}),this.failReady(r),r}}markReady(){let e=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,e)e()}failReady(e){let t=this.rejectReady;if(this.resolveReady=void 0,this.rejectReady=void 0,t)t(e)}requireClient(){if(!this.client)throw Error("WorkerRuntime not initialized");return this.client}async emitClientState(){let e=this.client;if(!e)return;let t=await e.clientState.get();this.post({kind:"clientState",connected:t.connected})}async emitXferState(){let e=this.client;if(!e)return;let t=await e.xferState.get();this.post({kind:"xferState",state:t})}hostFromSerialized(e){return{handle:new URL(e.handle),label:e.label,idx:e.idx}}async handle(e){if(e.op==="bind"){await this.bindStores(e);return}await this.whenReady;let t=this.requireClient();switch(e.op){case"ping":return"pong";case"setSeed":{let[r,n]=pe.fromBytes(e.seed);if(e.seed.fill(0),n!==0)throw new Pe(n);let s=await t.adopt(r,this.boundLabel);if(s!==0)throw new Pe(s);return}case"link":{await t.link(this.hostFromSerialized(e.host),e.connect??!0);return}case"unlink":{await t.unlink(e.label);return}case"connect":{await t.connect(e.listen??!0,e.sync??!0);return}case"disconnect":{await t.disconnect();return}case"sync":return await t.sync();case"rebuild":return await t.rebuild({checkHost:e.checkHost??!0});case"reconcile":{let[r,n]=await t.reconcile(e.hostLabel,{pull:e.pull,push:e.push,sync:e.sync});if(n!==0)throw new Pe(n);if(!r)throw new Pe(12);return r}case"msgcheck":return await t.msgcheck();case"entcheck":{let r=this.entDB;if(!r)throw new Pe(12);let[n,s]=await r.checksum(Pt);if(s!==0)throw new Pe(s);if(!n)throw new Pe(12);return n}case"wipe":{if(await t.wipe({msgs:e.msgs,ents:e.ents,meta:e.meta,seed:e.seed}),e.seed===!0){this.store?.close();let r=this.entDB;if(r!==void 0&&Su(r))r.close()}return}case"import":{let r=e.bytes.slice(),n=new Blob([r]),s=new File([n],"import.dip");return await t.import(s)}case"export":{let[r,n]=await t.exportBytes();if(n!==0)throw new Pe(n);if(!r)throw new Pe(12);return r}case"getXferState":return await t.xferState.get();default:{let r=e;throw Error("unknown worker command")}}}}class Pe extends Error{status;constructor(e){super(`WorkerStatusError: ${A[e]}`);this.status=e;this.name="WorkerStatusError"}}function Gr(e,t){return{kind:"reply",id:e,ok:!0,result:t}}function Es(e,t){return{kind:"reply",id:e,ok:!1,status:t}}var $e=globalThis,bu=new Ps((e,t)=>{if(t&&t.length>0)$e.postMessage(e,t);else $e.postMessage(e)});$e.onmessage=(e)=>{let t=e.data;if(!Bs(t))return;Iu(t)};async function Iu(e){try{let t=await bu.handle(e);if((e.op==="export"||e.op==="msgcheck"||e.op==="entcheck")&&t instanceof Uint8Array){let r=t.slice();$e.postMessage(Gr(e.id,r),[r.buffer]);return}if(e.op==="reconcile"&&t&&typeof t==="object"&&"msgcheck"in t&&t.msgcheck instanceof Uint8Array){let r=t.msgcheck.slice(),n={...t,msgcheck:r};$e.postMessage(Gr(e.id,n),[r.buffer]);return}$e.postMessage(Gr(e.id,t))}catch(t){if(t instanceof Pe){$e.postMessage(Es(e.id,t.status));return}console.error("worker command failed",t),$e.postMessage(Es(e.id,12))}}
|
|
1
|
+
var xa=Object.defineProperty;var Pa=(e)=>e;function Ea(e,t){this[e]=Pa.bind(null,t)}var Aa=(e,t)=>{for(var r in t)xa(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Ea.bind(t,r)})};var _=(e,t)=>()=>(e&&(t=e(e=0)),t);var Be=64,z=32,Us=32,Oe=8,qe=32,Rs=30000,Hs=512,A;var D=_(()=>{((I)=>{I[I.Success=0]="Success";I[I.InvalidSignature=3]="InvalidSignature";I[I.ClockOutOfSync=4]="ClockOutOfSync";I[I.UserNotRegistered=5]="UserNotRegistered";I[I.ServerMisconfigured=6]="ServerMisconfigured";I[I.MissingBody=7]="MissingBody";I[I.ExtraBodyContent=8]="ExtraBodyContent";I[I.MissingParam=9]="MissingParam";I[I.InvalidParam=10]="InvalidParam";I[I.InvalidRequest=11]="InvalidRequest";I[I.InternalError=12]="InternalError";I[I.NotFound=13]="NotFound";I[I.InvalidMessage=14]="InvalidMessage";I[I.NoChange=15]="NoChange";I[I.DatabaseClosed=16]="DatabaseClosed";I[I.StorageError=17]="StorageError";I[I.DatabaseError=18]="DatabaseError";I[I.HashMismatch=19]="HashMismatch";I[I.DecryptionError=20]="DecryptionError";I[I.NotImplemented=21]="NotImplemented";I[I.MissingSeed=22]="MissingSeed";I[I.OutOfBounds=23]="OutOfBounds";I[I.HostError=24]="HostError";I[I.CommunicationError=25]="CommunicationError";I[I.VarLimitExceeded=26]="VarLimitExceeded";I[I.InvalidResponse=27]="InvalidResponse";I[I.ConnectionClosed=28]="ConnectionClosed";I[I.CryptoError=29]="CryptoError";I[I.WebAuthnError=30]="WebAuthnError"})(A||={})});function f(e){return[e,0]}function a(e){return[void 0,e]}var C=_(()=>{D()});function ka(e){if(e<0)console.info("N",e),console.trace();if(typeof e!=="bigint")e=BigInt(e);if(e<0n)return a(10);let t=[];while(e>0n){let r=Number(e&0x7fn);if(e>>=7n,e>0n)t.push(r|128);else t.push(r)}if(t.length===0)return f(new Uint8Array([0]));if(t.length>8)return a(26);return f(new Uint8Array(t))}function Da(e,t=0){let r=0n,n=0,s=t;while(!0){if(s>=e.length)return a(14);let o=e[s++];if(o===void 0)return a(14);if(r|=BigInt(o&127)<<BigInt(n),(o&128)===0){if(s-t>8)return a(26);return f({value:r>0x1fffffffffffffn?r:Number(r),bytesRead:s-t})}if(n+=7,n>=56)return a(26)}}class L{data;pos=0;constructor(e){this.data=e}static async fromResponse(e){let t=await e.arrayBuffer(),r=new Uint8Array(t);return new L(r)}readBigInt(){if(this.pos+8>this.data.length)return a(7);let e=new DataView(this.data.buffer,this.data.byteOffset+this.pos).getBigUint64(0,!1);return this.pos+=8,f(e)}readDate(){let[e,t]=this.readVarInt();if(t!==0)return a(t);return f(new Date(e))}readVarInt(){let[e,t]=Da(this.data,this.pos);if(t!==0)return a(t);this.pos+=e.bytesRead;let r=e.value;return f(typeof r==="bigint"?Number(r):r)}readVarString(){let[e,t]=this.readVarInt();if(t!==0)return a(t);let[r,n]=this.readBytes(e);if(n!==0)return a(n);let s=new TextDecoder().decode(r);return f(s)}readVarStrings(){let[e,t]=this.readVarInt();if(t!==0)return a(t);if(e<0||e>this.remaining())return a(14);let r=[];for(let n=0;n<e;n++){let[s,o]=this.readVarString();if(o!==0)return a(o);r.push(s)}return f(r)}readBytes(e){if(e<0)return a(10);if(this.pos+e>this.data.length)return a(23);let t=this.data.slice(this.pos,this.pos+e);return this.pos+=e,f(t)}readVarBytes(){let[e,t]=this.readVarInt();if(t!==0)return a(t);return this.readBytes(e)}readStruct(e){return e.decode(this)}readStructs(e){let t=[];while(!this.done()){let[r,n]=this.readStruct(e);if(n!==0)return a(n);t.push(r)}return f(t)}readBytesSeq(e){let t=[];while(!this.done()){let[r,n]=this.readBytes(e);if(n!==0)return a(n);t.push(r)}return f(t)}done(){return this.pos>=this.data.length}remaining(){return this.data.length-this.pos}readRest(){let e=this.data.subarray(this.pos);return this.pos=this.data.length,e}consumed(){return this.pos}}class O{parts=[];writeBigInt(e){let t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e,!1),this.parts.push(t)}writeDate(e){let t=e.getTime();return this.writeVarInt(t)}writeVarInt(e){let[t,r]=ka(e);if(r!==0)return r;return this.parts.push(t),0}writeVarString(e){let t=new TextEncoder().encode(e),r=this.writeVarInt(t.length);if(r!==0)return r;return this.writeBytes(t),0}writeVarStrings(e){let t=this.writeVarInt(e.length);if(t!==0)return t;for(let r of e){let n=this.writeVarString(r);if(n!==0)return n}return 0}prependBytes(e){this.parts.unshift(e.slice())}writeBytes(e){this.parts.push(e.slice())}writeVarBytes(e){let t=this.writeVarInt(e.length);if(t!==0)return t;return this.writeBytes(e),0}writeStruct(e,t){return e.encode(this,t)}writeStructs(e,t){for(let r of t){let n=this.writeStruct(e,r);if(n!==0)return n}return 0}writeBytesSeq(e){for(let t of e)this.writeBytes(t)}result(){let e=this.parts.reduce((n,s)=>n+s.length,0),t=new Uint8Array(e),r=0;for(let n of this.parts)t.set(n,r),r+=n.length;return t}wipe(){for(let e of this.parts)e.fill(0);this.parts.length=0}*scan(){for(let e of this.parts)yield e}}var re=_(()=>{C();D()});function ir(e,t){if(e.byteLength!==t.byteLength)return!1;let r=0;for(let n=0;n<e.byteLength;n++){let s=e[n],o=t[n];if(s===void 0||o===void 0)return!1;r|=s^o}return r===0}function et(e){return Array.from(e).map((r)=>r.toString(16).padStart(2,"0")).join("")}function Ks(e){if(e.length%2!==0)throw Error("Invalid hex string");let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=Number.parseInt(e.substr(r,2),16);return t}function G(e,t){return ir(e,t)}function Vs(e){return K(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ls(e){let t=e.length%4===0?"":"=".repeat(4-e.length%4),r=e.replace(/-/g,"+").replace(/_/g,"/")+t;return Ee(r)}function pt(e,t){let r=new Uint8Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}var K,Ee;var ce=_(()=>{if(typeof Uint8Array.prototype.toBase64==="function")K=(e)=>e.toBase64();else K=(e)=>btoa(String.fromCharCode(...e));if(typeof Uint8Array.fromBase64==="function")Ee=(e)=>Uint8Array.fromBase64(e);else Ee=(e)=>Uint8Array.from(atob(e),(t)=>t.charCodeAt(0))});function _e(e,t){return e.label===t.label&&e.index===t.index}var Kt;var tt=_(()=>{D();C();Kt={encode(e,t){let r=e.writeVarString(t.label);if(r!==0)return r;let n=e.writeVarInt(t.index);if(n!==0)return n;return 0},decode(e){let[t,r]=e.readVarString();if(r!==0)return a(r);let[n,s]=e.readVarInt();if(s!==0)return a(s);return f({label:t,index:n})}}});var rt;var _s=_(()=>{rt=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0});function cr(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function nn(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ue(e,...t){if(!nn(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function sn(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function Fs(e,t){ue(e);let r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}function on(e){if(typeof e!=="boolean")throw Error(`boolean expected, not ${e}`)}var Lt=()=>{};function va(e){if(typeof e!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ur(e){if(typeof e==="string")e=va(e);else if(nn(e))e=dr(e);else throw Error("Uint8Array expected, got "+typeof e);return e}function Ws(e,t){if(t==null||typeof t!=="object")throw Error("options must be defined");return Object.assign(e,t)}function js(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function an(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw Error("invalid output length, expected "+e+", got: "+t.length);if(r&&!Ma(t))throw Error("invalid output, must be aligned");return t}function Ma(e){return e.byteOffset%4===0}function dr(e){return Uint8Array.from(e)}function ve(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var He=(e)=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),Ba,Xs=(e,t)=>{function r(n,...s){if(ue(n),e.nonceLength!==void 0){let l=s[0];if(!l)throw Error("nonce / iv required");if(e.varSizeNonce)ue(l);else ue(l,e.nonceLength)}let o=e.tagLength;if(o&&s[1]!==void 0)ue(s[1]);let i=t(n,...s),c=(l,p)=>{if(p!==void 0){if(l!==2)throw Error("cipher output not supported");ue(p)}},u=!1;return{encrypt(l,p){if(u)throw Error("cannot encrypt() twice with same key + nonce");return u=!0,ue(l),c(i.encrypt.length,p),i.encrypt(l,p)},decrypt(l,p){if(ue(l),o&&l.length<o)throw Error("invalid ciphertext length: smaller than tagLength="+o);return c(i.decrypt.length,p),i.decrypt(l,p)}}}return Object.assign(r,e),r};var lr=_(()=>{Lt();/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */Ba=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Ba)throw Error("Non little-endian hardware is not supported")});function Ot(e=32){if(rt&&typeof rt.getRandomValues==="function")return rt.getRandomValues(new Uint8Array(e));if(rt&&typeof rt.randomBytes==="function")return rt.randomBytes(e);throw Error("crypto.getRandomValues must be defined")}var Gs=_(()=>{_s()});function B(e,t){return e<<t|e>>>32-t}function cn(e){return e.byteOffset%4===0}function Ka(e,t,r,n,s,o,i,c){let u=s.length,d=new Uint8Array(fr),l=He(d),p=cn(s)&&cn(o),y=p?He(s):Qs,m=p?He(o):Qs;for(let h=0;h<u;i++){if(e(t,r,n,l,i,c),i>=zs)throw Error("arx: counter overflow");let g=Math.min(fr,u-h);if(p&&g===fr){let S=h/4;if(h%4!==0)throw Error("arx: invalid block position");for(let b=0,x;b<Ta;b++)x=S+b,m[x]=y[x]^l[b];h+=fr;continue}for(let S=0,b;S<g;S++)b=h+S,o[b]=s[b]^d[S];h+=g}}function Ys(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:o,rounds:i}=Ws({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=="function")throw Error("core must be a function");return cr(s),cr(i),on(o),on(r),(c,u,d,l,p=0)=>{ue(c),ue(u),ue(d);let y=d.length;if(l===void 0)l=new Uint8Array(y);if(ue(l),cr(p),p<0||p>=zs)throw Error("arx: counter overflow");if(l.length<y)throw Error(`arx: output (${l.length}) is shorter than data (${y})`);let m=[],h=c.length,g,S;if(h===32)m.push(g=dr(c)),S=Ha;else if(h===16&&r)g=new Uint8Array(32),g.set(c),g.set(c,16),S=Ra,m.push(g);else throw Error(`arx: invalid 32-byte key, got length=${h}`);if(!cn(u))m.push(u=dr(u));let b=He(g);if(n){if(u.length!==24)throw Error("arx: extended nonce must be 24 bytes");n(S,b,He(u.subarray(0,16)),b),u=u.subarray(16)}let x=16-s;if(x!==u.length)throw Error(`arx: nonce must be ${x} or 16 bytes`);if(x!==12){let P=new Uint8Array(12);P.set(u,o?0:12-u.length),u=P,m.push(u)}let E=He(u);return Ka(e,S,b,E,d,l,p,i),ve(...m),l}}var $s=(e)=>Uint8Array.from(e.split("").map((t)=>t.charCodeAt(0))),Ca,Ua,Ra,Ha,fr=64,Ta=16,zs=4294967295,Qs;var Js=_(()=>{Lt();lr();Ca=$s("expand 16-byte k"),Ua=$s("expand 32-byte k"),Ra=He(Ca),Ha=He(Ua);Qs=new Uint32Array});class Zs{constructor(e){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,e=ur(e),ue(e,32);let t=le(e,0),r=le(e,2),n=le(e,4),s=le(e,6),o=le(e,8),i=le(e,10),c=le(e,12),u=le(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|n<<6)&7939,this.r[3]=(n>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|i<<2)&8191,this.r[7]=(i>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let d=0;d<8;d++)this.pad[d]=le(e,16+2*d)}process(e,t,r=!1){let n=r?0:2048,{h:s,r:o}=this,i=o[0],c=o[1],u=o[2],d=o[3],l=o[4],p=o[5],y=o[6],m=o[7],h=o[8],g=o[9],S=le(e,t+0),b=le(e,t+2),x=le(e,t+4),E=le(e,t+6),P=le(e,t+8),w=le(e,t+10),k=le(e,t+12),v=le(e,t+14),U=s[0]+(S&8191),T=s[1]+((S>>>13|b<<3)&8191),R=s[2]+((b>>>10|x<<6)&8191),V=s[3]+((x>>>7|E<<9)&8191),H=s[4]+((E>>>4|P<<12)&8191),I=s[5]+(P>>>1&8191),F=s[6]+((P>>>14|w<<2)&8191),N=s[7]+((w>>>11|k<<5)&8191),j=s[8]+((k>>>8|v<<8)&8191),X=s[9]+(v>>>5|n),M=0,te=M+U*i+T*(5*g)+R*(5*h)+V*(5*m)+H*(5*y);M=te>>>13,te&=8191,te+=I*(5*p)+F*(5*l)+N*(5*d)+j*(5*u)+X*(5*c),M+=te>>>13,te&=8191;let ne=M+U*c+T*i+R*(5*g)+V*(5*h)+H*(5*m);M=ne>>>13,ne&=8191,ne+=I*(5*y)+F*(5*p)+N*(5*l)+j*(5*d)+X*(5*u),M+=ne>>>13,ne&=8191;let ie=M+U*u+T*c+R*i+V*(5*g)+H*(5*h);M=ie>>>13,ie&=8191,ie+=I*(5*m)+F*(5*y)+N*(5*p)+j*(5*l)+X*(5*d),M+=ie>>>13,ie&=8191;let J=M+U*d+T*u+R*c+V*i+H*(5*g);M=J>>>13,J&=8191,J+=I*(5*h)+F*(5*m)+N*(5*y)+j*(5*p)+X*(5*l),M+=J>>>13,J&=8191;let Re=M+U*l+T*d+R*u+V*c+H*i;M=Re>>>13,Re&=8191,Re+=I*(5*g)+F*(5*h)+N*(5*m)+j*(5*y)+X*(5*p),M+=Re>>>13,Re&=8191;let at=M+U*p+T*l+R*d+V*u+H*c;M=at>>>13,at&=8191,at+=I*i+F*(5*g)+N*(5*h)+j*(5*m)+X*(5*y),M+=at>>>13,at&=8191;let ct=M+U*y+T*p+R*l+V*d+H*u;M=ct>>>13,ct&=8191,ct+=I*c+F*i+N*(5*g)+j*(5*h)+X*(5*m),M+=ct>>>13,ct&=8191;let ut=M+U*m+T*y+R*p+V*l+H*d;M=ut>>>13,ut&=8191,ut+=I*u+F*c+N*i+j*(5*g)+X*(5*h),M+=ut>>>13,ut&=8191;let dt=M+U*h+T*m+R*y+V*p+H*l;M=dt>>>13,dt&=8191,dt+=I*d+F*u+N*c+j*i+X*(5*g),M+=dt>>>13,dt&=8191;let lt=M+U*g+T*h+R*m+V*y+H*p;M=lt>>>13,lt&=8191,lt+=I*l+F*d+N*u+j*c+X*i,M+=lt>>>13,lt&=8191,M=(M<<2)+M|0,M=M+te|0,te=M&8191,M=M>>>13,ne+=M,s[0]=te,s[1]=ne,s[2]=ie,s[3]=J,s[4]=Re,s[5]=at,s[6]=ct,s[7]=ut,s[8]=dt,s[9]=lt}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(let i=2;i<10;i++)e[i]+=n,n=e[i]>>>13,e[i]&=8191;e[0]+=n*5,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let i=1;i<10;i++)r[i]=e[i]+n,n=r[i]>>>13,r[i]&=8191;r[9]-=8192;let s=(n^1)-1;for(let i=0;i<10;i++)r[i]&=s;s=~s;for(let i=0;i<10;i++)e[i]=e[i]&s|r[i];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let i=1;i<8;i++)o=(e[i]+t[i]|0)+(o>>>16)|0,e[i]=o&65535;ve(r)}update(e){sn(this);let{buffer:t,blockLen:r}=this;e=ur(e);let n=e.length;for(let s=0;s<n;){let o=Math.min(r-this.pos,n-s);if(o===r){for(;r<=n-s;s+=r)this.process(e,s);continue}if(t.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r)this.process(t,0,!1),this.pos=0}return this}destroy(){ve(this.h,this.r,this.buffer,this.pad)}digestInto(e){sn(this),Fs(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:n}=this;if(n){t[n++]=1;for(;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=r[o]>>>0,e[s++]=r[o]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}function Va(e){let t=(n,s)=>e(s).update(ur(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=(n)=>e(n),t}var le=(e,t)=>e[t++]&255|(e[t++]&255)<<8,un;var eo=_(()=>{Lt();lr();un=Va((e)=>new Zs(e))});function La(e,t,r,n,s,o=20){let i=e[0],c=t[0],u=t[1],d=t[2],l=t[3],p=e[1],y=r[0],m=r[1],h=s,g=0,S=e[2],b=t[4],x=t[5],E=t[6],P=t[7],w=e[3],k=i,v=c,U=u,T=d,R=l,V=p,H=y,I=m,F=h,N=g,j=S,X=b,M=x,te=E,ne=P,ie=w;for(let Re=0;Re<o;Re+=2)R^=B(k+M|0,7),F^=B(R+k|0,9),M^=B(F+R|0,13),k^=B(M+F|0,18),N^=B(V+v|0,7),te^=B(N+V|0,9),v^=B(te+N|0,13),V^=B(v+te|0,18),ne^=B(j+H|0,7),U^=B(ne+j|0,9),H^=B(U+ne|0,13),j^=B(H+U|0,18),T^=B(ie+X|0,7),I^=B(T+ie|0,9),X^=B(I+T|0,13),ie^=B(X+I|0,18),v^=B(k+T|0,7),U^=B(v+k|0,9),T^=B(U+v|0,13),k^=B(T+U|0,18),H^=B(V+R|0,7),I^=B(H+V|0,9),R^=B(I+H|0,13),V^=B(R+I|0,18),X^=B(j+N|0,7),F^=B(X+j|0,9),N^=B(F+X|0,13),j^=B(N+F|0,18),M^=B(ie+ne|0,7),te^=B(M+ie|0,9),ne^=B(te+M|0,13),ie^=B(ne+te|0,18);let J=0;n[J++]=i+k|0,n[J++]=c+v|0,n[J++]=u+U|0,n[J++]=d+T|0,n[J++]=l+R|0,n[J++]=p+V|0,n[J++]=y+H|0,n[J++]=m+I|0,n[J++]=h+F|0,n[J++]=g+N|0,n[J++]=S+j|0,n[J++]=b+X|0,n[J++]=x+M|0,n[J++]=E+te|0,n[J++]=P+ne|0,n[J++]=w+ie|0}function Oa(e,t,r,n){let s=e[0],o=t[0],i=t[1],c=t[2],u=t[3],d=e[1],l=r[0],p=r[1],y=r[2],m=r[3],h=e[2],g=t[4],S=t[5],b=t[6],x=t[7],E=e[3];for(let w=0;w<20;w+=2)u^=B(s+S|0,7),y^=B(u+s|0,9),S^=B(y+u|0,13),s^=B(S+y|0,18),m^=B(d+o|0,7),b^=B(m+d|0,9),o^=B(b+m|0,13),d^=B(o+b|0,18),x^=B(h+l|0,7),i^=B(x+h|0,9),l^=B(i+x|0,13),h^=B(l+i|0,18),c^=B(E+g|0,7),p^=B(c+E|0,9),g^=B(p+c|0,13),E^=B(g+p|0,18),o^=B(s+c|0,7),i^=B(o+s|0,9),c^=B(i+o|0,13),s^=B(c+i|0,18),l^=B(d+u|0,7),p^=B(l+d|0,9),u^=B(p+l|0,13),d^=B(u+p|0,18),g^=B(h+m|0,7),y^=B(g+h|0,9),m^=B(y+g|0,13),h^=B(m+y|0,18),S^=B(E+x|0,7),b^=B(S+E|0,9),x^=B(b+S|0,13),E^=B(x+b|0,18);let P=0;n[P++]=s,n[P++]=d,n[P++]=h,n[P++]=E,n[P++]=l,n[P++]=p,n[P++]=y,n[P++]=m}var dn,ln;var to=_(()=>{Js();Lt();eo();lr();dn=Ys(La,{counterRight:!0,extendNonceFn:Oa}),ln=Xs({blockSize:64,nonceLength:24,tagLength:16},(e,t)=>({encrypt(r,n){n=an(r.length+32,n,!1);let s=n.subarray(0,32),o=n.subarray(32);n.set(r,32),ve(s),dn(e,t,n,n);let i=un(o,s);return n.set(i,16),ve(n.subarray(0,16),i),n.subarray(16)},decrypt(r,n){ue(r),n=an(r.length+32,n,!1);let s=n.subarray(0,32),o=n.subarray(32,48),i=n.subarray(48);n.set(r,32),ve(s);let c=dn(e,t,s,s),u=un(i,c);if(!js(o,u))throw Error("invalid tag");return dn(e,t,n.subarray(16),n.subarray(16)),ve(s,o,u),i}}))});function qa(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function qt(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function nt(e,...t){if(!qa(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function Nt(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function pr(e,t){nt(e);let r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}function ro(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function yt(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function mt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _t(e,t){return e<<32-t|e>>>t}function so(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Na(e){for(let t=0;t<e.length;t++)e[t]=so(e[t]);return e}function _a(e){if(typeof e!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function ht(e){if(typeof e==="string")e=_a(e);return nt(e),e}class fn{}function io(e){let t=(n,s)=>e(s).update(ht(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=(n)=>e(n),t}var no,oo,he;var yr=_(()=>{/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */no=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();oo=no?(e)=>e:(e)=>so(e);he=no?(e)=>e:Na});var ao;var co=_(()=>{ao=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});function pn(e,t=!1){if(t)return{h:Number(e&mr),l:Number(e>>uo&mr)};return{h:Number(e>>uo&mr)|0,l:Number(e&mr)|0}}var mr,uo;var lo=_(()=>{mr=BigInt(4294967295),uo=BigInt(32)});function Te(e,t,r,n,s){return e=e+t+s|0,n=_t(n^e,16),r=r+n|0,t=_t(t^r,12),{a:e,b:t,c:r,d:n}}function Ke(e,t,r,n,s){return e=e+t+s|0,n=_t(n^e,8),r=r+n|0,t=_t(t^r,7),{a:e,b:t,c:r,d:n}}var fo=_(()=>{yr()});function mn(e,t,r,n,s,o,i,c,u,d,l,p,y,m,h,g,S,b,x,E){let P=0;for(let w=0;w<n;w++)({a:s,b:u,c:y,d:S}=Te(s,u,y,S,r[t+e[P++]])),{a:s,b:u,c:y,d:S}=Ke(s,u,y,S,r[t+e[P++]]),{a:o,b:d,c:m,d:b}=Te(o,d,m,b,r[t+e[P++]]),{a:o,b:d,c:m,d:b}=Ke(o,d,m,b,r[t+e[P++]]),{a:i,b:l,c:h,d:x}=Te(i,l,h,x,r[t+e[P++]]),{a:i,b:l,c:h,d:x}=Ke(i,l,h,x,r[t+e[P++]]),{a:c,b:p,c:g,d:E}=Te(c,p,g,E,r[t+e[P++]]),{a:c,b:p,c:g,d:E}=Ke(c,p,g,E,r[t+e[P++]]),{a:s,b:d,c:h,d:E}=Te(s,d,h,E,r[t+e[P++]]),{a:s,b:d,c:h,d:E}=Ke(s,d,h,E,r[t+e[P++]]),{a:o,b:l,c:g,d:S}=Te(o,l,g,S,r[t+e[P++]]),{a:o,b:l,c:g,d:S}=Ke(o,l,g,S,r[t+e[P++]]),{a:i,b:p,c:y,d:b}=Te(i,p,y,b,r[t+e[P++]]),{a:i,b:p,c:y,d:b}=Ke(i,p,y,b,r[t+e[P++]]),{a:c,b:u,c:m,d:x}=Te(c,u,m,x,r[t+e[P++]]),{a:c,b:u,c:m,d:x}=Ke(c,u,m,x,r[t+e[P++]]);return{v0:s,v1:o,v2:i,v3:c,v4:u,v5:d,v6:l,v7:p,v8:y,v9:m,v10:h,v11:g,v12:S,v13:b,v14:x,v15:E}}var yn;var po=_(()=>{fo();yr();yn=class yn extends fn{constructor(e,t){super();this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,qt(e),qt(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=yt(this.buffer)}update(e){Nt(this),e=ht(e),nt(e);let{blockLen:t,buffer:r,buffer32:n}=this,s=e.length,o=e.byteOffset,i=e.buffer;for(let c=0;c<s;){if(this.pos===t)he(n),this.compress(n,0,!1),he(n),this.pos=0;let u=Math.min(t-this.pos,s-c),d=o+c;if(u===t&&!(d%4)&&c+u<s){let l=new Uint32Array(i,d,Math.floor((s-c)/4));he(l);for(let p=0;c+t<s;p+=n.length,c+=t)this.length+=t,this.compress(l,p,!1);he(l);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){Nt(this),pr(e,this);let{pos:t,buffer32:r}=this;this.finished=!0,mt(this.buffer.subarray(t)),he(r),this.compress(r,0,!0),he(r);let n=yt(e);this.get().forEach((s,o)=>n[o]=oo(s))}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){let{buffer:t,length:r,finished:n,destroyed:s,outputLen:o,pos:i}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(t),e.destroyed=s,e.finished=n,e.length=r,e.pos=i,e.outputLen=o,e}clone(){return this._cloneInto()}}});var Me,Ve,yo,hn,gn;var mo=_(()=>{co();lo();po();yr();Me={CHUNK_START:1,CHUNK_END:2,PARENT:4,ROOT:8,KEYED_HASH:16,DERIVE_KEY_CONTEXT:32,DERIVE_KEY_MATERIAL:64},Ve=ao.slice(),yo=(()=>{let e=Array.from({length:16},(n,s)=>s),t=(n)=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((s)=>n[s]),r=[];for(let n=0,s=e;n<7;n++,s=t(s))r.push(...s);return Uint8Array.from(r)})();hn=class hn extends yn{constructor(e={},t=0){super(64,e.dkLen===void 0?32:e.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:r,context:n}=e,s=n!==void 0;if(r!==void 0){if(s)throw Error('Only "key" or "context" can be specified at same time');let o=ht(r).slice();nt(o,32),this.IV=yt(o),he(this.IV),this.flags=t|Me.KEYED_HASH}else if(s){let o=ht(n),i=new hn({dkLen:32},Me.DERIVE_KEY_CONTEXT).update(o).digest();this.IV=yt(i),he(this.IV),this.flags=t|Me.DERIVE_KEY_MATERIAL}else this.IV=Ve.slice(),this.flags=t;this.state=this.IV.slice(),this.bufferOut=ro(this.bufferOut32)}get(){return[]}set(){}b2Compress(e,t,r,n=0){let{state:s,pos:o}=this,{h:i,l:c}=pn(BigInt(e),!0),{v0:u,v1:d,v2:l,v3:p,v4:y,v5:m,v6:h,v7:g,v8:S,v9:b,v10:x,v11:E,v12:P,v13:w,v14:k,v15:v}=mn(yo,n,r,7,s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],Ve[0],Ve[1],Ve[2],Ve[3],i,c,o,t);s[0]=u^S,s[1]=d^b,s[2]=l^x,s[3]=p^E,s[4]=y^P,s[5]=m^w,s[6]=h^k,s[7]=g^v}compress(e,t=0,r=!1){let n=this.flags;if(!this.chunkPos)n|=Me.CHUNK_START;if(this.chunkPos===15||r)n|=Me.CHUNK_END;if(!r)this.pos=this.blockLen;if(this.b2Compress(this.chunksDone,n,e,t),this.chunkPos+=1,this.chunkPos===16||r){let s=this.state;this.state=this.IV.slice();for(let o,i=this.chunksDone+1;r||!(i&1);i>>=1){if(!(o=this.stack.pop()))break;this.buffer32.set(o,0),this.buffer32.set(s,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|Me.PARENT,this.buffer32,0),s=this.state,this.state=this.IV.slice()}this.chunksDone++,this.chunkPos=0,this.stack.push(s)}this.pos=0}_cloneInto(e){e=super._cloneInto(e);let{IV:t,flags:r,state:n,chunkPos:s,posOut:o,chunkOut:i,stack:c,chunksDone:u}=this;return e.state.set(n.slice()),e.stack=c.map((d)=>Uint32Array.from(d)),e.IV.set(t),e.flags=r,e.chunkPos=s,e.chunksDone=u,e.posOut=o,e.chunkOut=i,e.enableXOF=this.enableXOF,e.bufferOut32.set(this.bufferOut32),e}destroy(){this.destroyed=!0,mt(this.state,this.buffer32,this.IV,this.bufferOut32),mt(...this.stack)}b2CompressOut(){let{state:e,pos:t,flags:r,buffer32:n,bufferOut32:s}=this,{h:o,l:i}=pn(BigInt(this.chunkOut++));he(n);let{v0:c,v1:u,v2:d,v3:l,v4:p,v5:y,v6:m,v7:h,v8:g,v9:S,v10:b,v11:x,v12:E,v13:P,v14:w,v15:k}=mn(yo,0,n,7,e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],Ve[0],Ve[1],Ve[2],Ve[3],i,o,t,r);s[0]=c^g,s[1]=u^S,s[2]=d^b,s[3]=l^x,s[4]=p^E,s[5]=y^P,s[6]=m^w,s[7]=h^k,s[8]=e[0]^g,s[9]=e[1]^S,s[10]=e[2]^b,s[11]=e[3]^x,s[12]=e[4]^E,s[13]=e[5]^P,s[14]=e[6]^w,s[15]=e[7]^k,he(n),he(s),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,mt(this.buffer.subarray(this.pos));let e=this.flags|Me.ROOT;if(this.stack.length)e|=Me.PARENT,he(this.buffer32),this.compress(this.buffer32,0,!0),he(this.buffer32),this.chunksDone=0,this.pos=this.blockLen;else e|=(!this.chunkPos?Me.CHUNK_START:0)|Me.CHUNK_END;this.flags=e,this.b2CompressOut()}writeInto(e){Nt(this,!1),nt(e),this.finish();let{blockLen:t,bufferOut:r}=this;for(let n=0,s=e.length;n<s;){if(this.posOut>=t)this.b2CompressOut();let o=Math.min(t-this.posOut,s-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible after digest call");return this.writeInto(e)}xof(e){return qt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(pr(e,this),this.finished)throw Error("digest() was already called");return this.enableXOF=!1,this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}};gn=io((e)=>new hn(e))});function ho(e){if(e.byteLength!==Fa)return a(10);return f(e)}function So(e){let t=0n;for(let r=e.length-1;r>=0;r--)t=t<<8n|BigInt(e[r]);return t}function ja(e){let t=new Uint8Array(32),r=(e%Q+Q)%Q;for(let n=0;n<32;n++)t[n]=Number(r&0xffn),r>>=8n;return t}function Xa(e){let t=e.slice();return t[31]&=127,So(t)}function Ga(e){let t=e.slice();return t[0]&=248,t[31]&=127,t[31]|=64,t}function hr(e,t,r){let n=-e,s=(t^r)&n;return[t^s,r^s]}function Qa(e){let t=Q-2n,r=(e%Q+Q)%Q,n=1n;while(t>0n){if(t&1n)n=n*r%Q;r=r*r%Q,t>>=1n}return n}function Sn(e,t){let r=Ga(e),n=Xa(t),s=1n,o=0n,i=n,c=1n,u=0n,d=So(r);for(let l=254;l>=0;l--){let p=d>>BigInt(l)&1n;u^=p,[s,i]=hr(u,s,i),[o,c]=hr(u,o,c),u=p;let y=(s+o)%Q,m=y*y%Q,h=(s-o+Q)%Q,g=h*h%Q,S=(m-g+Q)%Q,b=(i+c)%Q,E=(i-c+Q)%Q*y%Q,P=b*h%Q,w=(E+P)%Q,k=(E-P+Q)%Q;i=w*w%Q,c=n*k*k%Q,s=m*g%Q,o=S*(m+Wa*S)%Q}return[s,i]=hr(u,s,i),[o,c]=hr(u,o,c),r.fill(0),ja(s*Qa(o)%Q)}function bo(e){return Sn(e,go)}var Fa=32,al,Q,Wa=121665n,go;var Io=_(()=>{D();C();al=Symbol("X25519Sk");Q=(1n<<255n)-19n,go=new Uint8Array(32);go[0]=9});function wo(e){let t=new Uint8Array(bn.length+32);return t.set(bn),t.set(e.subarray(0,32),bn.length),t}function xo(e){let t=new Uint8Array(In.length+32);return t.set(In),t.set(e.subarray(0,32),In.length),t}function Po(e){return typeof e==="string"?new TextEncoder().encode(e):e}function Le(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}async function $a(e){return Ot(e)}async function wn(){return Ot(32)}async function gt(e,t){let r=Ot(24),s=ln(t,r).encrypt(e);return new Uint8Array([...r,...s])}async function st(e,t){let r=e.slice(0,24),n=e.slice(24);return ln(t,r).decrypt(n)}async function gr(e){let t=e,r=wo(t),n=Le(r),s;try{let d=await globalThis.crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]);s=await globalThis.crypto.subtle.exportKey("jwk",d)}finally{r.fill(0),new Uint8Array(n).fill(0)}if(typeof s.x!=="string")throw Error("Ed25519 JWK missing x");let o=s.x;s.d=void 0;let i=await globalThis.crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:o},{name:"Ed25519"},!0,["verify"]),c=new Uint8Array(await globalThis.crypto.subtle.exportKey("raw",i)),u=new Uint8Array(64);return u.set(t,0),u.set(c,32),{keyType:"ed25519",privateKey:u,publicKey:c}}async function za(e){let t=e.subarray(0,32),r=wo(t),n=Le(r);try{return await globalThis.crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!1,["sign"])}finally{r.fill(0),new Uint8Array(n).fill(0)}}async function Ya(e){return await globalThis.crypto.subtle.importKey("raw",Le(e),{name:"Ed25519"},!1,["verify"])}async function xn(e,t){let r=Po(e),n=await za(t),s=await globalThis.crypto.subtle.sign({name:"Ed25519"},n,Le(r));return new Uint8Array(s)}async function Ja(e,t,r){let n=Po(t);try{return await globalThis.crypto.subtle.verify({name:"Ed25519"},r,Le(e),Le(n))}catch{return!1}}async function Ft(e,t){if(t===void 0)return gn(e);return gn(e,t)}async function Pn(){let e=await Ot(32);e[0]&=248,e[31]&=127,e[31]|=64;let[t,r]=ho(e);if(r!==0||t===void 0)throw e.fill(0),Error("X25519 scalar brand failed");let n=bo(t),s=xo(t),o=Le(s);try{let i=await globalThis.crypto.subtle.importKey("pkcs8",o,{name:"X25519"},!0,["deriveBits"]),c=await globalThis.crypto.subtle.exportKey("jwk",i);if(typeof c.x!=="string")throw Error("X25519 JWK missing x");let u=Ls(c.x);if(c.d=void 0,!G(u,n))throw Error("X25519 WebCrypto pub != RFC 7748");return{priv:t,pub:n}}catch(i){throw t.fill(0),i}finally{s.fill(0),new Uint8Array(o).fill(0)}}async function Eo(e,t){let r=xo(e),n=Le(r);try{let s=await globalThis.crypto.subtle.importKey("pkcs8",n,{name:"X25519"},!1,["deriveBits"]),o=await globalThis.crypto.subtle.importKey("raw",Le(t),{name:"X25519"},!1,[]),i=await globalThis.crypto.subtle.deriveBits({name:"X25519",public:o},s,256);return new Uint8Array(i)}catch{return Sn(e,t)}finally{r.fill(0),new Uint8Array(n).fill(0)}}function Za(e){return Object.freeze(e),e}var bn,In,Ao;var St=_(()=>{Gs();to();mo();ce();D();Io();bn=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);In=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);Ao=Za({genRandomBytes:$a,gen256BitSecureRandomSeed:wn,encryptXSalsa20Poly1305Combined:gt,decryptXSalsa20Poly1305Combined:st,deriveEd25519KeyPair:gr,signEd25519:xn,importVerifyKey:Ya,checkSigEd25519:Ja,blake3:Ft})});function ec(e,t){return e}function ko(e){return e}function Fe(e,t){if(e.byteLength!==z)return a(10);return f(ko(e))}function We(e){return Fe(e,Y.HostRLM)}function tc(e){if(e instanceof Uint8Array)return f(e);let t=new O,r=Kt.encode(t,e);if(r!==0)return a(r);return f(t.result())}async function Do(e,t){try{return f(await Ft(e,t))}catch{return a(29)}}async function rc({parent:e,purpose:t}){let[r,n]=await Do(e,{context:t});if(n!==0)return a(n);return f(ec(r,t))}async function nc({pdk:e,kdm:t}){let[r,n]=tc(t);if(n!==0)return a(n);let[s,o]=await Do(r,{key:e});if(o!==0)return a(o);return f(ko(s))}async function oe({parent:e,purpose:t,kdm:r}){let[n,s]=await rc({parent:e,purpose:t});if(s!==0)return a(s);try{return await nc({pdk:n,kdm:r})}finally{n.fill(0)}}var Y,wl,xl,q;var fe=_(()=>{re();tt();D();C();St();Y={Identity:"diplomatic.identity.v1",Cipher:"diplomatic.cipher.v1",Bind:"diplomatic.bind.v1",BindTag:"diplomatic.bindtag.v1",Fingerprint:"diplomatic.fingerprint.v1",Pair:"diplomatic.qrpair.v1",BagKdm:"diplomatic.bagkdm.v1",RealmKey:"diplomatic.realmKey.v1",RealmID:"diplomatic.realmID.v1",HostRLM:"diplomatic.hostRLM.v1",Export:"diplomatic.export.v1"},wl=Symbol("PurposeDerivedKey"),xl=Symbol("ChildKey"),q=Object.freeze({label:"",index:0})});function Fo(e){return e}class Xe{publicKey;idnt;realm;rlm;idKDM;realmKDM;constructor(e,t,r,n,s,o){this.publicKey=e;this.idnt=t;this.realm=r;this.rlm=n;this.idKDM=s;this.realmKDM=o}static async init(e,t,r,n,s){try{let o=await gr(Fo(e)),i=o.publicKey;o.privateKey.fill(0);let c=Object.freeze({...n}),u=Object.freeze({...s}),d=new Xe(i,e,t,r,c,u);return f(d)}catch{return e.fill(0),t.fill(0),r.fill(0),a(29)}}async sign(e){let t;try{t=await gr(Fo(this.idnt))}catch{return a(29)}try{return f(await xn(e,t.privateKey))}catch{return a(29)}finally{t.privateKey.fill(0)}}async bagKDM(e){let[t,r]=await oe({parent:this.idnt,purpose:Y.BagKdm,kdm:e});if(r!==0)return a(r);try{return f(t.slice(0,Oe))}finally{t.fill(0)}}async encrypt(e,t){let[r,n]=await this.#e(e.slice());if(n!==0)return a(n);try{return f(await gt(t,r))}catch{return a(29)}finally{r.fill(0)}}async decrypt(e,t){let[r,n]=await this.#e(e.slice());if(n!==0)return a(n);try{return f(await st(t,r))}catch{return a(20)}finally{r.fill(0)}}async#e(e){return oe({parent:this.realm,purpose:Y.Cipher,kdm:e})}}function Wo(e){for(let t of Object.getOwnPropertyNames(e)){if(cc.has(t))continue;let r=Object.getOwnPropertyDescriptor(e,t);if(r===void 0||typeof r.value!=="function")continue;Object.defineProperty(e,t,{value:r.value,writable:!1,configurable:!1})}}var cc;var Un=_(()=>{D();C();fe();St();cc=new Set(["constructor","prototype","length","name"]);Wo(Xe);Wo(Xe.prototype)});async function jo(e,t){return oe({parent:e,purpose:Y.RealmKey,kdm:t})}async function Xo(e,t){return oe({parent:e,purpose:Y.RealmID,kdm:t})}async function Er(e,t){return oe({parent:e,purpose:Y.HostRLM,kdm:t})}var Rn=_(()=>{fe()});function ot(e){if(e.byteLength!==Yo)return a(10);return f(e)}var xy,Py,Ae=32,Yo;var $t=_(()=>{D();C();xy=Symbol("MasterSeed"),Py=Symbol("SealedMasterKey"),Yo=24+Ae+16});var Kr;var $n=_(()=>{D();C();Kr={encode(e,t){let r=e.writeVarString(t.handle);if(r!==0)return r;let n=e.writeVarString(t.label);if(n!==0)return n;return e.writeVarInt(t.idx??0)},decode(e){let[t,r]=e.readVarString();if(r!==0)return a(r);let[n,s]=e.readVarString();if(s!==0)return a(s);let[o,i]=e.readVarInt();if(i!==0)return a(i);return f({handle:t,label:n,idx:o})}}});var zn;var xi=_(()=>{D();C();$n();$n();zn={encode(e,t){let r=e.writeVarInt(t.hosts.length);if(r!==0)return r;for(let n of t.hosts){let s=e.writeStruct(Kr,n);if(s!==0)return s}return 0},decode(e){let[t,r]=e.readVarInt();if(r!==0)return a(r);if(t===void 0||t<0)return a(10);let n=[];for(let s=0;s<t;s++){let[o,i]=e.readStruct(Kr);if(i!==0)return a(i);if(o===void 0)return a(14);n.push(o)}return f({hosts:n})}}});function Pi(e){if(e.byteLength!==Bt)return a(10);return f(e)}function Ei(e){if(e.byteLength<Cc)return a(10);return f(e)}async function Ai(e,t,r,n){if(t.byteLength!==Bt)return a(10);let s;try{s=await Eo(e,t)}catch{return a(29)}try{if(s.byteLength!==Bt||s.every((i)=>i===0))return a(10);let o=pt(r,n);try{let[i,c]=await oe({parent:s,purpose:Y.Pair,kdm:o});if(c!==0)return a(c);return f(i)}finally{o.fill(0)}}finally{s.fill(0)}}async function ki(e){let t;try{t=await Pn()}catch{return a(29)}try{let[r,n]=await Ai(t.priv,e,e,t.pub);if(n!==0)return a(n);return f({key:r,pub:t.pub})}finally{t.priv.fill(0)}}function Di(e){for(let t of Object.getOwnPropertyNames(e)){if(Uc.has(t))continue;let r=Object.getOwnPropertyDescriptor(e,t);if(r===void 0||typeof r.value!=="function")continue;Object.defineProperty(e,t,{value:r.value,writable:!1,configurable:!1})}}class vt{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(){let e;try{let t=await Pn();e=t.priv;let[r,n]=Pi(t.pub);if(n!==0)return a(n);let s=new vt(e,r);return e=void 0,f(s)}catch{return a(29)}finally{e?.fill(0)}}wipe(){this.#e.fill(0)}dhkeReq(){let e=this.#t.slice(),[t,r]=Pi(e);if(r!==0)return a(r);return f(t)}async finish(e){let t=e.subarray(0,Bt),r=e.subarray(Bt),[n,s]=await Ai(this.#e,t,this.#t,t);if(s!==0)return a(s);let o;try{try{o=await st(r,n)}catch{return a(20)}let{fromSeedHosts:i}=await Promise.resolve().then(() => (tr(),vi)),c=i(o);if(c[1]===0)this.wipe();return c}finally{n.fill(0),o?.fill(0)}}}var Bt=32,Cc,mg,hg,Uc;var Bi=_(()=>{ce();D();C();fe();St();Cc=Bt+24+16,mg=Symbol("DHKEReq"),hg=Symbol("DHKEResp");Uc=new Set(["constructor","prototype","length","name"]);Di(vt);Di(vt.prototype)});function Ce(e){let t=new Uint8Array(e);if(e>0)crypto.getRandomValues(t);return t}function Kc(e){return e.trim().toLowerCase().replace(/\.$/,"")||"localhost"}function Ue(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function Or(e){if(e instanceof ArrayBuffer)return new Uint8Array(e).slice();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice()}function Qe(e){if(e?.rpId!==void 0)return f(e.rpId);if(typeof location>"u")return a(9);return f(Kc(location.hostname))}function De(e){if(e instanceof Error){Mi=e.message===""?e.name:`${e.name}: ${e.message}`;return}Mi=String(e)}function qr(e){if(!(e instanceof Error))return!1;return e.name==="NotAllowedError"&&e.message.toLowerCase().includes("does not have focus")}function Ci(){if(typeof document>"u")return!0;return document.visibilityState!=="hidden"}function Mt(){if(typeof globalThis.focus!=="function")return;try{globalThis.focus()}catch{}}function Nr(e=2500){if(Ci())return Mt(),Promise.resolve();return new Promise((t)=>{let r=()=>{clearTimeout(s),document.removeEventListener("visibilitychange",n),Mt(),t()},n=()=>{if(Ci())r()},s=setTimeout(r,e);document.addEventListener("visibilitychange",n),n()})}async function _r(e){await Nr();try{return await navigator.credentials.create(e)}catch(t){if(!qr(t))throw t;return Mt(),await navigator.credentials.create(e)}}async function Fr(e){await Nr();try{return await navigator.credentials.get(e)}catch(t){if(!qr(t))throw t;return Mt(),await navigator.credentials.get(e)}}function $e(){if(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")return 24;return 0}function ze(e){if(e===null||e.type!==ke||!("rawId"in e)||typeof e.getClientExtensionResults!=="function")return a(27);return f(e)}function Jn(e){if(e==="platform"||e==="cross-platform")return e;return}function Ri(e){if(/iPhone|iPad|iPod/i.test(e))return"ios";if(/Android/i.test(e))return"android";if(/Mac OS X|Macintosh/i.test(e))return"macos";if(/Windows/i.test(e))return"windows";if(/Linux/i.test(e))return"linux";return"other"}function Zn(e){let t=e.response;if(!("getTransports"in t))return;let r=t.getTransports;if(typeof r!=="function")return;let n=r.call(t);if(!Array.isArray(n))return;let s=[];for(let o of n)if(typeof o==="string"&&o.length>0)s.push(o);return s.length===0?void 0:s}function Hi(e){let t=e.response;if(!("getAuthenticatorData"in t))return;let r=t.getAuthenticatorData;if(typeof r!=="function")return;let n=r.call(t);if(!(n instanceof ArrayBuffer))return;let s=new Uint8Array(n);if(s.byteLength<Yn+Ui)return;let o=s[Vc];if(o===void 0||(o&Lc)===0)return;return s.slice(Yn,Yn+Ui)}var Ge=32,Vr="DIPLOMATIC",ke="public-key",Rc=-7,Hc=-8,Tc=-257,Lr,Mi="",Vc=32,Lc=64,Yn=37,Ui=16;var Ct=_(()=>{D();C();Lr=[{type:ke,alg:Rc},{type:ke,alg:Hc},{type:ke,alg:Tc}]});async function Ti(e){let t=$e();if(t!==0)return a(t);let[r,n]=Qe(e);if(n!==0)return a(n);if(r===void 0)return a(9);let s=e?.userName??e?.rpName??r,o={residentKey:"required",requireResidentKey:!0,userVerification:"required"};if(e?.authenticatorAttachment!==void 0)o.authenticatorAttachment=e.authenticatorAttachment;let i={largeBlob:{support:"required"}},c;try{c=await _r({publicKey:{challenge:Ce(Ge),rp:{id:r,name:e?.rpName??Vr},user:{id:Ce(16),name:s,displayName:s},pubKeyCredParams:Lr,authenticatorSelection:o,extensions:i,...e?.hints!==void 0?{hints:e.hints}:{}}})}catch(p){return De(p),a(30)}let[u,d]=ze(c);if(d!==0)return a(d);if(u===void 0)return a(27);if(u.getClientExtensionResults().largeBlob?.supported!==!0)return a(30);return f(new Uint8Array(u.rawId))}async function es(e,t,r,n){let s={challenge:Ce(Ge),rpId:e,userVerification:"preferred"};if(t?.hints!==void 0)s.hints=t.hints;if(r!==void 0)s.allowCredentials=[{type:ke,id:Ue(r)}];if(n!==void 0)s.extensions=n;let o;try{o=await Fr({publicKey:s})}catch(u){return De(u),a(30)}let[i,c]=ze(o);if(c!==0)return a(c);if(i===void 0)return a(27);return f(i)}async function Ki(e,t){let r=$e();if(r!==0)return a(r);let[n,s]=Qe(t);if(s!==0)return a(s);if(n===void 0)return a(9);let o=e;if(o===void 0){let[p,y]=await es(n,t);if(y!==0&&t?.hints!==void 0)[p,y]=await es(n,{rpId:t.rpId,rpName:t.rpName});if(y!==0)return a(y);if(p===void 0)return a(27);o=new Uint8Array(p.rawId)}let[i,c]=await es(n,t,o,{largeBlob:{read:!0}});if(c!==0)return a(c);if(i===void 0)return a(27);let d=i.getClientExtensionResults().largeBlob;if(d===void 0||d.blob===void 0)return a(7);let l=Or(d.blob);if(l.byteLength===0)return a(7);return f({blob:l,credId:new Uint8Array(i.rawId)})}var ts=_(()=>{D();C();Ct()});var Wr="";function qc(){if(typeof Wr!=="string"||Wr.length===0)throw Error("[DIPLOMATIC] worker source not embedded; run pkg build before spawn");return atob(Wr)}function Nc(){if(jr!==void 0)return jr;let e=new Blob([qc()],{type:"text/javascript"});return jr=URL.createObjectURL(e),jr}function Vi(){if(Xr===void 0)throw Error("[DIPLOMATIC] Worker API unavailable; cannot spawn sync worker");return new Xr(Nc(),{type:"module"})}function Li(e,t,r){if(rs===void 0)throw Error("[DIPLOMATIC] Worker API unavailable; cannot post to sync worker");if(r!==void 0&&r.length>0)rs.call(e,t,{transfer:r});else rs.call(e,t)}var Xr,rs,jr;var Oi=_(()=>{Xr=typeof globalThis.Worker==="function"?globalThis.Worker:void 0,rs=Xr===void 0?void 0:Xr.prototype.postMessage});async function qi(e){if(e?.credId!==void 0)return f(e.credId);return Ti(e)}async function ns(e,t,r){let n=$e();if(n!==0)return n;let[s,o]=Qe(r);if(o!==0)return o;if(s===void 0)return 9;await Nr();let i=new Uint8Array(t.byteLength);i.set(t);let c={largeBlob:{write:i.buffer}},u={publicKey:{challenge:Ce(Ge),rpId:s,allowCredentials:[{type:ke,id:Ue(e)}],userVerification:"required",extensions:c,...r?.hints!==void 0?{hints:r.hints}:{}}},d;try{try{d=await navigator.credentials.get(u)}catch(m){if(!qr(m))return De(m),30;Mt();try{d=await navigator.credentials.get(u)}catch(h){return De(h),30}}}catch(m){return De(m),30}finally{i.fill(0)}let[l,p]=ze(d);if(p!==0)return p;if(l===void 0)return 27;if(l.getClientExtensionResults().largeBlob?.written!==!0)return 30;return 0}function Ni(e,t){return ns(e,new Uint8Array(Ae),t)}var _i=_(()=>{D();$t();C();Ct();ts()});var ss,rr="diplomatic-prf";var os=_(()=>{Ct();ss=new TextEncoder().encode("diplomatic.prf.v1")});function _c(e){if(e===void 0)return[];if(e instanceof Uint8Array)return[e];return e.filter((t)=>t.byteLength>0)}function Fc(e){if(!(e instanceof Error))return!1;return e.name==="NotSupportedError"||e.name==="TypeError"}function Fi(e){if(e===void 0)return;let t=Or(e);if(t.byteLength<is){t.fill(0);return}if(t.byteLength===is)return t;let r=t.slice(0,is);return t.fill(0),r}async function Wc(e){let t=$e();if(t!==0)return a(t);let[r,n]=Qe(e);if(n!==0)return a(n);let s=e?.userName??rr,o=e?.displayName??s,i=Ce(16),c=e?.authenticatorAttachment==="cross-platform",u={residentKey:c?"discouraged":"required",requireResidentKey:!c,userVerification:c?"preferred":"required"};if(e?.authenticatorAttachment!==void 0)u.authenticatorAttachment=e.authenticatorAttachment;let d={challenge:Ce(Ge),rp:{id:r,name:e?.rpName??Vr},user:{id:i,name:s,displayName:o},pubKeyCredParams:Lr,authenticatorSelection:u,...e?.hints!==void 0?{hints:e.hints}:{},...e?.excludeCredentials!==void 0&&e.excludeCredentials.length>0?{excludeCredentials:e.excludeCredentials.map((x)=>({type:ke,id:Ue(x)}))}:{}},l=e?.salt!==void 0?Ue(e.salt):void 0,p=(x)=>_r({publicKey:{...d,extensions:x&&l!==void 0?{prf:{eval:{first:l}}}:{prf:{}}}}),y;try{y=await p(l!==void 0)}catch(x){if(l===void 0||!Fc(x))return De(x),a(30);try{y=await p(!1)}catch(E){return De(E),a(30)}}let[m,h]=ze(y);if(h!==0)return a(h);let g=m.getClientExtensionResults(),S=Fi(g.prf?.results?.first),b=g.prf?.enabled===!0||S!==void 0;if(c&&S!==void 0)S.fill(0);return f({credId:new Uint8Array(m.rawId),userId:new Uint8Array(i),prfEnabled:b,prf:c?void 0:S,attachment:Jn(m.authenticatorAttachment),transports:Zn(m),aaguid:Hi(m)})}async function Wi(e){let t=$e();if(t!==0)return a(t);let[r,n]=Qe(e);if(n!==0)return a(n);let s=e?.salt??ss,i={eval:{first:Ue(s)}},c=e?.salts;if(c!==void 0&&c.length>0){let g={};for(let S of c){if(S.credId.byteLength===0)continue;g[Vs(S.credId)]={first:Ue(S.salt)}}i.evalByCredential=g}let u={challenge:Ce(Ge),rpId:r,userVerification:"preferred",extensions:{prf:i}};if(e?.hints!==void 0)u.hints=e.hints;let d=_c(e?.credId);if(d.length>0)u.allowCredentials=d.map((g)=>({type:ke,id:Ue(g)}));let l;try{l=await Fr({publicKey:u})}catch(g){return De(g),a(30)}let[p,y]=ze(l);if(y!==0)return a(y);let m=p.getClientExtensionResults().prf?.results;if(m?.first===void 0)return a(7);let h=Fi(m.first);if(h===void 0)return a(27);return f({prf:h,credId:new Uint8Array(p.rawId),attachment:Jn(p.authenticatorAttachment),transports:Zn(p)})}async function ji(e){let t=e?.salt??ss,r=e?.credId,n=r,s=e?.createCredIfNeeded===!0&&(r===void 0||!(r instanceof Uint8Array)&&r.length===0),o,i;if(s){let[l,p]=await Wc({rpId:e?.rpId,rpName:e?.rpName,userName:e?.userName??rr,displayName:e?.displayName,authenticatorAttachment:e?.authenticatorAttachment,hints:e?.hints,excludeCredentials:e?.excludeCredentials,salt:t});if(p!==0)return a(p);if(!l.prfEnabled)return a(30);n=l.credId,o=l,i=l.prf}let c=(l,p,y,m)=>f({prf:l,salt:t.slice(),credId:p.slice(),userId:o?.userId===void 0?void 0:o.userId.slice(),attachment:y??o?.attachment,transports:m??o?.transports,aaguid:o?.aaguid===void 0?void 0:o.aaguid.slice()});if(i!==void 0&&o!==void 0)return c(i,o.credId,o.attachment,o.transports);let[u,d]=await Wi({rpId:e?.rpId,rpName:e?.rpName,credId:n,salt:t,hints:e?.hints});if(d!==0)return a(d);return c(u.prf,u.credId,u.attachment,u.transports)}async function Xi(e,t){let r=[],n=[],s=!1;for(let d of e){if(d.credId.byteLength===0)continue;r.push(d.credId);let l=d.salt??t.salt;if(!G(l,t.salt))s=!0;n.push({credId:d.credId,salt:l})}let[o,i]=await Wi({rpId:t.rpId,rpName:t.rpName,hints:t.hints,credId:r.length>0?r:void 0,salt:t.salt,salts:s?n:void 0});if(i!==0)return a(i);let c=e.find((d)=>G(d.credId,o.credId)),u=c===void 0?e:[c,...e.filter((d)=>d!==c)];return f({prf:o.prf,credId:o.credId.slice(),order:u})}var is=32;var Gi=_(()=>{ce();D();C();Ct();os()});var vi={};Aa(vi,{Enclave:()=>ye,MUSEC_MIN_LEN:()=>Qr,asMasterSeed:()=>Gr,fromSeedHosts:()=>$i});function $i(e){if(e.byteLength===0||e.every((c)=>c===0))return a(22);if(e.byteLength<Ae+1)return a(14);let t=e.subarray(0,Ae);if(t.every((c)=>c===0))return a(22);let r=new L(e.subarray(Ae)),[n,s]=r.readStruct(zn);if(s!==0)return a(s);if(n===void 0)return a(14);if(!r.done())return a(14);let[o,i]=ye.fromBytes(t);if(i!==0)return a(i);return f({enclave:o,hosts:n.hosts.map((c)=>({...c}))})}function Gr(e){if(e.byteLength!==Ae)return a(10);return[e,0]}async function Qi(e){if(e.byteLength<Xc)return a(10);let t=Y.Bind;return oe({parent:e,purpose:t,kdm:q})}class Ye{#e;constructor(e){this.#e=e}static async mix(e){let t,r,n;try{if(e.byteLength<Qr)return a(10);t=await wn(),r=new Uint8Array(t.byteLength+e.byteLength),r.set(t,0),r.set(e,t.byteLength),n=await Ft(r);let[s,o]=Gr(n);if(o!==0)return a(o);let i=new Ye(s);return n=void 0,f(i)}finally{t?.fill(0),r?.fill(0),e.fill(0),n?.fill(0)}}static importSeed(e){let[t,r]=Gr(e);if(r!==0)return a(r);let[n,s]=Gr(t.slice());if(s!==0)return a(s);return f(new Ye(n))}static async unseal(e,t){let[,r]=ot(e);if(r!==0)return a(r);let[n,s]=await Qi(t);if(s!==0)return a(s);let o;try{try{o=await st(e,n)}catch{return a(20)}return Ye.importSeed(o)}finally{n.fill(0),o?.fill(0)}}async idnt(e){let t=Y.Identity;return oe({parent:this.#e,purpose:t,kdm:e})}async realmKey(e){return jo(this.#e,e)}async realmID(e){return Xo(this.#e,e)}async exportFileKey(e){let t=Y.Export;return oe({parent:this.#e,purpose:t,kdm:e})}async fingerprint(e){let t=Y.Fingerprint;return await oe({parent:this.#e,purpose:t,kdm:e})}async bindTag(e){let t=Y.BindTag;return await oe({parent:this.#e,purpose:t,kdm:e})}async seal(e){let[t,r]=await Qi(e);if(r!==0)return a(r);try{let n=await gt(this.#e,t);return ot(n)}catch{return a(12)}finally{t.fill(0)}}async sealSeedHosts(e,t){let[r,n]=this.#t(t);if(n!==0)return a(n);try{return f(await gt(r,e))}catch{return a(12)}finally{r.fill(0)}}#t(e){let t=new O,r=t.writeStruct(zn,{hosts:e.map((o)=>({handle:o.handle,label:o.label,idx:o.idx??0}))});if(r!==0)return a(r);let n=t.result(),s=new Uint8Array(Ae+n.byteLength);return s.set(this.#e,0),s.set(n,Ae),[s,0]}async persistToLargeBlob(e,t){let[r,n]=await qi(t);if(n!==0)return a(n);let[s,o]=this.#t(e);if(o!==0)return a(o);try{let i=await ns(r,s,t);if(i!==0)return a(i);return f(r)}finally{s.fill(0)}}async dumpToTTY(){return 21}copyForWorker(){return this.#e.slice()}}class ye{#e;constructor(e){this.#e=e}static async fromRandom(e){try{let[t,r]=await Ye.mix(e);if(r!==0)return a(r);return f(new ye(t))}finally{e.fill(0)}}static fromBytes(e){let[t,r]=Ye.importSeed(e);if(r!==0)return a(r);return f(new ye(t))}async sealWithPasskey(e){let[t,r]=await ji(e);if(r!==0)return a(r);try{let[n,s]=await this.#e.seal(t.prf);if(s!==0)return a(s);return f({sealedMaster:n,salt:t.salt,credId:t.credId,userId:t.userId,attachment:t.attachment,transports:t.transports,aaguid:t.aaguid})}finally{t.prf.fill(0)}}async bind(e,t){if(t!==void 0)for(let i of t){if(i.tag.byteLength!==jc)return a(10);let[c,u]=await this.#e.bindTag(i.credId);if(u!==0)return a(u);try{if(!ir(c,i.tag))return a(10)}finally{c.fill(0)}}let[r,n]=await this.sealWithPasskey(e);if(n!==0)return a(n);let[s,o]=await this.#e.bindTag(r.credId);if(o!==0)return a(o);return f({...r,tag:s})}static async unsealWithPasskey(e,t){if(e.length===0)return a(22);let[r,n]=await Xi(e,t);if(n!==0)return a(n);try{for(let s of r.order){let[o,i]=await Ye.unseal(s.sealedMaster,r.prf);if(i===0)return f({enclave:new ye(o),credId:r.credId})}return a(20)}finally{r.prf.fill(0)}}async sealWithIKM(e){try{return await this.#e.seal(e)}finally{e.fill(0)}}static async unsealWithIKM(e,t){try{let[r,n]=await Ye.unseal(e,t);if(n!==0)return a(n);return f(new ye(r))}finally{t.fill(0)}}async persistToLargeBlob(e=[],t){return this.#e.persistToLargeBlob(e,t)}static async fromLargeBlob(e){let[t,r]=await Ki(e?.credId,e);if(r!==0)return a(r);try{let[n,s]=$i(t.blob);if(s!==0)return a(s);return f({...n,credId:t.credId})}finally{t.blob.fill(0)}}static clearLargeBlob(e,t){return Ni(e,t)}async dumpToTTY(){return this.#e.dumpToTTY()}static pairRequest(){return vt.create()}async pairAccept(e,t,r){if(r.userControlsBothSidesOfPair!==!0)return a(10);let[n,s]=await ki(e);if(s!==0)return a(s);try{let[o,i]=await this.#e.sealSeedHosts(n.key,t);if(i!==0)return a(i);return Ei(pt(n.pub,o))}finally{n.key.fill(0)}}spawnSyncWorker(e){let t=Vi(),r=this.#e.copyForWorker();return Li(t,{id:e.id,op:"setSeed",seed:r,persist:e.persist},[r.buffer]),t}async exportKey(e){if(e.byteLength!==z)return a(10);return this.#e.exportFileKey(e)}async bagman(e,t){let[r,n]=await this.#e.idnt(e);if(n!==0)return a(n);let[s,o]=await this.#e.realmKey(t);if(o!==0)return r.fill(0),a(o);let[i,c]=await this.#e.realmID(t);if(c!==0)return r.fill(0),s.fill(0),a(c);try{let[u,d]=await Er(i,e);if(d!==0)return r.fill(0),s.fill(0),a(d);return Xe.init(r,s,u,e,t)}finally{i.fill(0)}}async fingerprint(e=q){return this.#e.fingerprint(e)}}function zi(e){for(let t of Object.getOwnPropertyNames(e)){if(Gc.has(t))continue;let r=Object.getOwnPropertyDescriptor(e,t);if(r===void 0||typeof r.value!=="function")continue;Object.defineProperty(e,t,{value:r.value,writable:!1,configurable:!1})}}var jc=32,Xc=16,Qr=32,Gc;var tr=_(()=>{ce();re();xi();D();$t();C();fe();St();Bi();ts();Oi();_i();Gi();Rn();Un();Gc=new Set(["constructor","prototype","length","name"]);zi(ye);zi(ye.prototype)});D();function Ts(e){if(!e||typeof e!=="object")return!1;if(!("op"in e)||!("id"in e))return!1;return typeof e.op==="string"&&typeof e.id==="number"}class Ht{listeners=new Map;addEventListener(e,t){let r=this.listeners.get(e);if(!r)r=new Set,this.listeners.set(e,r);return r.add(t),()=>{this.removeEventListener(e,t)}}removeEventListener(e,t){let r=this.listeners.get(e);if(r){if(r.delete(t),r.size===0)this.listeners.delete(e)}}emit(e,t){let r=this.listeners.get(e);if(r){let n=Array.from(r);for(let s of n)s(t)}}emitAll(e){let t=Array.from(this.listeners.keys());for(let r of t)this.emit(r,e)}}class Ze{getter;static eventName="update";emitter;constructor(e){this.getter=e;this.emitter=new Ht}get=()=>this.getter();async emit(){let e=await this.getter();queueMicrotask(()=>this.emitter.emit(Ze.eventName,e))}listen(e){return this.emitter.addEventListener(Ze.eventName,e),()=>{this.emitter.removeEventListener(Ze.eventName,e)}}}re();D();C();async function Zr(e,t){let r=new O,n=r.writeDate(t);if(n!==0)return a(n);let s=r.result(),[o,i]=await e.sign(s);if(i!==0)return a(i);return f({pubKey:e.publicKey,sig:o,timestamp:t})}async function Ne(e,t,r){let n=r.now().getTime(),s=e.timestamp.getTime();if(Math.abs(n-s)>Rs)return 4;let i=new O;i.writeDate(e.timestamp);let c=i.result(),u;try{u=await t.importVerifyKey(e.pubKey)}catch{return 29}if(!await t.checkSigEd25519(e.sig,c,u))return 3;return 0}re();re();D();re();D();C();var ae={encode(e,t){let r=e.writeVarBytes(t.id);if(r!==0)return r;let n=e.writeDate(t.ts);if(n!==0)return n;return 0},decode(e){let[t,r]=e.readVarBytes();if(r!==0)return a(r);let[n,s]=e.readDate();if(s!==0)return a(s);return f({id:t,ts:n})}};function ft(e){let t=new O,r=t.writeStruct(ae,e);if(r!==0)return a(r);let n=t.result();return f(n)}C();var Ie={encode(e,t){let r=e.writeVarString(t.typ??"");if(r!==0)return r;let n=e.writeVarBytes(t.eid);if(n!==0)return n;let s=e.writeVarInt(t.off);if(s!==0)return s;let o=e.writeVarInt(t.ctr);if(o!==0)return o;let i=e.writeVarInt(t.len);if(i!==0)return i;if(t.hsh)e.writeBytes(t.hsh);return 0},decode(e){let[t,r]=e.readVarString();if(r!==0)return a(r);let[n,s]=e.readVarBytes();if(s!==0)return a(s);let o=new L(n),[,i]=ae.decode(o);if(i!==0)return a(i);let[c,u]=e.readVarInt();if(u!==0)return a(u);let[d,l]=e.readVarInt();if(l!==0)return a(l);let[p,y]=e.readVarInt();if(y!==0)return a(y);let m;if(p>0){let[h,g]=e.readBytes(qe);if(g!==0)return a(g);m=h}return f({typ:t,eid:n,off:c,ctr:d,len:p,hsh:m})}};D();ce();C();function ar(e,t){return pt(e,t)}function Os(e,t,r){if(e.rlm.byteLength!==z)return Promise.resolve(!1);return r.checkSigEd25519(e.sig,ar(e.rlm,e.headCph),t)}async function qs(e,t,r){let n;if(e.bod&&e.len>0)n=await r.blake3(e.bod);let s=new O,o=Ie.encode(s,{...e,hsh:n});if(o!==0)return a(o);let i=s.result(),[c,u]=await t.bagKDM(i);if(u!==0)return a(u);let d=t.rlm,[l,p]=await t.encrypt(c,i);if(p!==0)return a(p);let y=new Uint8Array(0);if(e.bod){let[S,b]=await t.encrypt(c,e.bod);if(b!==0)return a(b);y=S}let m=ar(d,l),[h,g]=await t.sign(m);if(g!==0)return a(g);return f({rlm:d,sig:h,kdm:c,headCph:l,bodyCph:y})}async function en(e,t,r,n,s){let o=new L(e),[i,c]=Ie.decode(o);if(c!==0)return a(14);let u;if(t&&t.length>0){let[y,m]=await r.decrypt(t);if(m!==0)return a(m);u=y}let d=i.hsh&&u===void 0,l=i.hsh===void 0&&u!==void 0;if(d||l)return a(19);if(i.hsh&&u){let y=await n.blake3(u);if(!G(y,i.hsh))return a(19)}let p=s??await n.blake3(e);return f({msgHead:i,bod:u,headHash:p})}class tn{now(){return new Date}}function Ns(e,t,r,n){let s=t.getTime()-e.getTime(),o=r.getTime()-n.getTime();return(s+o)/2}re();tt();D();C();D();C();var Vt={encode(e,t){if(e.writeVarInt(t.quota),t.quota>0){if(t.usage===void 0)return 9;e.writeVarInt(t.usage)}return 0},decode(e){let[t,r]=e.readVarInt();if(r!==0)return a(r);let n;if(t>0){let[s,o]=e.readVarInt();if(o!==0)return a(o);n=s}return f({quota:t,usage:n})}};var rn={encode(e,t){e.writeBytes(new Uint8Array([t.status]));let r=e.writeDate(t.timeRcvd);if(r!==0)return r;let n=e.writeDate(t.timeSent);if(n!==0)return n;let s=e.writeVarInt(t.subscription.term);if(s!==0)return s;let o=e.writeVarInt(t.subscription.elapsed);if(o!==0)return o;let i=e.writeStruct(Vt,t.subscription.stat);if(i!==0)return i;let c=e.writeStruct(Vt,t.subscription.dyn);if(c!==0)return c;return 0},decode(e){let[t,r]=e.readBytes(1);if(r!==0)return a(r);let n=t[0],[s,o]=e.readDate();if(o!==0)return a(o);let[i,c]=e.readDate();if(c!==0)return a(c);let[u,d]=e.readVarInt();if(d!==0)return a(d);let[l,p]=e.readVarInt();if(p!==0)return a(p);let[y,m]=e.readStruct(Vt);if(m!==0)return a(m);let[h,g]=e.readStruct(Vt);if(g!==0)return a(g);return f({status:n,timeRcvd:s,timeSent:i,subscription:{term:u,elapsed:l,stat:y,dyn:h}})}};D();fe();re();D();D();D();C();var En={encode(e,t){let r=e.writeVarBytes(t.headCph);if(r!==0)return r;let n=e.writeVarInt(t.seq);if(n!==0)return n;return 0},decode(e){let[t,r]=e.readVarBytes();if(r!==0)return a(r);let[n,s]=e.readVarInt();if(s!==0)return a(s);return f({headCph:t,seq:n})}};D();C();var ge={encode(e,t){e.writeBytes(t.pubKey),e.writeBytes(t.sig);let r=e.writeDate(t.timestamp);if(r!==0)return r;return 0},decode(e){let[t,r]=e.readBytes(Us);if(r!==0)return a(r);let[n,s]=e.readBytes(Be);if(s!==0)return a(s);let[o,i]=e.readDate();if(i!==0)return a(i);return f({pubKey:t,sig:n,timestamp:o})}};fe();C();var Bo={encode(e,t){if(t.rlm.byteLength!==z)return 10;return e.writeBytes(t.rlm),e.writeVarInt(t.seq)},decode(e){let[t,r]=e.readBytes(z);if(r!==0)return a(r);let[n,s]=We(t);if(s!==0)return a(s);let[o,i]=e.readVarInt();if(i!==0)return a(i);return f({rlm:n,seq:o})}},vo={async encodeReq(e,t,r,n,s){let o=s.writeStruct(ge,r);if(o!==0)return o;return s.writeStruct(Bo,n)},async handleReq(e,t,r){let{clock:n,crypto:s,storage:o}=e,[i,c]=t.readStruct(ge);if(c!==0)return c;let u=await Ne(i,s,n);if(u!==0)return u;let{pubKey:d}=i,[l,p]=await o.hasUser(d);if(p!==0)return p;if(!l)return 5;let[y,m]=t.readStruct(Bo);if(m!==0)return m;if(!t.done())return 8;let[h,g]=await o.listHeads(d,y.rlm,y.seq);if(g!==0)return g;return r.writeStructs(En,h)},decodeResp(e){return e.readStructs(En)}};D();C();var An={encode(e,t){e.writeVarInt(t.seq);let r=e.writeVarBytes(t.bodyCph);if(r!==0)return r;return 0},decode(e){let[t,r]=e.readVarInt();if(r!==0)return a(r);let[n,s]=e.readVarBytes();if(s!==0)return a(s);return f({seq:t,bodyCph:n})}};D();fe();C();var Mo={encode(e,t){if(t.rlm.byteLength!==z)return 10;e.writeBytes(t.rlm);for(let r of t.seqs){let n=e.writeVarInt(r);if(n!==0)return n}return 0},decode(e){let[t,r]=e.readBytes(z);if(r!==0)return a(r);let[n,s]=We(t);if(s!==0)return a(s);let o=[];while(!e.done()){let[i,c]=e.readVarInt();if(c!==0)return a(c);o.push(i)}return f({rlm:n,seqs:o})}},Co={async encodeReq(e,t,r,n,s){let o=s.writeStruct(ge,r);if(o!==0)return o;return s.writeStruct(Mo,n)},async handleReq(e,t,r){let{clock:n,crypto:s,storage:o}=e,[i,c]=t.readStruct(ge);if(c!==0)return c;let u=await Ne(i,s,n);if(u!==0)return u;let{pubKey:d}=i,[l,p]=await o.hasUser(d);if(p!==0)return p;if(!l)return 5;let[y,m]=t.readStruct(Mo);if(m!==0)return m;console.info(`PULL: ${y.seqs.length} bags`);let[h,g]=await o.getBodies(d,y.rlm,y.seqs);if(g!==0)return g;if(!h)return 17;for(let{seq:S,bodyCph:b}of h){let x={seq:S,bodyCph:b},E=r.writeStruct(An,x);if(E!==0)return E}return 0},decodeResp(e){return e.readStructs(An)}};re();D();fe();C();var kn={encode(e,t){if(t.rlm.byteLength!==z)return 10;if(t.sig.byteLength!==Be)return 10;e.writeBytes(t.sig),e.writeBytes(t.rlm),e.writeBytes(t.kdm);let r=e.writeVarBytes(t.headCph);if(r!==0)return r;let n=e.writeVarBytes(t.bodyCph);if(n!==0)return n;return 0},decode(e){let[t,r]=e.readBytes(Be);if(r!==0)return a(r);let[n,s]=e.readBytes(z);if(s!==0)return a(s);let[o,i]=We(n);if(i!==0)return a(i);let[c,u]=e.readBytes(Oe);if(u!==0)return a(u);let[d,l]=e.readVarBytes();if(l!==0)return a(l);let[p,y]=e.readVarBytes();if(y!==0)return a(y);return f({rlm:o,sig:t,kdm:c,headCph:d,bodyCph:p})}};D();fe();C();var Sr={encode(e,t){let r=e.writeVarInt(t.seq);if(r!==0)return r;if(t.rlm.byteLength!==z)return 10;e.writeBytes(t.rlm);let n=e.writeVarBytes(t.headCph);if(n!==0)return n;let s=t.bodyCph?t.bodyCph.length:0,o=e.writeVarInt(s);if(o!==0)return o;if(s>0){if(!t.bodyCph)return 10;e.writeBytes(t.bodyCph)}return 0},decode(e){let[t,r]=e.readVarInt();if(r!==0)return a(r);let[n,s]=e.readBytes(z);if(s!==0)return a(s);let[o,i]=We(n);if(i!==0)return a(i);let[c,u]=e.readVarBytes();if(u!==0)return a(u);let[d,l]=e.readVarInt();if(l!==0)return a(l);let p;if(d>0){let[y,m]=e.readBytes(d);if(m!==0)return a(m);p=y}return f({seq:t,rlm:o,headCph:c,bodyCph:p})}};D();C();var br={encode(e,t){e.writeBytes(t.sig),e.writeBytes(t.kdm);let r=e.writeVarBytes(t.headCph);if(r!==0)return r;return 0},decode(e){let[t,r]=e.readBytes(Be);if(r!==0)return a(r);let[n,s]=e.readBytes(Oe);if(s!==0)return a(s);let[o,i]=e.readVarBytes();if(i!==0)return a(i);return f({sig:t,kdm:n,headCph:o})}};D();C();var Wt={encode(e,t){if(e.writeVarInt(t.idx),e.writeBytes(new Uint8Array([t.status])),t.status===0)e.writeVarInt(t.seq);return 0},decode(e){let[t,r]=e.readVarInt();if(r!==0)return a(r);let[n,s]=e.readBytes(1);if(s!==0)return a(s);let o=n[0];if(o!==0)return f({idx:t,status:o});let[i,c]=e.readVarInt();if(c!==0)return a(c);return f({idx:t,status:o,seq:i})}};D();var Uo={encode(e,t){return e.writeStructs(kn,t)},decode(e){return e.readStructs(kn)}},Ro={async encodeReq(e,t,r,n,s){let o=s.writeStruct(ge,r);if(o!==0)return o;return s.writeStruct(Uo,n)},async handleReq(e,t,r){let{clock:n,crypto:s,storage:o,notifier:i}=e,[c,u]=t.readStruct(ge);if(u!==0)return u;let d=await Ne(c,s,n);if(d!==0)return d;let{pubKey:l}=c,[p,y]=await o.hasUser(l);if(y!==0)return y;if(!p)return 5;let[m,h]=t.readStruct(Uo);if(h!==0)return h;console.info(`PUSH: ${m.length} bags`);let g;try{g=await s.importVerifyKey(l)}catch{return 29}let S=[],b=[];for(let w=0;w<m.length;w++){let k=m[w];if(!await Os(k,g,s)){let U={idx:w,status:3},T=r.writeStruct(Wt,U);if(T!==0)return T;continue}S.push(w),b.push(k)}let[x,E]=await o.setBags(l,b);if(E!==0)return E;if(!x||x.length!==b.length)return 17;let P=[];for(let w=0;w<b.length;w++){let k=b[w],v=S[w],U=x[w];if(U.status!==0){let j={idx:v,status:U.status},X=r.writeStruct(Wt,j);if(X!==0)return X;continue}let T=U.seq,R=new O,V=R.writeStruct(br,k);if(V!==0)return V;let H=R.result(),I={seq:T,rlm:k.rlm,headCph:H};if(m.length===1&&k.bodyCph.length<=Hs)I.bodyCph=k.bodyCph;P.push(I);let F={idx:v,status:0,seq:T},N=r.writeStruct(Wt,F);if(N!==0)return N}if(P.length>0){let w=new O,k=w.writeStructs(Sr,P);if(k!==0)return k;let v=w.result();await Promise.resolve(i.push(l,v))}return 0},decodeResp(e){return e.readStructs(Wt)}};D();C();var Ho={async encodeReq(e,t,r,n,s){return s.writeStruct(ge,r)},async handleReq(e,t,r){let{clock:n,crypto:s,storage:o}=e,[i,c]=t.readStruct(ge);if(c!==0)return c;let u=await Ne(i,s,n);if(u!==0)return u;let{pubKey:d}=i;if(!t.done())return 8;let[l,p]=await o.addUser(d);if(p!==0)return p;return 0},decodeResp(e){return f(void 0)}};ce();re();D();class Dn{url;websocket;constructor(e){this.url=e}connected(){return this.websocket!==void 0&&this.websocket.readyState===WebSocket.OPEN}async connect(e,t,r=()=>{},n=()=>{}){let{url:s}=this;if(this.websocket)this.websocket.close(),this.websocket=void 0;let o=new O;o.writeStruct(ge,e);let i=o.result(),c=et(i);return s.searchParams.set("t",c),this.websocket=new WebSocket(s),this.websocket.binaryType="arraybuffer",this.websocket.onopen=()=>{console.log("CONNECTED"),n()},this.websocket.onclose=()=>{console.log("DISCONNECTED"),this.websocket=void 0,r()},this.websocket.onmessage=(u)=>{let d=new Uint8Array(u.data);t(d)},this.websocket.onerror=(u)=>{console.log(`ERROR: ${JSON.stringify(u)}`),this.websocket=void 0,r()},Promise.resolve(0)}disconnect(){this.websocket?.close(),this.websocket=void 0}}C();var pe={user:{path:"/user",endpoint:Ho,name:0},push:{path:"/push",endpoint:Ro,name:2},peek:{path:"/peek",endpoint:vo,name:1},pull:{path:"/pull",endpoint:Co,name:3}},sc={0:pe.user,2:pe.push,1:pe.peek,3:pe.pull},jf={[pe.user.path]:pe.user,[pe.push.path]:pe.push,[pe.peek.path]:pe.peek,[pe.pull.path]:pe.pull};class To{url;listener;constructor(e){this.url=e;this.listener=new Dn(e)}async call(e,t){let{path:r}=sc[e],n=new URL(r,this.url);try{return await oc(n,t)}catch{return a(25)}}}var Ko=(e)=>new To(e.handle);async function oc(e,t){let r=await fetch(e,{method:"POST",body:t.result().slice()});if(!r.ok)return a(24);let n=await L.fromResponse(r);return f(n)}C();class Ir{crypto;clock;transport;updateHostMeta;#e;constructor(e,t,r,n,s){this.crypto=t;this.clock=r;this.transport=n;this.updateHostMeta=s;this.#e=e}async call(e,t){let{clock:r,transport:n}=this,{endpoint:s,name:o}=e,[i,c]=await this.identity();if(c!==0)return a(c);let u=r.now(),[d,l]=await Zr(i,u);if(l!==0)return a(l);let p=new O,y=await s.encodeReq(this,i,d,t,p);if(y!==0)return a(y);let m=r.now(),[h,g]=await n.call(o,p),S=r.now();if(g!==0)return a(g);let[b,x]=h.readStruct(rn);if(x!==0)return a(x);if(b.status!==0)return a(b.status);let P={clockOffset:Ns(m,b.timeRcvd,b.timeSent,S),subscription:b.subscription},w=await this.updateHostMeta(P);if(w!==0)return a(w);return s.decodeResp(h)}bagMgrFor(e=q){return this.#e.find((t)=>_e(e,t.realmKDM))}bagMgrs(){return this.#e}add(e){if(this.bagMgrFor(e.realmKDM)!==void 0)return;this.#e.push(e)}identity=()=>{let e=this.bagMgrFor(q)??this.#e[0];if(e===void 0)return Promise.resolve(a(13));return Promise.resolve(f(e))};hostRlm=(e=q)=>{let t=this.bagMgrFor(e);if(t===void 0)return Promise.resolve(a(13));return Promise.resolve(f(t.rlm))};seal=async(e,t=q)=>{let r=this.bagMgrFor(t);if(r===void 0)return a(13);return qs(e,r,this.crypto)};register=()=>this.call(pe.user,void 0);peek=async(e,t=q)=>{let[r,n]=await this.hostRlm(t);if(n!==0)return a(n);return this.call(pe.peek,{rlm:r,seq:e})};push=(e)=>this.call(pe.push,e);pull=async(e,t=q)=>{let[r,n]=await this.hostRlm(t);if(n!==0)return a(n);return this.call(pe.pull,{rlm:r,seqs:e})};listen=async(e,t,r)=>{let{clock:n,transport:s}=this,{listener:o}=s,[i,c]=await this.identity();if(c!==0)return c;let u=n.now(),[d,l]=await Zr(i,u);if(l!==0)return l;return await o.connect(d,e,t,r)};isConnected(){let e=this.transport?.listener;if(e&&typeof e.connected==="function")return e.connected();return!0}closeListener(){this.transport?.listener?.disconnect()}}re();re();D();C();var ic=new Uint8Array(0),jt={encode(e,t){if(t.body!==void 0&&!(t.body instanceof Uint8Array))return 10;let r=e.writeVarBytes(t.pid??ic);if(r!==0)return r;let n=e.writeVarStrings(t.tags??[]);if(n!==0)return n;if(t.body!==void 0&&t.body.length>0)e.writeBytes(t.body);return 0},decode(e){let[t,r]=e.readVarBytes();if(r!==0)return a(r);let n;if(t.length>0){let u=new L(t),[d,l]=u.readStruct(ae);if(l!==0)return a(l);if(!u.done())return a(14);let[p,y]=ft(d);if(y!==0)return a(y);n=p}let[s,o]=e.readVarStrings();if(o!==0)return a(o);let i=e.readRest(),c={};if(n!==void 0)c.pid=n;if(s.length>0)c.tags=s;if(i.length>0)c.body=i;return f(c)}};function bt(e){let t=new O,r=t.writeStruct(jt,e);if(r!==0)return a(r);return f(t.result())}tt();D();fe();var mp=Symbol("DownloadKey");function wr(e){if(e===void 0)return!0;return e.label===q.label&&e.index===q.index}function Vo(e,t){return e.label===t.label&&e.index===t.index}function It(e){return`${e.label}\x00${e.index}`}function Xt(e,t=q){if(wr(t))return e.lastSeq;return e.seqs?.find((n)=>n.label===t.label&&n.index===t.index)?.lastSeq??0}function wt(e){let t=[q],r=new Set([It(q)]),n=(s,o)=>{let i=s===""&&o===0?q:{label:s,index:o},c=It(i);if(r.has(c))return;r.add(c),t.push(i)};for(let s of e){if(n(s.label,s.index),s.prior===void 0)continue;for(let o of s.prior)n(s.label,o)}return t}function xr(e,t){if(e===void 0||e==="")return q;for(let r of t)if(r.label===e)return{label:r.label,index:r.index};return{label:e,index:0}}function Pr(e){if(wr(e))return;return e}function Bn(e,t,r){let n=r??q;return wr(n)?`${e}:${t}`:`${e}:${n.label}:${n.index}:${t}`}function Lo(e,t){if(t.setLastSeq!==void 0)return t.setLastSeq;if(t.lastSeq!==void 0&&t.lastSeq>e)return t.lastSeq;return}function Oo(e){let t=0,r=[];for(let n of e)if(wr(n))t=n.lastSeq;else r.push(n);if(r.length===0)return{lastSeq:t};return{lastSeq:t,seqs:r}}D();C();function je(e){if(e===void 0)return f("");if(typeof e!=="string")return a(10);return f(e.trim())}function qo(e,t,r){let[n,s]=je(t);if(s!==0||n===void 0)return a(10);if(r&&e!==void 0&&e!==n)return a(10);return f(n)}ce();re();D();C();re();D();C();D();C();tt();var vn={encode(e,t){if(!Number.isInteger(t.num)||t.num<1)return 14;if(t.hsh.byteLength!==qe)return 10;let r=Kt.encode(e,t.realm);if(r!==0)return r;let n=e.writeVarInt(t.num);if(n!==0)return n;return e.writeBytes(t.hsh),0},decode(e){let[t,r]=Kt.decode(e);if(r!==0)return a(r);let[n,s]=e.readVarInt();if(s!==0)return a(s);if(!Number.isInteger(n)||n<1)return a(14);let[o,i]=e.readBytes(qe);if(i!==0)return a(i);return f({realm:t,num:n,hsh:o})}};function Mn(e,t){if(e.byteLength!==z)return a(10);let r=new O;r.writeBytes(e);let n=No(r,t);if(n!==0)return a(n);return f(r.result())}var xt={encode(e,t){if(t.nonce.byteLength!==z)return 10;if(t.hsh.byteLength!==qe)return 10;if(t.sig.byteLength!==Be)return 10;e.writeBytes(t.nonce);let r=No(e,t.realms);if(r!==0)return r;return e.writeBytes(t.hsh),e.writeBytes(t.sig),0},decode(e){let[t,r]=e.readBytes(z);if(r!==0)return a(r);let[n,s]=ac(e);if(s!==0)return a(s);let[o,i]=e.readBytes(qe);if(i!==0)return a(i);let[c,u]=e.readBytes(Be);if(u!==0)return a(u);return f({nonce:t,realms:n,hsh:o,sig:c})}};function No(e,t){let r=e.writeVarInt(t.length);if(r!==0)return r;for(let n of t){let s=vn.encode(e,n);if(s!==0)return s}return 0}function ac(e){let[t,r]=e.readVarInt();if(r!==0)return a(r);if(!Number.isInteger(t)||t<0||t>e.remaining())return a(14);let n=[];for(let s=0;s<t;s++){let[o,i]=vn.decode(e);if(i!==0)return a(i);n.push(o)}return f(n)}var _o={encode(e,t){let r=e.writeStruct(xt,t.head);if(r!==0)return r;return e.writeBytes(t.chunks),0},decode(e){let[t,r]=e.readStruct(xt);if(r!==0)return a(r);return f({head:t,chunks:e.readRest()})}};D();C();var Cn={encode(e,t){e.writeBytes(t.kdm);let r=e.writeVarBytes(t.headCph);if(r!==0)return r;return e.writeVarInt(t.lenBody)},decode(e){let[t,r]=e.readBytes(Oe);if(r!==0)return a(r);let[n,s]=e.readVarBytes();if(s!==0)return a(s);let[o,i]=e.readVarInt();if(i!==0)return a(i);return f({kdm:t,headCph:n,lenBody:o})}};tt();D();C();fe();D();C();Un();fe();Rn();async function Go(e,t){let[r,n]=await oe({parent:e,purpose:Y.Identity,kdm:q});if(n!==0)return a(n);let[s,o]=await oe({parent:e,purpose:Y.RealmKey,kdm:t});if(o!==0)return r.fill(0),a(o);let[i,c]=await oe({parent:e,purpose:Y.RealmID,kdm:t});if(c!==0)return r.fill(0),s.fill(0),a(c);try{let[u,d]=await Er(i,q);if(d!==0)return r.fill(0),s.fill(0),a(d);return Xe.init(r,s,u,q,t)}finally{i.fill(0)}}var Gt;((Qo)=>{Qo.defaultFileExtension="dpl";function t(c){let[u,d]=xt.decode(new L(c));if(d!==0)return a(d);return f(u.nonce)}Qo.exportNonce=t;async function r(c,u,d,l){return s(c,u,d,l)}Qo.sealExport=r;async function n(c,u,d){let l=await u.genRandomBytes(z),[p,y]=await c.exportKey(l);if(y!==0)return a(y);try{return await s(d,u,p,l)}finally{p.fill(0)}}Qo.exportFile=n;async function s(c,u,d,l){if(l.byteLength!==z)return a(10);let p=$o(d),[y,m]=await p(q);if(m!==0)return a(m);let h=new O,g=[];for(let v of c){if(v.msgs.length<1)return a(14);let[U,T]=await p(v.realm);if(T!==0)return a(T);let[R,V]=await lc(h,v,U);if(V!==0)return a(V);let H=await u.blake3(R);g.push({realm:v.realm,num:v.msgs.length,hsh:H})}let[S,b]=Mn(l,g);if(b!==0)return a(b);let x=await u.blake3(S),[E,P]=await y.sign(x);if(P!==0)return a(P);let w=new O,k=w.writeStruct(xt,{nonce:l,realms:g,hsh:x,sig:E});if(k!==0)return a(k);return h.prependBytes(w.result()),f(h.result())}Qo.encodeFile=s;async function o(c,u,d){let[l,p]=_o.decode(new L(c));if(p!==0)return a(p);let{head:y,chunks:m}=l,h=$o(d),[g,S]=await h(q);if(S!==0)return a(S);let b;try{b=await u.importVerifyKey(g.publicKey)}catch{return a(29)}if(!await u.checkSigEd25519(y.sig,y.hsh,b))return a(3);let[E,P]=Mn(y.nonce,y.realms);if(P!==0)return a(P);let w=await u.blake3(E);if(!G(w,y.hsh))return a(19);let k=new L(m),v=[];for(let U of y.realms){let[T,R]=await h(U.realm);if(R!==0)return a(R);let[V,H]=await fc(k,m,U,u,T);if(H!==0)return a(H);v.push({realm:U.realm,msgs:V})}if(!k.done())return a(14);return f(v)}Qo.decodeFile=o;async function i(c,u,d,l,p,y){let[m,h]=await o(c,u,d);if(h!==0)return a(h);let g=await y(m);return s(g,u,l,p)}Qo.migrateFile=i})(Gt||={});function $o(e){let t=[];return async(r)=>{for(let o of t)if(_e(o.realm,r))return f(o.bagMgr);let[n,s]=await Go(e,r);if(s!==0)return a(s);return t.push({realm:r,bagMgr:n}),f(n)}}var uc=40;function dc(e){let t=e.body;if(t===void 0||e.head.len<=0||e.head.hsh===void 0)return 0;return t.length+uc}async function lc(e,t,r){if(t.msgs.length<1)return a(14);let n=new O,s=[];for(let i of t.msgs){let c=new O,u=c.writeStruct(Ie,i.head);if(u!==0)return a(u);let d=c.result(),[l,p]=await r.bagKDM(d);if(p!==0)return a(p);let[y,m]=await r.encrypt(l,d);if(m!==0)return a(m);let h=n.writeStruct(Cn,{kdm:l,headCph:y,lenBody:dc(i)});if(h!==0)return a(h);s.push(l)}let o=n.result();e.writeBytes(o);for(let i=0;i<t.msgs.length;i++){let c=t.msgs[i],u=s[i];if(c===void 0||u===void 0)return a(12);let d=c.body;if(d===void 0||c.head.len<=0||c.head.hsh===void 0)continue;let[l,p]=await r.encrypt(u,d);if(p!==0)return a(p);e.writeBytes(l)}return f(o)}async function fc(e,t,r,n,s){let o=e.consumed(),i=[];for(let d=0;d<r.num;d++){let[l,p]=e.readStruct(Cn);if(p!==0)return a(p);i.push(l)}let c=await n.blake3(t.subarray(o,e.consumed()));if(!G(c,r.hsh))return a(19);let u=[];for(let d of i){let[l,p]=await s.decrypt(d.kdm,d.headCph);if(p!==0)return a(p);let[y,m]=Ie.decode(new L(l));if(m!==0)return a(m);if(d.lenBody<0)return a(14);if(d.lenBody===0){u.push({head:y});continue}if(y.hsh===void 0)return a(14);let[h,g]=e.readBytes(d.lenBody);if(g!==0)return a(g);let[S,b]=await s.decrypt(d.kdm,h);if(b!==0)return a(b);let x=await n.blake3(S);if(!G(x,y.hsh))return a(19);u.push({head:y,body:S})}return f(u)}re();D();C();async function zo({now:e,bod:t,crypto:r,typ:n=""}){let s=await r.genRandomBytes(8),o=new O,i=o.writeStruct(ae,{id:s,ts:e});if(i!==0)return a(i);let c=o.result();return Ar({now:e,eid:c,ctr:0,typ:n,bod:t,crypto:r})}async function Ar({now:e,eid:t,ctr:r,typ:n="",bod:s,crypto:o}){let i=new L(t),[c,u]=ae.decode(i);if(u!==0)return a(u);let d=e.getTime()-c.ts.getTime(),l,p=s?.length??0;if(s&&p>0)l=await o.blake3(s);return f({eid:t,off:d,ctr:r,typ:n,len:p,hsh:l})}ce();re();D();C();function pc(e,t){let r=e.length<t.length?e.length:t.length;for(let n=0;n<r;n++)if(e[n]!==t[n])return e[n]-t[n];return e.length-t.length}async function Qt(e,t){let r=Array.from(e);r.sort(pc);let n=0;for(let i of r)n+=i.length;let s=new Uint8Array(n),o=0;for(let i of r)s.set(i,o),o+=i.length;return t.blake3(s)}function yc(e){let t=new O,r=t.writeVarBytes(e.eid);if(r!==0)return a(r);let n=t.writeDate(e.updatedAt);if(n!==0)return a(n);let s=t.writeVarInt(e.ctr);if(s!==0)return a(s);return f(t.result())}async function kr(e,t){let r=[];for(let n of e){let[s,o]=yc(n);if(o!==0||!s)return a(o);r.push(s)}return f(await Qt(r,t))}re();D();C();$t();var Ay=Symbol("EntityID");function Jo(e){return"type"in e}var ky=Symbol("DerivationSeed"),Dy=Symbol("PublicKey"),By=Symbol("PrivateKey"),vy=Symbol("HostSpecificKeyPair"),My=Symbol("Hash");re();D();C();function mc(e){if(!e.bod||e.bod.length===0){let o={off:e.off,ctr:e.ctr,eid:e.eid};return f(o)}let t=new L(e.bod),[r,n]=t.readStruct(jt);if(n!==0)return a(n);let s={off:e.off,ctr:e.ctr,eid:e.eid,type:e.typ??"",body:r.body};if(r.pid!==void 0)s.pid=r.pid;if(r.tags!==void 0)s.tags=r.tags;return f(s)}class Dr{applier;emitter=new Ht;clearer;onDirtyEids;cacheDriven;peerIngest;constructor(e,t,r,n){this.applier=e;this.clearer=t,this.onDirtyEids=r,this.cacheDriven=n?.cacheDriven??!1,this.peerIngest=n?.peerIngest}apply=async(e)=>{let t=[],r=[];for(let c of e){let[u,d]=mc(c);if(r.push(d),d!==0)continue;t.push(u)}let{stats:n,types:s,eids:o}=await this.applier(t),i=[];for(let c=0;c<e.length;c++){let u=r[c],d=n[c];if(u!==0){i.push(u);continue}if(d!==0){i.push(d);continue}i.push(0)}if(!this.cacheDriven)for(let c of s)this.emitter.emit(c,null);if(o.length>0)this.onDirtyEids?.(o);return i};clear=async()=>{let e=await this.clearer();if(e!==0)return e;return this.emitter.emitAll(null),e};notify=(e)=>{for(let t of e)this.emitter.emit(t,null)};refresh=async(e)=>{if(this.peerIngest){await this.peerIngest(e);return}};on=(e,t)=>{this.emitter.addEventListener(e,t)};off=(e,t)=>{this.emitter.removeEventListener(e,t)}}function Z(e){return"type"in e}function hc(e,t){let r=t.excludeStart?e>t.start:e>=t.start,n=t.excludeEnd?e<t.end:e<=t.end;return r&&n}function zt(e){if(e instanceof Date)return f(!0);if(e.range.start>e.range.end)return a(10);return f(!0)}function Hn(e,t){if(t instanceof Date)return e.getTime()===t.getTime();return hc(e,t.range)}function gc(e,t){let r=t.excludeStart?e>t.start:e>=t.start,n=t.excludeEnd?e<t.end:e<=t.end;return r&&n}function Yt(e){if(typeof e==="string")return f(e.length>0);if("range"in e){if(e.range.start>e.range.end)return a(10);return f(!0)}return f(e.prefix.length>0)}function Tn(e,t){if(typeof t==="string")return e===t;if("range"in t)return gc(e,t.range);if(t.prefix.length===0)return!1;return e.startsWith(t.prefix)}function Sc(e){if(!Array.isArray(e)||e.length===0)return;let t=new Set,r=[];for(let n of e){if(typeof n!=="string"||n.length===0)continue;if(t.has(n))continue;t.add(n),r.push(n)}return r.length>0?r:void 0}function Br(e){return{eid:e.eid,ctr:e.ctr,updatedAt:e.updatedAt}}function Zo(e){let t=new L(e.eid),[r,n]=t.readStruct(ae);if(n!==0)return a(n);return f({eid:e.eid,ctr:e.ctr,updatedAt:new Date(r.ts.getTime()+e.off)})}function Pt(e,t){let r=new L(t.eid),[n,s]=r.readStruct(ae);if(s!==0)return a(s);let o=new Date(n.ts.getTime()+t.off);if(e!==void 0&&o<=e.updatedAt)return a(15);if(Jo(t)){let i=Sc(t.tags);return f({eid:t.eid,pid:t.pid,...i!==void 0?{tags:i}:{},type:t.type,createdAt:n.ts,updatedAt:o,ctr:t.ctr,body:t.body})}return f({eid:t.eid,updatedAt:o,ctr:t.ctr})}function Et(e,t){let r=new Set;if(e!==void 0&&Z(e))r.add(e.type);if(Z(t))r.add(t.type);return[...r]}C();class vr{inflight=null;again=!1;run(e){if(this.again=!0,this.inflight)return this.inflight;return this.inflight=this.drain(e),this.inflight}async flush(){if(!this.inflight)return;try{await this.inflight}catch{}}async drain(e){try{this.again=!1;let t=await e();while(this.again)this.again=!1,t=await e();return t}finally{this.inflight=null}}}var ei=100;class Kn{timer=null;delayMs;work;tail=new vr;constructor(e,t){this.delayMs=e<0?0:e,this.work=t}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 ti=!1;function ri(e){ti=e===!0}function W(e,t){if(!ti)return;let r=Math.round(performance.now());if(t!==void 0)console.warn(`[dip ${r}ms] ${e}`,t);else console.warn(`[dip ${r}ms] ${e}`)}re();D();function ni(e){let t=new L(e.eid),[r,n]=ae.decode(t);if(n!==0)return;return r.ts.getTime()+e.off}function bc(e,t){let r=ni(e),n=ni(t);if(r===void 0&&n===void 0)return 0;if(r===void 0)return 1;if(n===void 0)return-1;if(n!==r)return n-r;return t.ctr-e.ctr}function At(e,t){return e.slice().sort((r,n)=>bc(t(r),t(n)))}var Vn={phase:"idle"},Jt=50;function Ln(e,t,r){if(e<=0||t<=0)return!1;if(e===1||e===t)return!0;return e%r===0}re();D();C();var On="blob:";function si(e){return On+e}function oi(e){return e!==void 0&&e.startsWith(On)}function Ic(e){if(!oi(e))return;let t=e.slice(On.length);if(t.length===0)return;return t}function ii(e){return new L(e).readStruct(jt)}function wc(e,t){let r={};if(e!==void 0&&e.pid!==void 0)r.pid=e.pid;if(e!==void 0&&e.tags!==void 0&&e.tags.length>0)r.tags=e.tags;if(t.length>0)r.body=t;return r}function xc(e,t,r){let n={},s=r!==void 0&&Object.hasOwn(r,"pid")?r.pid:e.pid,o=r!==void 0&&Object.hasOwn(r,"tags")?r.tags:e.tags;if(s!==void 0)n.pid=s;if(o!==void 0&&o.length>0)n.tags=o;if(t.length>0)n.body=t;return n}function Pc(e){let t=new L(e.eid),[r,n]=t.readStruct(ae);if(n!==0)return a(n);return f({eid:e.eid,ctr:e.ctr,updatedAt:new Date(r.ts.getTime()+e.off)})}function ai(e,t,r){if(e.length===0)return a(10);let[n,s]=bt(wc(r,t));if(s!==0)return a(s);return f({typ:si(e),bod:n})}function ci(e,t,r){if(e===void 0||e.bod===void 0||e.bod.length===0)return a(13);let n=Ic(e.typ);if(n===void 0)return a(10);let[s,o]=Pc(e);if(o!==0)return a(o);let[i,c]=ii(e.bod);if(c!==0)return a(c);let u=r?.mime??n;if(u.length===0)return a(10);let[d,l]=bt(xc(i,t,r));if(l!==0)return a(l);return f({typ:si(u),bod:d,prior:s})}function ui(e){if(e===void 0||e.bod===void 0||e.bod.length===0)return a(13);if(!oi(e.typ))return a(13);let[t,r]=ii(e.bod);if(r!==0)return a(r);if(t.body===void 0)return f(new Uint8Array);return f(t.body.slice())}function di(e,t){if(typeof navigator.msSaveOrOpenBlob==="function"){navigator.msSaveOrOpenBlob(e,t);return}let r=URL.createObjectURL(e),n=document.createElement("a");n.href=r,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}function li(e,t,r){let n=[],s=[],o=0;for(let i of e){let c=t(i);if(s.length>0&&o+c>r)n.push(s),s=[],o=0;if(s.push(i),o+=c,o>=r)n.push(s),s=[],o=0}if(s.length>0)n.push(s);return n}async function qn(e,t,r){let n=e.length;if(n<1)return[];let s=Array(n),o=0,i=Math.min(Math.max(1,t),n),c=async()=>{while(!0){let d=o;if(o+=1,d>=n)return;s[d]=await r(e[d],d)}},u=[];for(let d=0;d<i;d++)u.push(c());return await Promise.all(u),s}re();tt();D();fe();re();D();C();async function Mr(e,t,r,n){let s=r.rlm;if(s.byteLength!==z)return a(10);let o=new L(e.headCph),[i,c]=o.readStruct(br);if(c!==0)return a(c);let{sig:u,kdm:d,headCph:l}=i;if(!await n.checkSigEd25519(u,ar(s,l),t))return a(3);let[y,m]=await r.decrypt(d,l);if(m!==0)return a(m);return f({kdm:d,headEnc:y})}D();C();var Mm=Symbol("EntRlm");function it(e){if(typeof e!=="string"||e==="")return;return e}function Cr(e){if(e.rlm!==void 0&&e.rlm!=="")return e;if(e.rlm===void 0)return e;let t={...e};return delete t.rlm,t}function Nn(e){return typeof e==="number"&&Number.isInteger(e)&&e>=0}function Ec(e){return e!==null&&typeof e==="object"}function Ur(e){if(!Ec(e)||typeof e.label!=="string")return;if(!Nn(e.index))return;let t={label:e.label,index:e.index};if(e.prior===void 0)return t;if(!Array.isArray(e.prior))return;let r=[];for(let n of e.prior){if(!Nn(n))return;r.push(n)}if(r.length>0)t.prior=r;return t}function fi(e,t,r){if(typeof e!=="string"||!Nn(r))return a(10);if(t!==void 0&&r<t.index)return a(10);let n=t?.prior!==void 0?t.prior.slice():void 0;if(t!==void 0&&r>t.index){let s=n!==void 0?n:[];return s.push(t.index),f({label:e,index:r,prior:s})}return f({label:e,index:r,...n!==void 0?{prior:n}:{}})}C();ce();D();var Zt="f",Rr="t",kt="e";function Ac(e){if(e===!0||e===Rr)return Rr;if(e===kt)return kt;return Zt}function pi(e){return e!==0&&e!==15&&e!==18&&e!==17}function _n(e,t,r){if(e.apld=t,t===kt&&r!==void 0)e.err=r;else delete e.err}async function Hr(e,t,r,n){let s=n?.body!==!1,o=Ac(t.apld),i=t.body,c=i?.length??0,u;if(s&&i&&c>0)u=await r.blake3(i);let d={eid:t.eid,off:t.off??0,ctr:t.ctr??0,typ:t.typ??"",len:c,hsh:u},l={hash:e,head:d,apld:o};if(s&&i!==void 0)l.body=i;if(o===kt&&t.err!==void 0)l.err=t.err;let p=it(t.rlm);if(p!==void 0)l.rlm=p;return l}var Fn=1048576,Wn=1048576,mi=64;function kc(e){return e.sig.length+e.kdm.length+e.headCph.length+e.bodyCph.length}function er(e,t,r,n){let s=`${t}\x00${It(n??q)}`,o=e.get(s);if(o){o.seqs.push(r);return}e.set(s,{host:t,realm:n,seqs:[r]})}async function hi(e,t){for(let r of t.values())await e.downloads.deq(r.host,r.seqs,r.realm)}async function Dc(e,t,r,n,s,o=q){if(n.length<1)return 0;let[i,c]=await e.push(n);if(c!==0)return c;if(!i)return 27;for(let d of i){if(d.status!==0){console.error("push err",d);continue}let l=s[d.idx];if(!l){console.error("no hash",d);continue}await t.uploads.deq(r,[l])}let u=await t.hosts.get(r);if(u){let d=Xt(u,o),l=d,p=[];for(let y of i)if(y.status===0)p.push(y.seq);p.sort((y,m)=>y-m);for(let y of p)if(y===d+1)d=y;if(d>l)await t.hosts.touch(r,d,o)}return 0}async function yi(e,t){if(t.length<1)return f([]);let r=new Map;for(let s of t){let o=s.realm??q,i=It(o),c=r.get(i);if(!c)c={realm:o,dls:new Map,seqs:[]},r.set(i,c);c.dls.set(s.seq,s),c.seqs.push(s.seq)}let n=[];for(let s of r.values()){let[o,i]=await e.pull(s.seqs,s.realm);if(i!==0)return a(i);if(!o)return a(27);for(let{seq:c,bodyCph:u}of o){let d=s.dls.get(c);if(!d)continue;n.push({dl:d,bodyCph:u})}}return f(n)}async function Bc(e,t,r,n){if(n.length<1)return f({parts:[],hashes:[]});let s=[],o=[],i=[],c=new Map;for(let{dl:d,bodyCph:l}of n){let{head:p,kdm:y,seq:m,host:h}=d,g=d.realm??q,[S,b]=await gi(d,r);if(b!==0){er(c,h,m,d.realm);continue}let{headEnc:x,headEncHash:E}=S,P=t.find((T)=>_e(g,T.realmKDM));if(P===void 0){er(c,h,m,d.realm);continue}let[w,k]=await en(x,l,{decrypt:(T)=>P.decrypt(y,T)},r,E);if(k!==0){er(c,h,m,d.realm);continue}let v={head:p,body:w.bod},U=w.headHash;i.push({key:U,data:Tr(v,g)}),s.push(v),o.push(U),er(c,h,m,d.realm)}let u=await e.messages.add(i);await hi(e,c);for(let d=0;d<u.length;d++){let l=u[d];if(l!==0&&l!==15)console.error("ERR storing",A[l],"for message",d)}return f({parts:s,hashes:o})}async function gi(e,t){let r=e.headEnc;if(!r){let s=new O,o=s.writeStruct(Ie,e.head);if(o!==0)return a(o);r=s.result()}if(e.headEncHash)return f({headEnc:r,headEncHash:e.headEncHash});let n=await t.blake3(r);return f({headEnc:r,headEncHash:n})}async function Si(e,t,r){let n=new Set;for(let i of t)n.add(K(i));if(n.size<1)return;let s=Array.from(await e.downloads.list());if(s.length<1)return;let o=new Map;for(let i of s){let c;if(i.headEncHash)c=K(i.headEncHash);else{let[u,d]=await gi(i,r);if(d!==0)continue;c=K(u.headEncHash)}if(!n.has(c))continue;er(o,i.host,i.seq,i.realm)}await hi(e,o)}async function jn({conn:e,store:t,host:r,crypto:n,onProgress:s,peekProgressEvery:o,peekConcurrency:i,realm:c}){let u=c??q,d=e.bagMgrFor(u);if(d===void 0)return 13;let[l,p]=await e.identity();if(p!==0)return p;let y;try{y=await n.importVerifyKey(l.publicKey)}catch{return 29}let m=[],[h,g]=await e.peek(Xt(r,u),u);if(g!==0)return g;let S=h.length,b=o??Jt,x=i??mi;if(s&&S>0)s({phase:"peek",host:r.label,done:0,total:S});let E=0,P=await qn(h,x,async(k)=>{let[v,U]=await Mr(k,y,d,n),T;if(U!==0)T={ok:!1,seq:k.seq,stat:U};else{let R=await n.blake3(v.headEnc);T={ok:!0,seq:k.seq,kdm:v.kdm,headEnc:v.headEnc,headEncHash:R}}if(E+=1,s&&Ln(E,S,b))s({phase:"peek",host:r.label,done:E,total:S});return T}),w=new Set;for(let k of P){if(!k.ok){console.error("peek: decrypting item head",k.stat);continue}let v=K(k.headEncHash);if(await t.messages.has(k.headEncHash)){console.info("peek: local msg; skip download, deq upload"),await t.uploads.deq(r.label,[k.headEncHash]),await t.downloads.deq(r.label,[k.seq],u);continue}if(w.has(v)){await t.downloads.deq(r.label,[k.seq],u);continue}let T=new L(k.headEnc),[R,V]=T.readStruct(Ie);if(V!==0){console.error("peek: reading item head",V);continue}w.add(v);let H={kdm:k.kdm,head:R,seq:k.seq,host:r.label,headEnc:k.headEnc,headEncHash:k.headEncHash},I=Pr(u);if(I!==void 0)H.realm=I;m.push(H)}if(await t.downloads.enq(m),h.length>0){let k=Math.max(...h.map((v)=>v.seq));await t.hosts.recordSeqs(r.label,{lastSeq:k},u)}if(s)s({phase:"peek",host:r.label,done:S,total:S});return 0}async function bi({conn:e,store:t,host:r,maxPushBytes:n,onProgress:s}){let o=n??Fn,i=await t.uploads.list(r.label),c=i.length,u=0;if(s&&c>0)s({phase:"push",host:r.label,done:0,total:c});let d=[],l=[],p=0,y=q,m=async()=>{if(d.length<1)return 0;let S=d.length,b=await Dc(e,t,r.label,d,l,y);if(d=[],l=[],p=0,b===0){if(u+=S,s)s({phase:"push",host:r.label,done:u,total:c})}return b},h=[],g=await t.realms.list();for(let S of i){let b=await t.messages.get(S);if(!b){u+=1;continue}h.push({hash:S,realm:xr(b.rlm,g),msg:{...b.head,bod:b.body}})}h.sort((S,b)=>{if(S.realm.label<b.realm.label)return-1;if(S.realm.label>b.realm.label)return 1;return S.realm.index-b.realm.index});for(let S of h){if(d.length>0&&!Vo(y,S.realm)){let P=await m();if(P!==0)return P}let[b,x]=await e.seal(S.msg,S.realm);if(x!==0)return x;let E=kc(b);if(d.length>0&&p+E>o){let P=await m();if(P!==0)return P}if(d.length<1)y=S.realm;if(d.push(b),l.push(S.hash),p+=E,p>=o){let P=await m();if(P!==0)return P}}return m()}async function Xn({conn:e,store:t,host:r,crypto:n,maxPullBytes:s,onProgress:o},i){let c=s??Wn,u=await t.downloads.list(),d=Array.from(u).filter((g)=>g.host===r.label);if(d.length<1)return 15;let l=At(d,(g)=>g.head),p=li(l,(g)=>g.head.len,c),y=l.length,m=0;if(o)o({phase:"pull",host:r.label,done:0,total:y});let h=yi(e,p[0]);for(let g=0;g<p.length;g++){let[S,b]=await h;if(b!==0)return b;if(m+=p[g].length,o)o({phase:"pull",host:r.label,done:m,total:y});let x=p[g+1];if(x)h=yi(e,x);if(o)o({phase:"open",host:r.label,done:m,total:y});let E=At(S,(w)=>w.dl.head),[,P]=await Bc(t,e.bagMgrs(),n,E);if(P!==0)return P;if(i){if(o)o({phase:"exec",host:r.label,done:m,total:y});await i()}}return 0}function Tr({head:e,body:t},r){let n={eid:e.eid,body:t,apld:Zt};if(e.off!==0)n.off=e.off;if(e.ctr!==0)n.ctr=e.ctr;if(e.typ)n.typ=e.typ;let s=it(r?.label);if(s!==void 0)n.rlm=s;return n}async function Ii(e,{conn:t,store:r,host:n,crypto:s,onProgress:o},i){let c=n.label,[u,d]=await t.identity();if(d!==0)return;let l;try{l=await s.importVerifyKey(u.publicKey)}catch(w){console.error("Failed importing host verify key",w);return}let p=new L(e),[y,m]=p.readStructs(Sr);if(m!==0){console.error("Failed decoding notif",A[m]);return}let h=!1,g=await r.hosts.get(c),S=new Map,b=[],x=!1;for(let w of y){let k=t.bagMgrs().find((j)=>G(j.rlm,w.rlm));if(k===void 0){console.error("notif: realm",A[13]);continue}let v=k.realmKDM,[U,T]=await Mr({seq:w.seq,headCph:w.headCph},l,k,s);if(T!==0){console.error("Failed decrypting notif",A[T]);continue}let R=await s.blake3(U.headEnc);if(await r.messages.has(R))continue;let V=new L(U.headEnc),[H,I]=V.readStruct(Ie);if(I!==0){console.error("Failed to parse head",A[I]);continue}if(!w.bodyCph&&H.len>0){x=!0;let j={seq:w.seq,host:c,kdm:U.kdm,head:H,headEnc:U.headEnc,headEncHash:R},X=Pr(v);if(X!==void 0)j.realm=X;await r.downloads.enq([j])}else b.push({...U,head:H,bodyCph:w.bodyCph,headEncHash:R,realm:v,bagMgr:k});if(!g){console.log("out of seq",w.seq,void 0),h=!0;continue}let F=It(v),N=S.get(F);if(!N)N={realm:v,seq:Xt(g,v)},S.set(F,N);if(w.seq!==N.seq+1)console.log("out of seq",w.seq,N.seq),h=!0;else N.seq=w.seq}if(g){for(let w of S.values())if(w.seq>Xt(g,w.realm))await r.hosts.touch(n.label,w.seq,w.realm)}let E=[];for(let w of b){let[k,v]=await en(w.headEnc,w.bodyCph,{decrypt:(U)=>w.bagMgr.decrypt(w.kdm,U)},s);if(v!==0){console.error("Failed to open body",A[v]);continue}E.push({key:w.headEncHash,data:Tr({head:w.head,body:k.bod},w.realm)})}let P=await r.messages.add(E);for(let w=0;w<P.length;w++){let k=P[w];if(k!==0&&k!==15)console.error("ERR storing",A[k],"for message",w)}if(o&&E.length>0)o({phase:"open",host:n.label,done:E.length,total:E.length});if(h||x||E.length>0)i()}async function Gn(e,t={}){let r=t.pull!==!1,n=t.push===!0,{conn:s,store:o,host:i,crypto:c,onProgress:u,peekProgressEvery:d,peekConcurrency:l}=e,[p,y]=await s.identity();if(y!==0)return a(y);let m;try{m=await c.importVerifyKey(p.publicKey)}catch{return a(29)}let h=new Map,g=0,S=d??Jt,b=l??mi,x=wt(await o.realms.list());for(let R of x){let V=s.bagMgrFor(R);if(V===void 0)return a(13);let[H,I]=await s.peek(0,R);if(I!==0)return a(I);g+=H.length;let F=H.length;if(u&&F>0)u({phase:"peek",host:i.label,done:0,total:F});let N=0,j=await qn(H,b,async(M)=>{let[te,ne]=await Mr(M,m,V,c),ie;if(ne!==0)ie={ok:!1,seq:M.seq,stat:ne};else{let J=await c.blake3(te.headEnc);ie={ok:!0,seq:M.seq,kdm:te.kdm,headEnc:te.headEnc,headEncHash:J}}if(N+=1,u&&Ln(N,F,S))u({phase:"peek",host:i.label,done:N,total:F});return ie});for(let M of j){if(!M.ok)continue;let te=K(M.headEncHash),ne=h.get(te);if(ne)ne.count+=1;else h.set(te,{hash:M.headEncHash,count:1,sample:M,realm:R})}let X=H.length>0?Math.max(...H.map((M)=>M.seq)):0;if(await o.hosts.recordSeqs(i.label,{setLastSeq:X},R),u)u({phase:"peek",host:i.label,done:F,total:F})}let E=0,P=[];for(let R of h.values()){if(R.count>1)E+=R.count-1;P.push(R.hash)}let w=h.size,k=await Qt(P,c),v=[],U=0;for(let R of h.values()){if(await o.messages.has(R.hash)){await o.uploads.deq(i.label,[R.hash]);continue}if(U+=1,!r)continue;let H=R.sample,I=new L(H.headEnc),[F,N]=I.readStruct(Ie);if(N!==0){console.error("reconcile: reading msg header",N);continue}let j={kdm:H.kdm,head:F,seq:H.seq,host:i.label,headEnc:H.headEnc,headEncHash:H.headEncHash},X=Pr(R.realm);if(X!==void 0)j.realm=X;v.push(j)}if(v.length>0)await o.downloads.enq(v);let T=0;if(n){let R=await o.messages.listKeys(),V=new Set(h.keys()),H=[];for(let I of R)if(!V.has(K(I)))T+=1,H.push(I);if(H.length>0)await o.uploads.enq(i.label,H)}else{let R=await o.messages.listKeys(),V=new Set(h.keys());for(let H of R)if(!V.has(K(H)))T+=1}return f({msgcheck:k,numBags:g,uniqueMsgs:w,numDupes:E,missingLocal:U,missingHost:T})}function vc(e){return e.map(({head:t,body:r})=>({...t,bod:r}))}function Mc(e,t){let r=[];for(let n of e){let s=xr(n.rlm,t),o=r.find((i)=>_e(i.realm,s));if(o===void 0)o={realm:s,msgs:[]},r.push(o);o.msgs.push({head:n.head,body:n.body})}return r}class Qn{clock;state;store;transport;crypto;forceSkewHandlingByDefault;onScheduleSync;connections=new Map;#e;applyChain=Promise.resolve();syncRuns=new vr;clientState;xferState;maxPushBytes;maxPullBytes;peekProgressEvery=Jt;lastProgress=Vn;scheduledSync;constructor(e,t,r,n,s,o=!0,i=Fn,c=Wn,u){this.clock=e;this.state=t;this.store=r;this.transport=n;this.crypto=s;this.forceSkewHandlingByDefault=o;this.onScheduleSync=u;this.maxPushBytes=i,this.maxPullBytes=c,this.clientState=new Ze(()=>this.getClientState()),this.xferState=new Ze(()=>this.getXferState()),this.scheduledSync=new Kn(ei,async()=>{try{console.info("Running scheduled sync"),await this.sync()}catch(d){console.error("Debounced sync failed:",d)}})}emitProgress=(e)=>{this.lastProgress=e,this.xferState.emit()};selected(){return this.#e}async setSeed(e,t){let[r,n]=je(t?.label);if(n!==0||r===void 0)return 10;let[,s]=await this.store.account.save(e,t);if(s!==0)return s;let o=await this.#i(r,e);if(o!==0)return o;return this.clientState.emit(),0}async adopt(e,t=""){let r=await this.#i(t,e);if(r!==0)return r;return this.clientState.emit(),0}#t(){return this.#e?.enclave}async#n(){return Array.from(await this.store.hosts.list())}async#s(){if(this.#e===void 0)return;this.#e.hosts=await this.#n()}async#r(){if(this.#e===void 0)return;this.#e.realms=await this.store.realms.list()}async#i(e,t){let r=await this.store.bind(e);if(r!==0)return r;return this.#e={label:e,enclave:t,hosts:await this.#n(),realms:await this.store.realms.list()},0}async getClientState(){let{store:e,connections:t}=this,r=this.#t(),n=await e.hosts.list(),s=!1;for(let o of t.values())if(o.isConnected()){s=!0;break}return{hasSeed:r!==void 0,hasHost:Array.from(n).length>0,connected:s}}async getXferState(){let{uploads:e,downloads:t}=this.store,r=await e.count();return{numDownloads:await t.count(),numUploads:r,progress:this.lastProgress}}apply=(e,t)=>{W("apply kick",{n:e.length});let r=this.state.apply(vc(e));return this.enqueueApplyJob(()=>this.doApply(e,t,r))};async doApply(e,t={enqueueUpload:!0,triggerUpload:!0},r){let n=[],s=[];for(let i of e){let c=new O;c.writeStruct(Ie,i.head);let u=c.result(),d=await this.crypto.blake3(u),l=Tr(i,t.realm);n.push(d),s.push({key:d,data:l})}W("doApply archive start"),await this.store.messages.add(s),W("doApply archive done"),await Si(this.store,n,this.crypto),W("doApply await persist");let o=await r;if(W("doApply persist done"),await this.markApplyStats(n,o),t.enqueueUpload){let i=[];for(let c=0;c<n.length;c++){let u=o[c];if(u===0||u===15)i.push(n[c])}if(i.length>0){let c=await this.store.hosts.list();for(let u of c)await this.store.uploads.enq(u.label,i);this.xferState.emit()}}if(t.triggerUpload)this.scheduleSync();return o}enqueueApplyJob(e){let t=this.applyChain.then(e,e);return this.applyChain=t.then(()=>{return},()=>{return}),t}drainApplyQueue(){return this.enqueueApplyJob(()=>this.doDrainApplyQueue())}async doDrainApplyQueue(){let e=await this.store.messages.list({apld:Zt});if(e.length<1)return[];let t=At(e,(r)=>r.head);return this.applyStored(t)}applyHashes=(e)=>this.enqueueApplyJob(()=>this.doApplyHashes(e));async doApplyHashes(e){let t=[];for(let s of e){let o=await this.store.messages.get(s);if(o)t.push(o)}let r=await this.applyStored(t),n=new Map;for(let s=0;s<t.length;s++)n.set(K(t[s].hash),r[s]??12);return e.map((s)=>n.get(K(s))??13)}async applyStored(e){if(e.length<1)return[];let t=e.map((n)=>({...n.head,bod:n.body})),r=await this.state.apply(t);return await this.markApplyStats(e.map((n)=>n.hash),r),r}async markApplyStats(e,t){let r=[],n=[];for(let s=0;s<e.length;s++){let o=t[s];if(o===0||o===15)r.push(e[s]);else if(o!==void 0&&pi(o))n.push({key:e[s],err:o})}if(r.length>0)await this.store.messages.markApplied(r);if(n.length>0)await this.store.messages.markFailed(n)}async insertRaw(e,t=""){W("insertRaw");let{clock:r,crypto:n}=this,s=r.now(),[o,i]=await zo({now:s,bod:e,typ:t,crypto:n});if(i!==0)return a(i);let u=(await this.apply([{head:o,body:e}]))[0];if(u!==0&&u!==15)return a(u??12);return f(o)}async makeUpdate(e,t,r=""){let{clock:n,crypto:s}=this,o=n.now();if(e.updatedAt.getTime()>o.getTime())return a(4);let i=e.ctr+1,[c,u]=await Ar({now:o,eid:e.eid,ctr:i,typ:r,bod:t,crypto:s});if(u!==0)return a(u);return f({head:c,body:t})}async updateWithSkew(e,t,r,n=""){if(r===!1)return a(4);let{clock:s,crypto:o}=this,i=s.now(),c=new L(e.eid),[u,d]=c.readStruct(ae);if(d!==0)return a(d);let l=e.updatedAt.getTime()-u.ts.getTime(),p={eid:e.eid,off:l+1,ctr:e.ctr+1,typ:"",len:0},m=(await this.apply([{head:p,body:void 0}]))[0];if(m!==0&&m!==15)return a(m??12);if(t===void 0)return f(p);let[h,g]=ft({id:u.id,ts:i});if(g!==0)return a(g);let[S,b]=await Ar({now:i,eid:h,ctr:0,typ:n,bod:t,crypto:o});if(b!==0)return a(b);let E=(await this.apply([{head:S,body:t}]))[0];if(E!==0&&E!==15)return a(E??12);return f(S)}async updateRaw(e,t,r=this.forceSkewHandlingByDefault,n=""){if(W("updateRaw"),e.updatedAt.getTime()>this.clock.now().getTime())return this.updateWithSkew(e,t,r,n);let[s,o]=await this.makeUpdate(e,t,n);if(o!==0)return a(o);let c=(await this.apply([s]))[0];if(c!==0&&c!==15)return a(c??12);return f(s.head)}async insert(e){let[t,r]=bt(e);if(r!==0)return a(r);return this.insertRaw(t,e.type)}async update(e){let[t,r]=bt(e);if(r!==0)return a(r);return this.updateRaw(e.prior,t,e.force??this.forceSkewHandlingByDefault,e.type)}async delete(e){let t=e.force??!0;if("prior"in e)return this.updateRaw(e.prior,void 0,t);let[r,n]=await this.revFromArchive(e.eid);if(n!==0)return a(n);return this.updateRaw(r,void 0,t)}async insertBlob(e,t,r){let[n,s]=ai(e,t,r);if(s!==0)return a(s);return this.insertRaw(n.bod,n.typ)}async updateBlob(e,t,r){let[n,s]=ci(await this.lastMsg(e),t,r);if(s!==0)return a(s);return this.updateRaw(n.prior,n.bod,void 0,n.typ)}deleteBlob(e){return this.delete({eid:e})}async readBlob(e){return ui(await this.lastMsg(e))}async lastMsg(e){let t=await this.store.messages.last(e);if(t===void 0)return;let r={...t.head};if(t.body!==void 0)r.bod=t.body;return r}async revFromArchive(e){let t=await this.store.messages.last(e);if(t)return Zo(t.head);let r=new L(e),[n,s]=r.readStruct(ae);if(s!==0)return a(s);return f({eid:e,ctr:-1,updatedAt:n.ts})}async genEID(e){let{clock:t,crypto:r}=this,n=t.now();if(e!==void 0)return ft({id:e,ts:n});let s=await r.genRandomBytes(8);return ft({id:s,ts:n})}sync(){return this.syncRuns.run(()=>this.doSync())}async doSync(){let{connections:e,crypto:t,store:r}=this;if(!this.#t())return 22;await this.drainApplyQueue(),await this.#r();let s=wt(this.#e?.realms??[]);for(let[o,i]of e){let c=await r.hosts.get(o);if(!c)continue;let u=await this.#o(i,c);if(u!==0)return this.emitProgress({phase:"idle"}),u;let d={conn:i,store:r,host:c,crypto:t,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};for(let y of s){let m=await jn({...d,realm:y});if(m!==0)return console.error(`Failed to peek: ${m}`),this.emitProgress({phase:"idle"}),m;this.xferState.emit()}let l=await bi(d);if(l!==0)return console.error(`Failed to push: ${l}`),this.emitProgress({phase:"idle"}),l;this.xferState.emit();let p=await Xn(d,async()=>{await this.drainApplyQueue()});if(p!==0&&p!==15)return console.error(`Failed to pull: ${p}`),this.emitProgress({phase:"idle"}),p;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async rebuild(e){if(this.scheduledSync.cancel(),await this.syncRuns.flush(),e?.checkHost??!0){let r=await this.repull();if(r!==0)return r}return this.enqueueApplyJob(()=>this.replay())}async msgcheck(){let e=await this.store.messages.listKeys();return Qt(e,this.crypto)}listMsgs(e){return this.store.messages.list(e)}countMsgs(e){return this.store.messages.count(e)}async reconcile(e,t){this.scheduledSync.cancel(),await this.syncRuns.flush();let{connections:r,crypto:n,store:s}=this;if(!this.#t())return a(22);let i=await s.hosts.get(e);if(!i)return a(13);let c=r.get(e);if(!c||!c.isConnected()){if(await this.connectToHost(i,!1,!1),i=await s.hosts.get(e),!i)return a(13);c=r.get(e)}if(!c)return a(12);let u=await this.#o(c,i);if(u!==0)return a(u);let d={conn:c,store:s,crypto:n,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery},[l,p]=await Gn({...d,host:i},t);if(this.xferState.emit(),p!==0)return this.emitProgress({phase:"idle"}),a(p);if(!l)return this.emitProgress({phase:"idle"}),a(12);if(t?.sync===!1)return this.emitProgress({phase:"idle"}),f(l);let y=await this.sync();if(y!==0)return a(y);let m=await s.hosts.get(e);if(!m)return a(13);let[h,g]=await Gn({...d,host:m},{pull:!1,push:!1});if(this.xferState.emit(),this.emitProgress({phase:"idle"}),g!==0)return a(g);if(!h)return a(12);return f(h)}async repull(){let{connections:e,crypto:t,store:r}=this;if(!this.#t())return 22;let s=Array.from(await r.hosts.list());if(s.length<1)return 0;await this.#r();let o=wt(this.#e?.realms??[]);for(let i of s){let c=e.get(i.label);if(!c||!c.isConnected())await this.connectToHost(i,!1,!1)}for(let[i,c]of e){let u=await r.hosts.get(i);if(!u)continue;let d=await this.#o(c,u);if(d!==0)return this.emitProgress({phase:"idle"}),d;let l={conn:c,store:r,host:{...u,lastSeq:0,seqs:void 0},crypto:t,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};for(let y of o){let m=await jn({...l,realm:y});if(m!==0)return console.error(`rebuild: failed to peek: ${m}`),this.emitProgress({phase:"idle"}),m;this.xferState.emit()}let p=await Xn(l);if(p!==0&&p!==15)return console.error(`rebuild: failed to pull: ${p}`),this.emitProgress({phase:"idle"}),p;this.xferState.emit()}return this.emitProgress({phase:"idle"}),0}async replay(){let e=await this.state.clear();if(e!==0)return e;let t=await this.store.messages.list(),r=At(t,(o)=>o.head),n=r.length;if(n<1)return this.emitProgress({phase:"idle"}),0;let s=0;while(s<r.length){let o=0,i=0,c=s;for(let d=s;d<r.length&&i<100&&o<102400;d++)o+=r[d].head.len,i++,c=d+1;let u=r.slice(s,c);await this.applyStored(u),this.emitProgress({phase:"exec",done:c,total:n}),s=c}return this.emitProgress({phase:"idle"}),0}async wipe(e){let t=e?.msgs!==!1,r=e?.ents!==!1,n=e?.meta!==!1,s=e?.seed===!0;this.scheduledSync.cancel(),await this.disconnect(),await this.syncRuns.flush();let{store:o}=this;if(n)await o.hosts.wipe(),await o.uploads.wipe(),await o.downloads.wipe();if(t)await o.messages.wipe();if(r)await this.state.clear();if(s)await o.account.wipe(),await o.realms.wipe(),this.#e=void 0;else if(n)await this.#s(),await this.#r();this.lastProgress=Vn,this.clientState.emit(),this.xferState.emit()}import=async(e,t)=>{let{crypto:r}=this,n=t?.onProgress,s=this.#t();if(!s)return 22;console.time("import: decoding file...");let o=await e.bytes(),[i,c]=Gt.exportNonce(o);if(c!==0)return console.timeEnd("import: decoding file..."),c;let[u,d]=await s.exportKey(i);if(d!==0)return console.timeEnd("import: decoding file..."),d;let l;try{l=await Gt.decodeFile(o,r,u)}finally{u.fill(0),console.timeEnd("import: decoding file...")}let[p,y]=l;if(y!==0)return y;let m=0,h=new Map;for(let S of p){if(m+=S.msgs.length,S.realm.label==="")continue;let b=h.get(S.realm.label);if(b===void 0||S.realm.index>b)h.set(S.realm.label,S.realm.index)}for(let[S,b]of h){let x=await this.store.realms.put(S,b);if(x===10)continue;if(x!==0)return x}if(h.size>0)await this.#r();let g=0;for(let S of p){let b=0;while(b<S.msgs.length){let x=0,E=0,P=b;for(let v=b;v<S.msgs.length&&E<100&&x<102400;v++)x+=S.msgs[v].head.len,E++,P=v+1;let w=S.msgs.slice(b,P);console.time(`import: applying [${g}, ${g+w.length}]`);let k=await this.apply(w,{enqueueUpload:!0,triggerUpload:!1,realm:S.realm});console.timeEnd(`import: applying [${g}, ${g+w.length}]`);for(let v=0;v<w.length;v++){let U=k[v];if(U!==0&&U!==15)console.warn(`failed to import msg ${g+v}: ${A[U]}`)}if(g+=w.length,n)queueMicrotask(()=>n(g,m,0));this.emitProgress({phase:"import",done:g,total:m}),b=P}}return this.scheduleSync(),this.emitProgress({phase:"idle"}),0};scheduleSync=()=>{if(this.onScheduleSync){this.onScheduleSync();return}this.scheduledSync.schedule()};async exportBytes(){let{crypto:e,store:t}=this,r=this.#t();if(!r)return a(22);let n=await t.realms.list(),s=await t.messages.list();return Gt.exportFile(r,e,Mc(s,n))}async export(e){let[t,r]=await this.exportBytes();if(r!==0)return r;if(!t)return 12;let n=new Blob([t.slice()]);return di(n,e),0}async link(e,t=!0){if(await this.store.hosts.add(e),await this.#s(),await this.#r(),this.clientState.emit(),t){let r=await this.store.hosts.get(e.label);if(r)await this.connectToHost(r)}}async unlink(e){await this.store.hosts.del(e),await this.#s(),await this.#r(),this.clientState.emit()}async hosts(){return Array.from(await this.store.hosts.list())}connectToHost=async(e,t=!0,r=!0)=>{let{clock:n,connections:s,crypto:o,store:i,transport:c}=this,u=s.get(e.label);if(u){if(u.isConnected())return;try{u.closeListener()}catch{}s.delete(e.label)}if(!this.#t())return;console.info(`Connecting to ${e.handle} (${e.label})`);let l=new Ir([],o,n,c(e),async(y)=>{let m=await i.hosts.set(e.label,y);return await this.#s(),await this.#r(),m});if(await this.#o(l,e)!==0)return;if(await l.register(),t)await l.listen(async(y)=>{if(await this.#o(l,e)!==0)return;let h={conn:l,store:i,host:e,crypto:o,maxPushBytes:this.maxPushBytes,maxPullBytes:this.maxPullBytes,onProgress:this.emitProgress,peekProgressEvery:this.peekProgressEvery};return Ii(y,h,this.scheduleSync)},()=>this.clientState.emit(),()=>this.clientState.emit());if(s.set(e.label,l),this.clientState.emit(),r)this.scheduleSync()};async#o(e,t){let r=this.#t();if(!r)return 22;let n={label:t.label,index:t.idx??0},s=wt(await this.store.realms.list());for(let o of s){if(e.bagMgrFor(o)!==void 0)continue;let[i,c]=await r.bagman(n,o);if(c!==0)return c;e.add(i)}return 0}async connect(e=!0,t=!0){let{connectToHost:r,scheduleSync:n,store:s}=this;if(!this.#t())return;await this.drainApplyQueue();let i=await s.hosts.list();for(let c of i)await r(c,e,!1);if(t)n()}disconnect=async()=>{for(let e of this.connections.values())try{e.closeListener()}catch{}this.connections.clear(),this.clientState.emit()}}St();var Dt=Ao;ce();D();function wi(e,t){if(e===null||t===null||typeof e!=="object"||typeof t!=="object")return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}C();ce();D();tr();C();tr();fe();D();ce();$t();C();os();Ct();var Qc=8;class $r{#e;#t;#n;#s;#r;#i;#o;constructor(e){this.#r=e.persistKeyring,this.#n={rpId:e.rpId,rpName:e.rpName},this.#s=e.userName??e.rpId??e.rpName??rr,this.#i=e.unlockAccount}static open(e){let t=new $r(e);if(e.keyring===void 0)return f(t);let[r,n]=nr(e.keyring);if(n!==0)return a(n);return t.#t=r,f(t)}get keyring(){if(this.#t===void 0)return;let[e,t]=nr(this.#t);if(t!==0)return;return e}list(){if(this.#t===void 0)return[];return this.#t.entries.map(Jc)}async save(e,t){let r=this.#e!==void 0||this.#t!==void 0&&this.#t.entries.length>0,[n,s]=qo(this.#o,t?.label,r);if(s!==0||n===void 0)return a(10);if(t?.persist===!0)return a(10);return this.#o=n,this.#e=e,f(this.#e)}async bindAndSave(e,t){let r=this.#t,n=t?.credId,s=n instanceof Uint8Array?n.byteLength>0:n!==void 0&&n.length>0;if(!s&&r!==void 0&&r.entries.length>=Qc)return a(26);let o=Yi(t?.nick),i=t?.excludeCredentials??(s?void 0:Zc(r)),c=t?.salt??r?.salt,u=r===void 0?void 0:r.entries.map((b)=>({credId:b.credId,tag:b.tag})),[d,l]=await e.bind({...this.#n,salt:c,credId:n,createCredIfNeeded:t?.createCredIfNeeded??!s,excludeCredentials:i,userName:this.#s,displayName:o??this.#n.rpName??this.#s,authenticatorAttachment:t?.authenticatorAttachment,hints:t?.hints},u);if(l!==0)return a(l);let p=Date.now(),y={type:"prf",sealedMaster:d.sealedMaster,credId:d.credId,tag:d.tag,userId:d.userId,nick:o,enrolledAt:p,lastUsedAt:p,attachment:d.attachment,transports:d.transports,aaguid:d.aaguid,enrolledOs:$c()},m=r===void 0?{salt:d.salt.slice(),entries:[]}:r,[h,g]=eu(m,y);if(g!==0)return a(g);let S=await this.#r(h);if(S!==0)return a(S);return this.#t=h,this.#e=e,f(this.#e)}async load(){return this.#e}async unlock(){let e=this.#i;if(e!==void 0){let[i,c]=await e();if(c!==0)return a(c);if(i===void 0)return a(13);if(i.keyring===void 0)this.#t=void 0;else{let[u,d]=nr(i.keyring);if(d!==0)return a(d);this.#t=u}return this.#e=i.enclave,f(i.enclave)}let t=this.#t;if(t===void 0||t.entries.length===0)return a(22);let[r,n]=await ye.unsealWithPasskey(t.entries.map((i)=>({sealedMaster:i.sealedMaster,credId:i.credId})),{...this.#n,salt:t.salt});if(n!==0)return a(n);this.#e=r.enclave;let[s,o]=as(t,r.credId);if(o!==0)return a(o);if(s!==void 0){let i=await this.#r(s);if(i!==0)return a(i);this.#t=s}return f(r.enclave)}async rename(e,t){let r=this.#t;if(r===void 0)return a(22);let n=r.entries.findIndex((l)=>G(l.credId,e));if(n<0)return a(13);let[s,o]=sr(r.entries);if(o!==0)return a(o);let i=s[n];if(i===void 0)return a(13);let c=Yi(t);s[n]={...i,nick:c};let u={salt:r.salt.slice(),entries:s},d=await this.#r(u);if(d!==0)return a(d);return this.#t=u,f(void 0)}async remove(e){let t=this.#t;if(t===void 0)return a(22);let r=t.entries.filter((c)=>!G(c.credId,e));if(r.length===t.entries.length)return a(13);if(r.length===0){let c=await this.#r(void 0);if(c!==0)return a(c);return this.#t=void 0,f(void 0)}let[n,s]=sr(r);if(s!==0)return a(s);let o={salt:t.salt.slice(),entries:n},i=await this.#r(o);if(i!==0)return a(i);return this.#t=o,f(void 0)}async wipe(){this.#e=void 0,this.#t=void 0,this.#o=void 0,await this.#r(void 0)}}function Yi(e){if(e===void 0)return;let t=e.trim();return t===""?void 0:t}function $c(){if(typeof navigator>"u")return;return Ri(navigator.userAgent)}function zc(e){let[t,r]=ot(e.sealedMaster.slice());if(r!==0)return a(r);let[n,s]=Fe(e.tag.slice(),Y.BindTag);if(s!==0)return a(s);return f({type:"prf",sealedMaster:t,credId:e.credId.slice(),tag:n,userId:e.userId===void 0?void 0:e.userId.slice(),nick:e.nick,enrolledAt:e.enrolledAt,lastUsedAt:e.lastUsedAt,attachment:e.attachment,transports:e.transports===void 0?void 0:[...e.transports],aaguid:e.aaguid===void 0?void 0:e.aaguid.slice(),enrolledOs:e.enrolledOs})}function sr(e){let t=[];for(let r of e){let[n,s]=zc(r);if(s!==0)return a(s);t.push(n)}return f(t)}function nr(e){let[t,r]=sr(e.entries);if(r!==0)return a(r);return f({salt:e.salt.slice(),entries:t})}function Ji(e){return e!==null&&typeof e==="object"}function Yc(e){if(!Ji(e)||e.type!=="prf")return;if(!(e.sealedMaster instanceof Uint8Array)||!(e.credId instanceof Uint8Array)||!(e.tag instanceof Uint8Array)||typeof e.enrolledAt!=="number"||!Number.isFinite(e.enrolledAt))return;let[t,r]=ot(e.sealedMaster);if(r!==0)return;let[n,s]=Fe(e.tag.slice(),Y.BindTag);if(s!==0)return;let o=e.attachment==="platform"||e.attachment==="cross-platform"?e.attachment:void 0,i=e.enrolledOs,c=i==="ios"||i==="macos"||i==="android"||i==="windows"||i==="linux"||i==="other"?i:void 0,u=Array.isArray(e.transports)?e.transports.filter((d)=>typeof d==="string"):void 0;return{type:"prf",sealedMaster:t,credId:e.credId.slice(),tag:n,userId:e.userId instanceof Uint8Array?e.userId.slice():void 0,nick:typeof e.nick==="string"?e.nick:void 0,enrolledAt:e.enrolledAt,lastUsedAt:typeof e.lastUsedAt==="number"&&Number.isFinite(e.lastUsedAt)?e.lastUsedAt:void 0,attachment:o,transports:u===void 0||u.length===0?void 0:u,aaguid:e.aaguid instanceof Uint8Array?e.aaguid.slice():void 0,enrolledOs:c}}function Zi(e){if(!Ji(e))return;if(!(e.salt instanceof Uint8Array)||!Array.isArray(e.entries))return;let t=[];for(let r of e.entries){let n=Yc(r);if(n!==void 0)t.push(n)}if(t.length===0)return;return{salt:e.salt.slice(),entries:t}}function Jc(e){return{type:"prf",credId:e.credId.slice(),userId:e.userId===void 0?void 0:e.userId.slice(),nick:e.nick,enrolledAt:e.enrolledAt,lastUsedAt:e.lastUsedAt,attachment:e.attachment,transports:e.transports===void 0?void 0:[...e.transports],aaguid:e.aaguid===void 0?void 0:e.aaguid.slice(),enrolledOs:e.enrolledOs}}function Zc(e){if(e===void 0)return[];return e.entries.filter((t)=>t.credId.byteLength>0).map((t)=>t.credId.slice())}function eu(e,t){let[r,n]=sr(e.entries);if(n!==0)return a(n);let s=r.findIndex((o)=>G(o.credId,t.credId));if(s>=0){let o=r[s];r[s]={...t,enrolledAt:o?.enrolledAt??t.enrolledAt,nick:t.nick??o?.nick}}else r.push(t);return f({salt:e.salt.slice(),entries:r})}function as(e,t){if(t.byteLength===0)return f(void 0);let r=e.entries.findIndex((i)=>G(i.credId,t));if(r<0)return f(void 0);let[n,s]=sr(e.entries);if(s!==0)return a(s);let o=n[r];if(o===void 0)return a(13);return n[r]={...o,lastUsedAt:Date.now()},f({salt:e.salt.slice(),entries:n})}var gS=zr("fbfc3007154e4ecc8c0b6e020557d7bd"),SS=zr("ea9b8d664d011d213ce4b6b48cb575d4"),bS=zr("08987058cadc4b81b6e130de50dcbe96"),IS=zr("2fc0579f811347eab116bb5a8db9202a");function zr(e){let t=new Uint8Array(16);for(let r=0;r<16;r++)t[r]=Number.parseInt(e.slice(r*2,r*2+2),16);return t}D();fe();C();async function ea(e,t){let[r,n]=await e.fingerprint(t);if(n!==0)return a(n);return Fe(r.slice(),Y.Fingerprint)}async function ta(e,t){let r=await e.gen256BitSecureRandomSeed(),[n,s]=await ea(t,r);if(s!==0)return a(s);return f({n:r,h:n})}async function cs(e,t){let[r,n]=await ea(e,t.n);if(n!==0)return!1;return tu(r,t.h)}function ra(e){if(e===void 0||e===null||typeof e!=="object")return;let t=e;if(!(t.n instanceof Uint8Array)||!(t.h instanceof Uint8Array))return;if(t.n.byteLength<1)return;let[r,n]=Fe(t.h.slice(),Y.Fingerprint);if(n!==0)return;return{n:t.n.slice(),h:r}}function na(e){let t=e.n.slice(),[r,n]=Fe(e.h.slice(),Y.Fingerprint);if(n!==0)return{n:t,h:e.h};return{n:t,h:r}}function tu(e,t){if(e.byteLength!==t.byteLength)return!1;let r=0;for(let n=0;n<e.byteLength;n++)r|=e[n]^t[n];return r===0}function us(e){if(e===""||typeof indexedDB>"u")return Promise.resolve();return new Promise((t,r)=>{let n=indexedDB.deleteDatabase(e);n.onsuccess=()=>t(),n.onerror=()=>r(n.error??Error(`[DIPLOMATIC] deleteDatabase failed (${e})`)),n.onblocked=()=>{console.warn(`[DIPLOMATIC] deleteDatabase blocked (${e})`)}})}function ds(e,t,r){return new Promise((n,s)=>{let o=indexedDB.open(e,t);o.onupgradeneeded=()=>{let{result:i,transaction:c}=o;if(c===null){s(Error(`[DIPLOMATIC] missing upgrade transaction (${e})`));return}try{r(i,c)}catch(u){s(u instanceof Error?u:Error(String(u)))}},o.onblocked=()=>{console.warn(`[DIPLOMATIC] IDB upgrade blocked (${e} → v${t})`)},o.onsuccess=()=>{let i=o.result;i.onversionchange=()=>{i.close()},n(i)},o.onerror=()=>{s(o.error??Error(`[DIPLOMATIC] IDB open failed (${e})`))}})}ce();var sa="meta",oa=1,ia=9;function ru(){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),et(e)}function nu(e){return`data-${e}`}function su(e){return`ents-${e}`}function ls(e,t){let r=e!==void 0&&e!==""?e:ru();if(t!==void 0&&t!=="")return{acct:r,data:t};return{acct:r,data:nu(r)}}function aa(e,t){if(t!==void 0&&t!=="")return t;return su(e)}D();C();class fs{db;constructor(e){this.db=e}async enq(e){let t=[...e];if(t.length===0)return;let r=this.db.transaction(Se,"readwrite"),n=r.objectStore(Se);return new Promise((s,o)=>{r.oncomplete=()=>s(),r.onerror=()=>o(r.error);for(let i of t)n.put(i,Bn(i.host,i.seq,i.realm))})}async deq(e,t,r){let n=[...t];if(n.length===0)return;let s=this.db.transaction(Se,"readwrite"),o=s.objectStore(Se);return new Promise((i,c)=>{s.oncomplete=()=>i(),s.onerror=()=>c(s.error);for(let u of n)o.delete(Bn(e,u,r))})}async list(){let t=this.db.transaction(Se,"readonly").objectStore(Se);return new Promise((r,n)=>{let s=t.getAll();s.onsuccess=()=>r(s.result),s.onerror=()=>n(s.error)})}async count(){let t=this.db.transaction(Se,"readonly").objectStore(Se);return new Promise((r,n)=>{let s=t.count();s.onsuccess=()=>r(s.result),s.onerror=()=>n(s.error)})}async wipe(){let e=this.db.transaction(Se,"readwrite"),t=e.objectStore(Se);return new Promise((r,n)=>{e.oncomplete=()=>r(),e.onerror=()=>n(e.error),t.clear()})}}D();fe();function ps(e){return e!==null&&typeof e==="object"}function ys(e){if(!ps(e))return!1;return typeof e.host==="string"&&typeof e.label==="string"&&typeof e.index==="number"&&Number.isInteger(e.index)&&typeof e.lastSeq==="number"&&Number.isInteger(e.lastSeq)&&e.lastSeq>=0}function ou(e){let t=[];if(!Array.isArray(e))return t;for(let r of e){if(!ys(r))continue;t.push({label:r.label,index:r.index,lastSeq:r.lastSeq})}return t}function iu(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!ys(r))continue;let n=t.get(r.host)??[];n.push({label:r.label,index:r.index,lastSeq:r.lastSeq}),t.set(r.host,n)}return t}function ca(e,t){let r=Oo(t),n={label:e.label,handle:new URL(e.handle),idx:e.idx,lastSeq:r.lastSeq,clockOffset:e.clockOffset,subscription:e.subscription};if(r.seqs!==void 0)n.seqs=r.seqs;return n}function ua(e){let t={label:e.label,handle:e.handle.toString()};if(e.idx!==void 0)t.idx=e.idx;if(e.clockOffset!==void 0)t.clockOffset=e.clockOffset;if(e.subscription!==void 0)t.subscription=e.subscription;return t}class ms{db;constructor(e){this.db=e}async add(e){let t=await this.get(e.label),r=t!==void 0&&t.handle.href===e.handle.href&&(t.idx??0)===(e.idx??0),n=ua(r&&t!==void 0?{...e,clockOffset:t.clockOffset,subscription:t.subscription}:e),s=this.db.transaction([de,me],"readwrite"),o=s.objectStore(de),i=s.objectStore(me);return new Promise((c,u)=>{if(s.oncomplete=()=>c(),s.onerror=()=>u(s.error),r){o.put(n);return}let d=i.index("host").getAllKeys(e.label);d.onsuccess=()=>{for(let l of d.result)i.delete(l);o.put(n)}})}async touch(e,t,r){return this.recordSeqs(e,{lastSeq:t},r)}async recordSeqs(e,t,r){let n=r??q,s=this.db.transaction([de,me],"readwrite"),o=s.objectStore(de),i=s.objectStore(me),c=[e,n.label,n.index];return new Promise((u,d)=>{s.oncomplete=()=>u(),s.onerror=()=>d(s.error);let l=o.get(e);l.onsuccess=()=>{if(!l.result)return;let p=i.get(c);p.onsuccess=()=>{let y=p.result,m=ys(y)?y.lastSeq:0,h=Lo(m,t);if(h===void 0)return;i.put({host:e,label:n.label,index:n.index,lastSeq:h})}}})}async get(e){let t=this.db.transaction([de,me],"readonly"),r=t.objectStore(de),n=t.objectStore(me);return new Promise((s,o)=>{t.onerror=()=>o(t.error);let i,c,u=2,d=()=>{if(u-=1,u>0)return;if(!ps(i)){s(void 0);return}s(ca(i,ou(c)))},l=r.get(e);l.onsuccess=()=>{i=l.result,d()};let p=n.index("host").getAll(e);p.onsuccess=()=>{c=p.result,d()}})}async set(e,t){let r=await this.get(e);if(!r)return 13;try{return await this.put(ua({...r,...t})),0}catch{return 18}}async del(e){let t=this.db.transaction([de,me],"readwrite"),r=t.objectStore(de),n=t.objectStore(me);return new Promise((s,o)=>{t.oncomplete=()=>s(),t.onerror=()=>o(t.error),r.delete(e);let i=n.index("host").getAllKeys(e);i.onsuccess=()=>{for(let c of i.result)n.delete(c)}})}async list(){let e=this.db.transaction([de,me],"readonly"),t=e.objectStore(de),r=e.objectStore(me);return new Promise((n,s)=>{e.onerror=()=>s(e.error);let o,i,c=2,u=()=>{if(c-=1,c>0)return;let p=iu(i),y=[];if(Array.isArray(o))for(let m of o){if(!ps(m)||typeof m.label!=="string")continue;y.push(ca(m,p.get(m.label)??[]))}n(y)},d=t.getAll();d.onsuccess=()=>{o=d.result,u()};let l=r.getAll();l.onsuccess=()=>{i=l.result,u()}})}async wipe(){let e=this.db.transaction([de,me],"readwrite"),t=e.objectStore(de),r=e.objectStore(me);return new Promise((n,s)=>{e.oncomplete=()=>n(),e.onerror=()=>s(e.error),t.clear(),r.clear()})}put(e){let t=this.db.transaction(de,"readwrite"),r=t.objectStore(de);return new Promise((n,s)=>{t.oncomplete=()=>n(),t.onerror=()=>s(t.error),r.put(e)})}}function gs(){return ds(sa,oa,(e)=>{if(!e.objectStoreNames.contains(we))e.createObjectStore(we,{keyPath:"label"})})}function Ss(e){return ds(e,ia,au)}function au(e,t){if(!e.objectStoreNames.contains(de))e.createObjectStore(de,{keyPath:"label"});if(!e.objectStoreNames.contains(be))e.createObjectStore(be,{keyPath:["host","hash"]});if(!e.objectStoreNames.contains(Se))e.createObjectStore(Se);let r;if(!e.objectStoreNames.contains(ee))r=e.createObjectStore(ee);else r=t.objectStore(ee);if(!r.indexNames.contains(Ut))r.createIndex(Ut,"apld",{unique:!1});if(!r.indexNames.contains(hs))r.createIndex(hs,"rlm",{unique:!1});if(!e.objectStoreNames.contains(xe))e.createObjectStore(xe,{keyPath:"label"});if(!e.objectStoreNames.contains(me))e.createObjectStore(me,{keyPath:["host","label","index"]}).createIndex("host","host",{unique:!1})}ce();D();class bs{db;crypto;constructor(e,t){this.db=e;this.crypto=t}async add(e){let t=this.db.transaction(ee,"readwrite"),r=t.objectStore(ee);return new Promise((n)=>{if(e.length===0){n([]);return}let s=Array(e.length).fill(0);t.oncomplete=()=>n(s),t.onerror=()=>{for(let o=0;o<s.length;o++)s[o]=18;n(s)};for(let o=0;o<e.length;o++){let{key:i,data:c}=e[o],u=K(i),d=r.put(Cr(c),u);d.onerror=(l)=>{l.preventDefault(),s[o]=18}}})}async del(e){let t=[...e];if(t.length===0)return;let r=this.db.transaction(ee,"readwrite"),n=r.objectStore(ee);return new Promise((s,o)=>{r.oncomplete=()=>s(),r.onerror=()=>o(r.error);for(let i of t){let c=K(i);n.delete(c)}})}async get(e){let r=this.db.transaction(ee,"readonly").objectStore(ee);return new Promise((n,s)=>{let o=K(e),i=r.get(o);i.onsuccess=async()=>{let c=i.result;if(c)n(await Hr(e,c,this.crypto));else n(void 0)},i.onerror=()=>s(i.error)})}async has(e){return await this.get(e)!==void 0}async list(e){let t=e?.apld,r=e?.body!==!1,s=this.db.transaction(ee,"readonly").objectStore(ee);return new Promise((o,i)=>{let c=[],u=t===void 0?s.openCursor():s.index(Ut).openCursor(IDBKeyRange.only(t));u.onsuccess=(d)=>{let l=d.target.result;if(l){let p=t===void 0?l.key:l.primaryKey,y=l.value;c.push({hash:Ee(p),data:y}),l.continue()}else Promise.all(c.map(({hash:p,data:y})=>Hr(p,y,this.crypto,{body:r}))).then(o).catch(i)},u.onerror=()=>i(u.error)})}async count(e){let r=this.db.transaction(ee,"readonly").objectStore(ee);return new Promise((n,s)=>{let o=e===void 0?r.count():r.index(Ut).count(IDBKeyRange.only(e));o.onsuccess=()=>n(o.result),o.onerror=()=>s(o.error)})}async listKeys(){let t=this.db.transaction(ee,"readonly").objectStore(ee);return new Promise((r,n)=>{let s=[],o=t.openKeyCursor();o.onsuccess=(i)=>{let c=i.target.result;if(c)s.push(Ee(c.key)),c.continue();else r(s)},o.onerror=()=>n(o.error)})}async last(e){let r=this.db.transaction(ee,"readonly").objectStore(ee);return new Promise((n,s)=>{let o,i=r.openCursor();i.onsuccess=async(c)=>{let u=c.target.result;if(u){let{key:d,value:l}=u;if(G(e,l.eid)){if(!o||(l.ctr??0)>(o.data.ctr??0)||(l.ctr??0)===(o.data.ctr??0)&&(l.off??0)>(o.data.off??0))o={key:d,data:l}}u.continue()}else if(o){let d=Ee(o.key);n(await Hr(d,o.data,this.crypto))}else n(void 0)},i.onerror=()=>s(i.error)})}async markApplied(e){let t=[...e];if(t.length===0)return;let r=this.db.transaction(ee,"readwrite"),n=r.objectStore(ee);return new Promise((s,o)=>{r.oncomplete=()=>s(),r.onerror=()=>o(r.error);for(let i of t){let c=K(i),u=n.get(c);u.onsuccess=()=>{let d=u.result;if(!d)return;_n(d,Rr),n.put(d,c)},u.onerror=(d)=>{d.preventDefault()}}})}async markFailed(e){let t=[...e];if(t.length===0)return;let r=this.db.transaction(ee,"readwrite"),n=r.objectStore(ee);return new Promise((s,o)=>{r.oncomplete=()=>s(),r.onerror=()=>o(r.error);for(let{key:i,err:c}of t){let u=K(i),d=n.get(u);d.onsuccess=()=>{let l=d.result;if(!l)return;_n(l,kt,c),n.put(l,u)},d.onerror=(l)=>{l.preventDefault()}}})}async wipe(){let e=this.db.transaction(ee,"readwrite"),t=e.objectStore(ee);return new Promise((r,n)=>{e.oncomplete=()=>r(),e.onerror=()=>n(e.error),t.clear()})}}D();class Is{db;constructor(e){this.db=e}async list(){let t=this.db.transaction(xe,"readonly").objectStore(xe);return new Promise((r,n)=>{let s=t.getAll();s.onsuccess=()=>{let o=s.result,i=[];if(Array.isArray(o))for(let c of o){let u=Ur(c);if(u!==void 0)i.push(u)}r(i)},s.onerror=()=>n(s.error)})}async get(e){let r=this.db.transaction(xe,"readonly").objectStore(xe);return new Promise((n,s)=>{let o=r.get(e);o.onsuccess=()=>n(Ur(o.result)),o.onerror=()=>s(o.error)})}async put(e,t){let r=this.db.transaction(xe,"readwrite"),n=r.objectStore(xe);return new Promise((s,o)=>{let i=0;r.oncomplete=()=>s(i),r.onerror=()=>o(r.error);let c=n.get(e);c.onsuccess=()=>{let[u,d]=fi(e,Ur(c.result),t);if(d!==0){i=d;return}n.put(u)}})}async wipe(){let e=this.db.transaction(xe,"readwrite"),t=e.objectStore(xe);return new Promise((r,n)=>{e.oncomplete=()=>r(),e.onerror=()=>n(e.error),t.clear()})}}ce();class ws{db;constructor(e){this.db=e}async enq(e,t){let r=[...t];if(r.length===0)return;let n=this.db.transaction(be,"readwrite"),s=n.objectStore(be);return new Promise((o,i)=>{n.oncomplete=()=>o(),n.onerror=()=>i(n.error);for(let c of r){let u=et(c);s.put({host:e,hash:u})}})}async deq(e,t){let r=[...t];if(r.length===0)return;let n=this.db.transaction(be,"readwrite"),s=n.objectStore(be);return new Promise((o,i)=>{n.oncomplete=()=>o(),n.onerror=()=>i(n.error);for(let c of r){let u=et(c);s.delete([e,u])}})}async list(e){let r=this.db.transaction(be,"readonly").objectStore(be);return new Promise((n,s)=>{let o=r.getAll();o.onsuccess=()=>{let c=o.result.filter((u)=>u.host===e).map((u)=>u.hash);n(c.map((u)=>Ks(u)))},o.onerror=()=>s(o.error)})}async count(){let t=this.db.transaction(be,"readonly").objectStore(be);return new Promise((r,n)=>{let s=t.count();s.onsuccess=()=>r(s.result),s.onerror=()=>n(s.error)})}async wipe(){let e=this.db.transaction(be,"readwrite"),t=e.objectStore(be);return new Promise((r,n)=>{e.oncomplete=()=>r(),e.onerror=()=>n(e.error),t.clear()})}}var we="accounts",de="hosts",me="host_seqs",be="uploadQueue",Se="downloadQueue",ee="messages",Ut="apld",hs="rlm",xe="realms";function cu(e,t){return{realms:new Is(e),hosts:new ms(e),uploads:new ws(e),downloads:new fs(e),messages:new bs(e,t)}}function da(){return{realms:{async list(){return[]},async get(){return},async put(){return 13},async wipe(){}},hosts:{async add(){},async get(){return},async del(){},async set(){return 13},async list(){return[]},async wipe(){},async touch(){},async recordSeqs(){}},uploads:{async enq(){},async deq(){},async list(){return[]},async count(){return 0},async wipe(){}},downloads:{async enq(){},async deq(){},async list(){return[]},async count(){return 0},async wipe(){}},messages:{async add(e){return e.map(()=>18)},async get(){return},async has(){return!1},async del(){},async list(){return[]},async count(){return 0},async listKeys(){return[]},async last(){return},async markApplied(){},async markFailed(){},async wipe(){}}}}class la{account;realms;hosts;uploads;downloads;messages;#e;#t;#n;constructor(e,t,r,n){this.account=e,this.#t=t,this.#n=r;let s=da();if(this.realms=s.realms,this.hosts=s.hosts,this.uploads=s.uploads,this.downloads=s.downloads,this.messages=s.messages,n!==void 0)this.#s(n)}#s(e){let t=this.#e;if(this.#e=e,e.onversionchange=()=>{if(this.#e!==e)return;this.#r()},this.#i(cu(e,this.#t)),t!==void 0&&t!==e)t.close()}#r(){let e=this.#e;if(this.#e=void 0,this.#i(da()),e!==void 0)e.close()}#i(e){this.realms=e.realms,this.hosts=e.hosts,this.uploads=e.uploads,this.downloads=e.downloads,this.messages=e.messages}async bind(e){if(this.#n===void 0)return this.#e===void 0?13:0;let t=await this.#n(e);if(t===void 0)return 13;if(this.#e!==void 0&&this.#e.name===t)return 0;let r=await Ss(t);return this.#s(r),0}async prepareWorker(e){let t=await this.#n?.(e);if(t===void 0)return a(13);if(!(this.account instanceof or))return a(10);let r=await this.account.ensureEnts(e);return f({data:t,ents:r})}close(){this.#r()}async wipe(){await this.hosts.wipe(),await this.uploads.wipe(),await this.downloads.wipe(),await this.messages.wipe()}}async function fa(e,t){let r=await Ss(t);return new la({async save(){return a(10)},async wipe(){}},e,void 0,r)}function pa(e){return e!==null&&typeof e==="object"}function xs(e,t){let r=e[t];if(typeof r!=="string"||r==="")return;return r}function uu(e,t){if(e===void 0)return t;if(t.acct===void 0)t.acct=e.acct;if(t.data===void 0)t.data=e.data;if(t.ents===void 0)t.ents=e.ents;return t}function Ps(e){if(!pa(e)||typeof e.label!=="string")return;let t={label:e.label},r=xs(e,"acct"),n=xs(e,"data"),s=xs(e,"ents");if(r!==void 0)t.acct=r;if(n!==void 0)t.data=n;if(s!==void 0)t.ents=s;let o=ra(e.keyTag),i=Zi(e.keyring);if(o!==void 0)t.keyTag=o;if(i!==void 0)t.keyring=i;return t}function du(e){let t=[];for(let r of e){let n=r.keyring;if(n===void 0)continue;for(let s of n.entries){if(s.credId.byteLength===0)continue;let o=!1;for(let i of t){if(!G(i.credId,s.credId))continue;if(i.label!==r.label)return a(10);o=!0;break}if(o)continue;t.push({label:r.label,salt:n.salt,sealedMaster:s.sealedMaster,credId:s.credId})}}return f(t)}function lu(e){if(!Array.isArray(e))return[];let t=[];for(let r of e){let n=Ps(r);if(n!==void 0)t.push(n)}return t}function fu(e,t,r,n){let s={label:t.label};if(t.acct!==void 0)s.acct=t.acct;if(t.data!==void 0)s.data=t.data;if(t.ents!==void 0)s.ents=t.ents;if(r!==void 0)s.keyTag=r;if(n!==void 0)s.keyring=n;e.put(s)}class or{db;#e;#t;constructor(e,t){this.db=e,this.#e=t}setCloser(e){this.#t=e}async create(e,t){let[r,n]=je(e);if(n!==0||r===void 0)return t.fill(0),a(10);if((await this.#r(r))?.keyTag!==void 0)return t.fill(0),a(19);if(t.byteLength<Qr)return t.fill(0),a(10);let[o,i]=await ye.fromRandom(t);if(i!==0)return a(i);return this.save(o,{label:r})}async save(e,t){let[r,n]=je(t?.label);if(n!==0||r===void 0)return a(10);let s=await this.#n(e,r);if(s!==0)return a(s);return f(e)}async dataName(e){let t=await this.#r(e);if(t===void 0)return;if(t.data!==void 0&&t.data!=="")return t.data;return await this.#o(e,(n)=>{if(n===void 0)return;return{...n}}),(await this.#r(e))?.data}async ensureEnts(e){let[t,r]=je(e);if(r!==0||t===void 0)throw Error("[DIPLOMATIC] invalid account label");let n=await this.#r(t),s=ls(n?.acct,n?.data),o=aa(s.acct,n?.ents);return await this.#o(t,(i)=>({...i===void 0?{label:t}:{...i},acct:s.acct,data:s.data,ents:o})),o}async wipe(){let e=await this.#i();this.#t?.();for(let n of e){if(n.data!==void 0)await us(n.data);if(n.ents!==void 0)await us(n.ents)}let t=this.db.transaction(we,"readwrite"),r=t.objectStore(we);return new Promise((n,s)=>{t.oncomplete=()=>n(),t.onerror=()=>s(t.error),r.clear()})}async loadKeyring(e){let[t,r]=await this.#s(e);if(r!==0||t===void 0)return;return(await this.#r(t))?.keyring}async persistKeyring(e,t){let r;if(e!==void 0){let[o,i]=nr(e);if(i!==0)return i;r=o}let[n,s]=await this.#s(t);if(s!==0)return s;if(n===void 0)return 13;return await this.#o(n,(o)=>{if(r===void 0){if(o?.keyTag===void 0)return;return{label:n,keyTag:o.keyTag}}let i={label:n,keyring:r};if(o?.keyTag!==void 0)i.keyTag=o.keyTag;return i}),0}async hasKeyring(e){let t=await this.loadKeyring(e);return t!==void 0&&t.entries.length>0}async unlock(e){let[t,r]=du(await this.#i());if(r!==0)return a(r);if(t===void 0||t.length===0)return a(22);let n=t[0];if(n===void 0)return a(22);let[s,o]=await ye.unsealWithPasskey(t.map((y)=>({sealedMaster:y.sealedMaster,credId:y.credId,salt:y.salt})),{rpId:e.rpId,rpName:e.rpName,salt:n.salt});if(o!==0)return a(o);if(s===void 0)return a(20);let i=t.find((y)=>G(y.credId,s.credId));if(i===void 0)return a(13);let c=await this.#r(i.label),u=c?.keyTag;if(u!==void 0){if(!await cs(s.enclave,u))return a(19)}let d=c?.keyring;if(d===void 0)return a(13);let[l,p]=as(d,s.credId);if(p!==0)return a(p);if(l!==void 0)await this.#o(i.label,(y)=>{let m={label:i.label,keyring:l};if(y?.keyTag!==void 0)m.keyTag=y.keyTag;return m});return f({enclave:s.enclave,label:i.label})}async openPrfStore(e,t){let[r,n]=await this.#s(t),s=n===0?await this.loadKeyring(r):void 0,o=n===0?r:void 0;return $r.open({rpId:e.rpId,rpName:e.rpName,userName:e.userName,keyring:s,persistKeyring:(i)=>this.persistKeyring(i,o),unlockAccount:async()=>{let[i,c]=await this.unlock(e);if(c!==0)return a(c);if(i===void 0)return a(13);return o=i.label,f({enclave:i.enclave,keyring:await this.loadKeyring(i.label)})}})}async#n(e,t){let r=await this.#r(t);if(r?.keyTag!==void 0){if(!await cs(e,r.keyTag))return 19;return 0}let[n,s]=await ta(this.#e,e);if(s!==0)return s;let o=na(n),i=!1;if(await this.#o(t,(c)=>{if(c?.keyTag!==void 0)return i=!0,c;let u={label:t,keyTag:o};if(c?.keyring!==void 0)u.keyring=c.keyring;return u}),!i)return 0;return this.#n(e,t)}async#s(e){if(e!==void 0){let[n,s]=je(e);if(s!==0||n===void 0)return a(10);return f(n)}let t=await this.#i(),r=t.length===1?t[0]:void 0;if(r!==void 0)return f(r.label);if(t.length===0)return a(13);return a(10)}#r(e){let r=this.db.transaction(we,"readonly").objectStore(we);return new Promise((n,s)=>{let o=r.get(e);o.onsuccess=()=>n(Ps(o.result)),o.onerror=()=>s(o.error)})}#i(){let t=this.db.transaction(we,"readonly").objectStore(we);return new Promise((r,n)=>{let s=t.getAll();s.onsuccess=()=>r(lu(s.result)),s.onerror=()=>n(s.error)})}async#o(e,t){let r=this.db.transaction(we,"readwrite"),n=r.objectStore(we);return new Promise((s,o)=>{r.oncomplete=()=>s(),r.onerror=()=>o(r.error);let i=n.get(e);i.onsuccess=()=>{let c=pa(i.result)?i.result:void 0,u=Ps(i.result),d=t(u);if(d===void 0){if(u!==void 0)n.delete(e);return}let l=uu(u,d===u?{...d}:d),p=ls(l.acct,l.data);if(l.acct=p.acct,l.data=p.data,d===u&&u?.acct===l.acct&&u?.data===l.data&&u?.ents===l.ents)return;let y=void 0;if(l.keyTag!==void 0)y=l.keyTag===u?.keyTag&&c?.keyTag!==void 0?c.keyTag:l.keyTag;let m=void 0;if(l.keyring!==void 0)m=l.keyring===u?.keyring&&c?.keyring!==void 0?c.keyring:l.keyring;fu(n,l,y,m)}})}}async function ya(e){let t=await gs();try{return await new or(t,Dt).ensureEnts(e)}finally{t.close()}}D();C();ce();var se="entities",Yr="entity_type_created_at",As="entity_type_updated_at",ks="entity_type_parent_id",Ds="entity_tags",ma="entity_rlm",ha=15;function pu(e){return"typ"in e}function yu(e){let t=it(e.rlm),r={bod:e.body,crd:e.createdAt,...e.ctr!==0?{ctr:e.ctr}:{},eid:K(e.eid),pid:e.pid?K(e.pid):void 0,...t!==void 0?{rlm:t}:{},tgs:e.tags,typ:e.type,upd:e.updatedAt};if(r.pid===void 0)delete r.pid;if(r.tgs===void 0)delete r.tgs;if(r.ctr===void 0)delete r.ctr;return r}function mu(e){if(!Z(e))return{eid:K(e.eid),upd:e.updatedAt,...e.ctr!==0?{ctr:e.ctr}:{}};return yu(e)}function Rt(e){let t=it(e.rlm);return{body:e.bod,createdAt:e.crd,updatedAt:e.upd,ctr:e.ctr??0,type:e.typ,eid:Ee(e.eid),pid:e.pid?Ee(e.pid):void 0,...e.tgs!==void 0?{tags:e.tgs}:{},...t!==void 0?{rlm:t}:{}}}function Es(e){if(pu(e))return Rt(e);return{eid:Ee(e.eid),updatedAt:e.upd,ctr:e.ctr??0}}function hu(e,t){if(t instanceof Date)return IDBKeyRange.only([e,t]);let r=t.range;return IDBKeyRange.bound([e,r.start],[e,r.end],r.excludeStart===!0,r.excludeEnd===!0)}function gu(e){if(typeof e==="string")return IDBKeyRange.only(e);if("range"in e){let t=e.range;return IDBKeyRange.bound(t.start,t.end,t.excludeStart===!0,t.excludeEnd===!0)}return IDBKeyRange.bound(e.prefix,e.prefix+"")}function Su(e,t,r){let n=[];if(typeof r==="string"){for(let i of e)if(i.typ===t)n.push(Rt(i));return n}let s=new Set,o="prefix"in r?r.prefix:void 0;for(let i of e){if(i.typ!==t)continue;if(s.has(i.eid))continue;if(o!==void 0){let c=i.tgs;if(!c||!c.some((u)=>u.startsWith(o)))continue}s.add(i.eid),n.push(Rt(i))}return n}class ga{name;db;opening;constructor(e){this.name=e}async init(){await this.ensureDb()}close(){let e=this.db;if(this.db=void 0,this.opening=void 0,e!==void 0)e.close()}async ensureDb(){if(this.db)return this.db;if(this.opening)return this.opening;return this.opening=Iu(this.name).then((e)=>(e.onversionchange=()=>{if(e.close(),this.db===e)this.db=void 0},this.db=e,this.opening=void 0,e),(e)=>{throw this.opening=void 0,e}),this.opening}apply=async(e)=>{let t=new Set,r=[],n=performance.now();W("idb apply start",{ops:e.length});let s;try{s=await this.ensureDb()}catch{return{stats:e.map(()=>16),types:t,eids:r}}let o=s.transaction(se,"readwrite"),i=o.objectStore(se);return new Promise((c)=>{let u=Array(e.length).fill(0);if(e.length<1){c({stats:[],types:t,eids:r});return}o.oncomplete=()=>{W("idb apply complete",{ops:e.length,ms:Math.round(performance.now()-n)}),c({stats:u,types:t,eids:r})},o.onerror=()=>{for(let l=0;l<u.length;l++)if(u[l]===void 0)u[l]=18;c({stats:u,types:t,eids:r})};let d=new Map;for(let l=0;l<e.length;l++){let p=e[l],y=K(p.eid),m={op:p,index:l},h=d.get(y);if(h)h.push(m);else d.set(y,[m])}for(let[l,p]of d){if(p.length<1)continue;let y=i.get(l);y.onsuccess=()=>{let m=y.result,h=m?Es(m):void 0,g=!1;for(let{op:S,index:b}of p){let[x,E]=Pt(h,S);if(E!==0){u[b]=E;continue}if(x===void 0){u[b]=12;continue}g=!0;for(let P of Et(h,x))t.add(P);h=x}if(g)r.push(p[0].op.eid);if(h){let S=i.put(mu(h));S.onerror=(b)=>{b.preventDefault();for(let{index:x}of p)u[x]=18}}},y.onerror=()=>{for(let{index:m}of p)u[m]=18}}})};async clear(){let e;try{e=await this.ensureDb()}catch{return 16}let t=e.transaction(se,"readwrite"),r=t.objectStore(se);return new Promise((n)=>{t.oncomplete=()=>n(0),t.onerror=()=>n(18),r.clear()})}async getRow(e){let t;try{t=await this.ensureDb()}catch{return a(16)}let r=K(e),s=t.transaction(se,"readonly").objectStore(se);return new Promise((o)=>{let i=s.get(r);i.onsuccess=()=>{let c=i.result;if(!c)o(f(void 0));else o(f(Es(c)))},i.onerror=()=>o(a(18))})}async getEnt(e){let[t,r]=await this.getRow(e);if(r!==0)return a(r);if(t===void 0||!Z(t))return f(void 0);return f(t)}async getByUpdatedAt(e,t){let[r,n]=zt(t);if(n!==0)return a(n);if(!r)return f([]);let s;try{s=await this.ensureDb()}catch{return a(16)}let i=s.transaction(se,"readonly").objectStore(se).index(As),c=hu(e,t);return new Promise((u)=>{let d=i.getAll(c);d.onsuccess=()=>{let l=d.result;u(f(l.map(Rt)))},d.onerror=()=>u(a(18))})}async getAllOfType(e){let t;try{t=await this.ensureDb()}catch{return a(16)}let n=t.transaction(se,"readonly").objectStore(se).index(Yr);return new Promise((s)=>{let o=n.getAll(IDBKeyRange.bound([e],[e,[]]));o.onsuccess=()=>{let i=o.result;s(f(i.map(Rt)))},o.onerror=()=>s(a(18))})}async getByTag(e,t){let[r,n]=Yt(t);if(n!==0)return a(n);if(!r)return f([]);let s;try{s=await this.ensureDb()}catch{return a(16)}let o=gu(t),c=s.transaction(se,"readonly").objectStore(se).index(Ds);return new Promise((u)=>{let d=c.getAll(o);d.onsuccess=()=>{let l=d.result;u(f(Su(l,e,t)))},d.onerror=()=>u(a(18))})}async getAllEntities(e){if("pid"in e){let t;try{t=await this.ensureDb()}catch{return a(16)}let r=K(e.pid),s=t.transaction(se,"readonly").objectStore(se).index(ks);return new Promise((o)=>{let i=s.getAll(IDBKeyRange.only([e.type,r]));i.onsuccess=()=>{let u=i.result.map(Rt);o(f(u))},i.onerror=()=>o(a(18))})}else if("tag"in e)return await this.getByTag(e.type,e.tag);else if("updatedAt"in e)return await this.getByUpdatedAt(e.type,e.updatedAt);return await this.getAllOfType(e.type)}async getEntities(e){let t=performance.now(),[r,n]=await this.getAllEntities(e);if(W("idb getEntities",{type:e.type,n:r?.length??0,ms:Math.round(performance.now()-t)}),n!==0)return a(n);return f(r)}async countEntities({type:e}){let t;try{t=await this.ensureDb()}catch{return a(16)}let n=t.transaction(se,"readonly").objectStore(se).index(Yr);return new Promise((s)=>{let o=IDBKeyRange.bound([e],[e,[]]),i=n.count(o);i.onsuccess=()=>s(f(i.result)),i.onerror=()=>s(a(18))})}async checksum(e){let t;try{t=await this.ensureDb()}catch{return a(16)}let n=t.transaction(se,"readonly").objectStore(se),s=[];return new Promise((o)=>{let i=n.openCursor();i.onsuccess=()=>{let c=i.result;if(c){let u=c.value;s.push(Br(Es(u))),c.continue()}else kr(s,e).then(o)},i.onerror=()=>o(a(18))})}}function bu(e,t){if(!e.objectStoreNames.contains(se))e.createObjectStore(se,{keyPath:"eid",autoIncrement:!1});let r=t.objectStore(se);if(!r.indexNames.contains(Yr))r.createIndex(Yr,["typ","crd"],{unique:!1});if(!r.indexNames.contains(As))r.createIndex(As,["typ","upd"],{unique:!1});if(!r.indexNames.contains(ks))r.createIndex(ks,["typ","pid"],{unique:!1});if(!r.indexNames.contains(Ds))r.createIndex(Ds,"tgs",{unique:!1,multiEntry:!0});if(!r.indexNames.contains(ma))r.createIndex(ma,"rlm",{unique:!1})}function Iu(e){return new Promise((t,r)=>{let n=indexedDB.open(e,ha);n.onupgradeneeded=()=>{let{result:s,transaction:o}=n;if(!o){r(Error("Transaction is null during EntDB upgrade"));return}try{bu(s,o)}catch(i){r(i instanceof Error?i:Error(String(i)))}},n.onblocked=()=>{console.warn(`[DIPLOMATIC] EntDB IDB upgrade blocked (${e} → v${ha}); waiting for other connections to close`)},n.onsuccess=()=>t(n.result),n.onerror=()=>r(n.error??Error("EntDB IndexedDB open failed"))})}async function Sa(e){let t=new ga(e);return await t.init(),t}ce();D();C();class Bs{ents=new Map;useIndex;byType=new Map;byTypePid=new Map;byTypeTag=new Map;constructor(e=[],t){this.useIndex=t?.indexes!==!1;for(let r of e)this.put(r)}put(e){let t=Z(e)?Cr(e):e,r=K(t.eid),n=this.ents.get(r);if(n!==void 0&&Z(n))this.unindex(r,n);if(this.ents.set(r,t),Z(t))this.index(r,t)}del(e){let t=this.ents.get(e);if(t===void 0)return;if(Z(t))this.unindex(e,t);this.ents.delete(e)}index(e,t){if(!this.useIndex)return;let r=this.byType.get(t.type);if(!r)r=new Map,this.byType.set(t.type,r);if(r.set(e,t),t.pid){let n=K(t.pid),s=this.byTypePid.get(t.type);if(!s)s=new Map,this.byTypePid.set(t.type,s);let o=s.get(n);if(!o)o=new Map,s.set(n,o);o.set(e,t)}if(t.tags){let n=this.byTypeTag.get(t.type);if(!n)n=new Map,this.byTypeTag.set(t.type,n);for(let s of t.tags){let o=n.get(s);if(!o)o=new Map,n.set(s,o);o.set(e,t)}}}unindex(e,t){if(!this.useIndex)return;let r=this.byType.get(t.type);if(r){if(r.delete(e),r.size===0)this.byType.delete(t.type)}if(t.pid){let n=K(t.pid),s=this.byTypePid.get(t.type),o=s?.get(n);if(o){if(o.delete(e),o.size===0)s?.delete(n)}if(s&&s.size===0)this.byTypePid.delete(t.type)}if(t.tags){let n=this.byTypeTag.get(t.type);if(n){for(let s of t.tags){let o=n.get(s);if(o){if(o.delete(e),o.size===0)n.delete(s)}}if(n.size===0)this.byTypeTag.delete(t.type)}}}clearIndexes(){this.byType.clear(),this.byTypePid.clear(),this.byTypeTag.clear()}bucketList(e){if(!e||e.size===0)return[];let t=[];for(let r of e.values())t.push(r);return t}byTagSpec(e,t){let[r,n]=Yt(t);if(n!==0)return a(n);if(!r)return f([]);if(typeof t==="string")return f(this.bucketList(this.byTypeTag.get(e)?.get(t)));let s=this.byTypeTag.get(e);if(!s)return f([]);let o=new Set,i=[];for(let[c,u]of s){if(!Tn(c,t))continue;for(let[d,l]of u){if(o.has(d))continue;o.add(d),i.push(l)}}return f(i)}byDateSpec(e,t){let[r,n]=zt(t);if(n!==0)return a(n);if(!r)return f([]);let s=[],o=this.byType.get(e);if(o){for(let i of o.values())if(Hn(i.updatedAt,t))s.push(i)}return f(s)}async apply(e){let t=new Set,r=[],n=[];for(let s of e){let o=K(s.eid),i=this.ents.get(o),[c,u]=Pt(i,s);if(u!==0){n.push(u);continue}if(c===void 0){n.push(12);continue}for(let d of Et(i,c))t.add(d);this.put(c),r.push(s.eid),n.push(0)}return{stats:n,types:t,eids:r}}async clear(){return this.ents.clear(),this.clearIndexes(),0}async getRow(e){let t=K(e),r=this.ents.get(t);return f(r)}async getEnt(e){let[t,r]=await this.getRow(e);if(r!==0)return a(r);if(t===void 0||!Z(t))return f(void 0);return f(t)}async getAllEntities(e){let{type:t}=e;if(this.useIndex){if("pid"in e){let n=K(e.pid);return f(this.bucketList(this.byTypePid.get(t)?.get(n)))}if("tag"in e)return this.byTagSpec(t,e.tag);if("updatedAt"in e)return this.byDateSpec(t,e.updatedAt);return f(this.bucketList(this.byType.get(t)))}let r=[];if("pid"in e){for(let n of this.ents.values())if(Z(n)&&n.type===t&&n.pid&&G(n.pid,e.pid))r.push(n)}else if("tag"in e){let n=e.tag,[s,o]=Yt(n);if(o!==0)return a(o);if(!s)return f(r);for(let i of this.ents.values())if(Z(i)&&i.type===t&&i.tags&&i.tags.some((c)=>Tn(c,n)))r.push(i)}else if("updatedAt"in e){let n=e.updatedAt,[s,o]=zt(n);if(o!==0)return a(o);if(!s)return f(r);for(let i of this.ents.values())if(Z(i)&&i.type===t&&Hn(i.updatedAt,n))r.push(i)}else for(let n of this.ents.values())if(Z(n)&&n.type===t)r.push(n);return f(r)}async getEntities(e){let[t,r]=await this.getAllEntities(e);if(r!==0)return a(r);return f(t)}async countEntities({type:e}){if(this.useIndex)return f(this.byType.get(e)?.size??0);let t=0;for(let r of this.ents.values())if(Z(r)&&r.type===e)t+=1;return f(t)}async checksum(e){let t=[];for(let r of this.ents.values())t.push(Br(r));return kr(t,e)}}function wu(e){let t=globalThis.requestAnimationFrame;if(typeof t!=="function"){queueMicrotask(e);return}t(()=>{t(e)})}async function Ia(e){if(e?.verbose!==void 0)ri(e.verbose);let t=e?.name??await ya(e?.label??""),r=await Sa(t);if(e?.cache===!1)return r;return new wa(r,void 0,{indexes:e?.indexes,optimistic:e?.optimistic})}class wa{mem;durable;warmed=new Set;listeners=new Set;chain=Promise.resolve();optimistic;inflight=0;warmP=new Map;constructor(e,t,r){if(this.durable=e,this.optimistic=r?.optimistic!==!1,W("CachedEntDB open",{optimistic:this.optimistic}),this.mem=new Bs(t??[],{indexes:r?.indexes}),t)for(let n of t)this.warmed.add(n.type)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(e){if(e.size<1)return;let t=performance.now();W("emit start",{types:[...e],listeners:this.listeners.size});for(let r of this.listeners)r(e);W("emit done",{ms:Math.round(performance.now()-t)})}run(e){let t=this.chain.then(e,e);return this.chain=t.then(()=>{return},()=>{return}),t}apply(e){let t,r;if(this.optimistic){r=Du(this.mem,e).types,t=new Map;for(let s of e){let o=K(s.eid);t.set(o,ba(this.mem.ents.get(o)))}this.inflight+=1,W("apply mem patched",{ops:e.length,types:r?[...r]:[],inflight:this.inflight})}let n=this.run(async()=>{W("persist start",{ops:e.length});try{let s=performance.now(),o=await this.durable.apply(e);if(W("persist durable.apply done",{ms:Math.round(performance.now()-s)}),!this.optimistic){let{changed:c,status:u}=await this.pullEids(e.map((d)=>d.eid));if(this.emit(c),u!==0)return{stats:e.map(()=>u),types:o.types,eids:o.eids};return o}let i=[];for(let c=0;c<e.length;c++)if(o.stats[c]!==0)i.push(e[c].eid);if(i.length>0){W("persist pull rejected eids",{n:i.length});let{changed:c,status:u}=await this.pullEids(i,t);if(this.emit(c),u!==0)return{stats:e.map(()=>u),types:o.types,eids:o.eids}}return W("persist done"),o}finally{if(this.optimistic)this.inflight-=1}});if(r)wu(()=>{W("emit after paint"),this.emit(r)});return n}clear(){return this.run(async()=>{let e=await this.durable.clear();if(e!==0)return e;let t=this.mem.ents.size>0;return await this.mem.clear(),this.warmed.clear(),0})}ingestFromDurable(e){let t=[...e].length;return W("ingest queued",{eids:t}),this.run(async()=>{let r=performance.now();W("ingest start",{eids:t});let{changed:n,status:s}=await this.pullEids(e);return W("ingest done",{ms:Math.round(performance.now()-r),changed:[...n]}),this.emit(n),s})}async pullEids(e,t){let r=new Set,n=new Set;for(let s of e){let o=K(s);if(n.has(o))continue;n.add(o);let[i,c]=await this.durable.getRow(s);if(c!==0)return{changed:r,status:c};let u=this.mem.ents.get(o);if(u!==void 0&&i!==void 0&&vs(u,i))continue;if(t){if(!ku(ba(u),t.get(o)))continue}if(i){if(this.mem.put(i),!u||!xu(u,i)){if(Z(i))r.add(i.type);if(u!==void 0&&Z(u))r.add(u.type)}}else if(u!==void 0){if(this.mem.del(o),Z(u))r.add(u.type)}}return{changed:r,status:0}}async warmType(e){if(this.warmed.has(e))return 0;let t=performance.now();W("warmType start",{type:e});let[r,n]=await this.durable.getEntities({type:e});if(n!==0)return n;if(r)for(let s of r){let o=K(s.eid),i=this.mem.ents.get(o);if(!i||vs(s,i))this.mem.put(s)}return this.warmed.add(e),W("warmType done",{type:e,n:r?.length??0,ms:Math.round(performance.now()-t)}),0}beginWarm(e){if(this.warmed.has(e))return Promise.resolve(0);let t=this.warmP.get(e);if(t)return t;let r=this.warmType(e).finally(()=>{this.warmP.delete(e)});return this.warmP.set(e,r),r}ensureWarm(e){if(this.warmed.has(e))return;this.beginWarm(e).then((t)=>{if(t===0)this.emit(new Set([e]))})}async getRow(e){let t=K(e);if(this.mem.ents.has(t))return this.mem.getRow(e);let[r,n]=await this.durable.getRow(e);if(n!==0)return a(n);if(r){let s=this.mem.ents.get(t);if(!s||vs(r,s))this.mem.put(r)}return this.mem.getRow(e)}async getEnt(e){let[t,r]=await this.getRow(e);if(r!==0)return a(r);if(t===void 0||!Z(t))return f(void 0);return f(t)}async getEntities(e){if(this.warmed.has(e.type))return W("getEntities mem",{type:e.type}),this.mem.getEntities(e);if(this.inflight>0)return W("getEntities inflight-mem",{type:e.type}),this.ensureWarm(e.type),this.mem.getEntities(e);W("getEntities beginWarm",{type:e.type});let t=await this.beginWarm(e.type);if(t!==0)return a(t);return W("getEntities afterWarm",{type:e.type}),this.mem.getEntities(e)}async countEntities({type:e}){if(this.warmed.has(e))return this.mem.countEntities({type:e});if(this.inflight>0)return this.ensureWarm(e),this.mem.countEntities({type:e});let t=await this.beginWarm(e);if(t!==0)return a(t);return this.mem.countEntities({type:e})}async checksum(e){return this.durable.checksum(e)}}function xu(e,t){if(Z(e)!==Z(t))return!1;if(e.ctr!==t.ctr)return!1;if(e.updatedAt.getTime()!==t.updatedAt.getTime())return!1;if(!G(e.eid,t.eid))return!1;if(!Z(e)||!Z(t))return!0;if(e.createdAt.getTime()!==t.createdAt.getTime())return!1;if(e.type!==t.type)return!1;if(!Eu(e.pid,t.pid))return!1;if(!Pu(e.tags,t.tags))return!1;return Au(e.body,t.body)}function Pu(e,t){if(e===t)return!0;if(e===void 0||t===void 0)return!1;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Eu(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;return G(e,t)}function Au(e,t){if(Object.is(e,t))return!0;if(e instanceof Uint8Array&&t instanceof Uint8Array)return G(e,t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();return wi(e,t)}function vs(e,t){let r=e.updatedAt.getTime(),n=t.updatedAt.getTime();if(r!==n)return r>n;return e.ctr>t.ctr}function ba(e){if(e===void 0)return;return{t:e.updatedAt.getTime(),ctr:e.ctr}}function ku(e,t){if(e===void 0||t===void 0)return e===t;return e.t===t.t&&e.ctr===t.ctr}function Du(e,t){let r=new Set,n=[];for(let s of t){let o=K(s.eid),i=e.ents.get(o),[c,u]=Pt(i,s);if(u!==0){n.push(u);continue}if(c===void 0){n.push(12);continue}for(let d of Et(i,c))r.add(d);e.put(c),n.push(0)}return{stats:n,types:r}}D();tr();function Bu(e){return"close"in e&&typeof e.close==="function"}class Ms{client;store;entDB;boundLabel="";post;whenReady;resolveReady;rejectReady;constructor(e){this.post=e,this.whenReady=new Promise((t,r)=>{this.resolveReady=t,this.rejectReady=r})}async bindStores(e){if(this.client!==void 0)return;try{let t=await fa(Dt,e.data),r=await Ia({cache:!1,name:e.ents}),n=new Dr(r.apply,()=>r.clear(),(i)=>{if(i.length<1)return;this.post({kind:"dirty",eids:i.map((c)=>c.slice())})}),s=n.clear;n.clear=async()=>{let i=await s();if(i===0)this.post({kind:"wiped"});return i};let o=new Qn(new tn,n,t,Ko,Dt);this.client=o,this.store=t,this.entDB=r,this.boundLabel=e.label,o.clientState.listen(()=>{this.emitClientState()}),o.xferState.listen(()=>{this.emitXferState()}),await this.emitXferState(),this.post({kind:"ready"}),this.markReady()}catch(t){let r=t instanceof Error?t:Error(String(t));throw this.post({kind:"initError",message:r.message}),this.failReady(r),r}}markReady(){let e=this.resolveReady;if(this.resolveReady=void 0,this.rejectReady=void 0,e)e()}failReady(e){let t=this.rejectReady;if(this.resolveReady=void 0,this.rejectReady=void 0,t)t(e)}requireClient(){if(!this.client)throw Error("WorkerRuntime not initialized");return this.client}async emitClientState(){let e=this.client;if(!e)return;let t=await e.clientState.get();this.post({kind:"clientState",connected:t.connected})}async emitXferState(){let e=this.client;if(!e)return;let t=await e.xferState.get();this.post({kind:"xferState",state:t})}hostFromSerialized(e){return{handle:new URL(e.handle),label:e.label,idx:e.idx}}async handle(e){if(e.op==="bind"){await this.bindStores(e);return}await this.whenReady;let t=this.requireClient();switch(e.op){case"ping":return"pong";case"setSeed":{let[r,n]=ye.fromBytes(e.seed);if(e.seed.fill(0),n!==0)throw new Pe(n);let s=await t.adopt(r,this.boundLabel);if(s!==0)throw new Pe(s);return}case"link":{await t.link(this.hostFromSerialized(e.host),e.connect??!0);return}case"unlink":{await t.unlink(e.label);return}case"connect":{await t.connect(e.listen??!0,e.sync??!0);return}case"disconnect":{await t.disconnect();return}case"sync":return await t.sync();case"rebuild":return await t.rebuild({checkHost:e.checkHost??!0});case"reconcile":{let[r,n]=await t.reconcile(e.hostLabel,{pull:e.pull,push:e.push,sync:e.sync});if(n!==0)throw new Pe(n);if(!r)throw new Pe(12);return r}case"msgcheck":return await t.msgcheck();case"entcheck":{let r=this.entDB;if(!r)throw new Pe(12);let[n,s]=await r.checksum(Dt);if(s!==0)throw new Pe(s);if(!n)throw new Pe(12);return n}case"wipe":{if(await t.wipe({msgs:e.msgs,ents:e.ents,meta:e.meta,seed:e.seed}),e.seed===!0){this.store?.close();let r=this.entDB;if(r!==void 0&&Bu(r))r.close()}return}case"import":{let r=e.bytes.slice(),n=new Blob([r]),s=new File([n],"import.dip");return await t.import(s)}case"export":{let[r,n]=await t.exportBytes();if(n!==0)throw new Pe(n);if(!r)throw new Pe(12);return r}case"getXferState":return await t.xferState.get();default:{let r=e;throw Error("unknown worker command")}}}}class Pe extends Error{status;constructor(e){super(`WorkerStatusError: ${A[e]}`);this.status=e;this.name="WorkerStatusError"}}function Jr(e,t){return{kind:"reply",id:e,ok:!0,result:t}}function Cs(e,t){return{kind:"reply",id:e,ok:!1,status:t}}var Je=globalThis,vu=new Ms((e,t)=>{if(t&&t.length>0)Je.postMessage(e,t);else Je.postMessage(e)});Je.onmessage=(e)=>{let t=e.data;if(!Ts(t))return;Mu(t)};async function Mu(e){try{let t=await vu.handle(e);if((e.op==="export"||e.op==="msgcheck"||e.op==="entcheck")&&t instanceof Uint8Array){let r=t.slice();Je.postMessage(Jr(e.id,r),[r.buffer]);return}if(e.op==="reconcile"&&t&&typeof t==="object"&&"msgcheck"in t&&t.msgcheck instanceof Uint8Array){let r=t.msgcheck.slice(),n={...t,msgcheck:r};Je.postMessage(Jr(e.id,n),[r.buffer]);return}Je.postMessage(Jr(e.id,t))}catch(t){if(t instanceof Pe){Je.postMessage(Cs(e.id,t.status));return}console.error("worker command failed",t),Je.postMessage(Cs(e.id,12))}}
|