ulda-auth 1.0.1 → 1.1.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.
@@ -1,2 +1,2 @@
1
1
  /*! ULDA Auth: SDK and dependency licenses in THIRD_PARTY_LICENSES.md. */
2
- var oi=Object.defineProperty;var ai=(s,e)=>{for(var t in e)oi(s,t,{get:e[t],enumerable:!0})};var Qt=Object.freeze({INVALID_INPUT:"Invalid input.",INVALID_PACKET:"Invalid protocol packet.",UNSUPPORTED_PROFILE:"Unsupported resource profile.",CRYPTO_FAILED:"Cannot authenticate or decrypt resource.",CLOSED:"Client is closed.",OFFLINE:"Transport is not ready.",NOT_OPEN:"Open a master first.",UNKNOWN_OUTCOME:"The request may have committed. Automatic replay is disabled.",CONFLICT:"Resource changed. Refresh before applying the intention again.",NOT_FOUND:"Resource does not exist.",EXISTS:"Name already exists.",NEEDS_RESYNC:"Refresh is required before further writes.",ROLLBACK:"Older or inconsistent state rejected.",LIMIT:"SDK limit exceeded.",UNSUPPORTED:"Operation requires an agreed protocol extension.",SERVER_ERROR:"Server rejected the request.",STALE_REFERENCE:"Reference belongs to an old context.",BUSY:"An operation is still running.",TIMEOUT:"Operation timed out."}),S=class extends Error{constructor(e){let t=typeof e=="string"&&Object.hasOwn(Qt,e)?e:"SERVER_ERROR";super(Qt[t]),this.name="UldaError",this.code=t}},q=s=>{throw new S(s)},c=(s,e="INVALID_INPUT")=>{s||q(e)},z=s=>s instanceof S?s:new S("SERVER_ERROR");var N=Object.freeze({jsonBytes:1048576,payloadBytes:11e5,messageBytes:8388608,incoming:8,batch:64,resources:64,queue:128,depth:48,nodes:4e4}),Z=s=>new TextEncoder().encode(s),v=(s,e)=>s.length===e.length&&s.every((t,i)=>t===e[i]);function we(...s){let e=new Uint8Array(s.reduce((i,r)=>i+r.length,0)),t=0;for(let i of s)e.set(i,t),t+=i.length;return e}var Oe=s=>globalThis.crypto.getRandomValues(new Uint8Array(s));function F(s,e=N.payloadBytes){let t;return s instanceof ArrayBuffer?t=new Uint8Array(s):s instanceof Uint8Array&&s.buffer instanceof ArrayBuffer?t=new Uint8Array(s.buffer,s.byteOffset,s.byteLength):c(!1,"INVALID_PACKET"),c(t.byteLength>0&&t.byteLength<=e,"INVALID_PACKET"),t}function Xe(s){let e="";for(let t=0;t<s.length;t+=8192)e+=String.fromCharCode(...s.subarray(t,t+8192));return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function re(s,e=N.payloadBytes){c(typeof s=="string"&&s.length>0&&s.length<=Math.ceil(e*4/3)&&/^[A-Za-z0-9_-]+$/.test(s)&&s.length%4!==1,"INVALID_PACKET");let t;try{t=Uint8Array.from(atob(s.replaceAll("-","+").replaceAll("_","/")),i=>i.charCodeAt(0))}catch{c(!1,"INVALID_PACKET")}return c(t.length<=e&&Xe(t)===s,"INVALID_PACKET"),t}function V(s){return c(typeof s=="string"&&/^[1-9][0-9]{0,39}$/.test(s)),s}function de(s){return c(typeof s=="string"&&s.length>0&&s.length<=256),s}function B(s,e){c(s!==null&&typeof s=="object"&&!Array.isArray(s),"INVALID_PACKET"),c(Object.keys(s).length===e.length&&e.every(t=>Object.hasOwn(s,t)),"INVALID_PACKET")}function R(s){let e=new Set,t=0,i=0;function r(a,o){if(c(++t<=N.nodes&&o<=N.depth,"LIMIT"),typeof a=="string")return i+=a.length,c(i<=N.jsonBytes,"LIMIT"),a;if(a===null||typeof a=="boolean")return a;if(typeof a=="number")return c(Number.isFinite(a)),a;c(a&&typeof a=="object"&&!e.has(a));let h=Array.isArray(a),l=Object.getPrototypeOf(a);c(h?l===Array.prototype:l===Object.prototype||l===null),e.add(a);let d=h?[]:Object.create(null),f=Reflect.ownKeys(a).filter(u=>!(h&&u==="length"));h&&c(f.length===a.length&&a.length<=N.nodes);for(let u of f){c(typeof u=="string"),i+=u.length,c(i<=N.jsonBytes,"LIMIT"),h&&c(/^(0|[1-9][0-9]*)$/.test(u)&&Number(u)<a.length);let y=Object.getOwnPropertyDescriptor(a,u);c(y.enumerable&&Object.hasOwn(y,"value")),Object.defineProperty(d,u,{value:r(y.value,o+1),enumerable:!0,writable:!0,configurable:!0})}return e.delete(a),d}let n=r(s,0);return c(Z(JSON.stringify(n)).length<=N.jsonBytes,"LIMIT"),n}function yt(s,e){let t=s;for(let i of e)c(t!==null&&typeof t=="object"&&Object.hasOwn(t,i),"NOT_FOUND"),t=t[i];return t}function _t(s,e,t,i=!1){if(c(Array.isArray(e)&&e.length<=N.depth&&e.every(o=>typeof o=="string"||Number.isSafeInteger(o))),!e.length)return c(!i,"UNSUPPORTED"),R(t);let r=R(s),n=yt(r,e.slice(0,-1)),a=String(e.at(-1));return c(n!==null&&typeof n=="object"),Array.isArray(n)&&c(/^(0|[1-9][0-9]*)$/.test(a)&&Number(a)<n.length),i?(c(Object.hasOwn(n,a),"NOT_FOUND"),Array.isArray(n)?n.splice(Number(a),1):delete n[a]):Object.defineProperty(n,a,{value:R(t),enumerable:!0,writable:!0,configurable:!0}),r}function At(s){return[...s].map(e=>e.toString(16).padStart(2,"0")).join("")}function Ze(s){return Uint8Array.from(s.match(/../g).map(e=>parseInt(e,16)))}function rs(s){return btoa(String.fromCharCode(...s))}function Qe(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function ns(s){return/^[0-9a-f]+$/i.test(s)&&s.length%2===0?Ze(s):Qe(s)}function wt(s){let e=typeof s=="bigint"?s:BigInt(s);if(e===0n)return Uint8Array.of(0);let t=[];for(;e>0n;)t.unshift(Number(e&0xffn)),e>>=8n;return Uint8Array.from(t)}function Te(...s){let e=new Uint8Array(s.reduce((i,r)=>i+r.length,0)),t=0;return s.forEach(i=>(e.set(i,t),t+=i.length)),e}function ci(s,e){return s.length===e.length&&s.every((t,i)=>t===e[i])}function ke(s,e){return({base64:rs,bytes:t=>t,hex:At}[e]??At)(s)}function Ie(s,e){return s instanceof Uint8Array?s:({hex:Ze,base64:Qe}[e]??ns)(s)}var O=Object.freeze({ULDA_FORMAT_SENTINEL:"ULDA_FORMAT_SENTINEL",ULDA_FORMAT_HEADER:"ULDA_FORMAT_HEADER",ULDA_FORMAT_SIZE:"ULDA_FORMAT_SIZE",ULDA_FORMAT_BODY_DIVISION:"ULDA_FORMAT_BODY_DIVISION",ULDA_FORMAT_UNKNOWN_MODE:"ULDA_FORMAT_UNKNOWN_MODE",ULDA_FORMAT_UNKNOWN_ALGORITHM:"ULDA_FORMAT_UNKNOWN_ALGORITHM",ULDA_HASHER_NOT_REGISTERED:"ULDA_HASHER_NOT_REGISTERED",ULDA_HASHER_OUTPUT_UNSUPPORTED:"ULDA_HASHER_OUTPUT_UNSUPPORTED",ULDA_HASHER_SIZE_MISMATCH:"ULDA_HASHER_SIZE_MISMATCH",ULDA_MODE_UNSUPPORTED:"ULDA_MODE_UNSUPPORTED",ULDA_MODE_EMPTY_BLOCKS:"ULDA_MODE_EMPTY_BLOCKS",ULDA_VERIFY_INCOMPATIBLE_PARAMS:"ULDA_VERIFY_INCOMPATIBLE_PARAMS",ULDA_VERIFY_INVALID_GAP:"ULDA_VERIFY_INVALID_GAP",ULDA_CONFIG_INVALID:"ULDA_CONFIG_INVALID",ULDA_RANDOM_UNAVAILABLE:"ULDA_RANDOM_UNAVAILABLE",ULDA_INTERNAL_ERROR:"ULDA_INTERNAL_ERROR"}),hi=new Set(["origin","blocks","sigBytes","bytes","raw","secret","privateKey","preimage"]);function di(s){if(s===null||typeof s!="object")return!1;let e=Object.getPrototypeOf(s);return e===Object.prototype||e===null}function Ot(s){if(Array.isArray(s))return s.map(t=>Ot(t));if(!di(s))return s;let e={};for(let[t,i]of Object.entries(s))hi.has(t)||(e[t]=Ot(i));return e}var x=class extends Error{constructor(s,e,t={}){super(e,{cause:t.cause}),this.name="UldaError",this.code=s,this.operation=t.operation,this.details=t.details,this.cause=t.cause}toLogObject(){return{name:this.name,code:this.code,message:this.message,operation:this.operation,details:Ot(this.details),causeName:this.cause?.name,causeMessage:this.cause?.message}}},os=0,as=0,U=Object.freeze({BACKUP_SIZE:128,N:64,ALGORITHM:32,AGE:16,BACKUP_DESCRIPTOR:8,MODE_X:4,FUTURE_MODE:2,BACKUP_ACTIVE:1}),j=Object.freeze({N:5,algorithm:2,mode:"S",age:0n}),Ge=3,cs=20;function D(s,e,t){return new x(s,e,{operation:"compactHeader",details:t})}function Et(s,e){if(!Number.isInteger(s)||s<0||s>255)throw D(O.ULDA_CONFIG_INVALID,`invalid ${e}`,{[e]:s})}function hs(s,e){if(!(s instanceof Uint8Array))throw D(O.ULDA_CONFIG_INVALID,`invalid ${e}`,{type:typeof s})}function Se(s,e,t){let i=0;for(let r=0;r<t;r++){let n=e+r,o=s[n>>>3]>>>7-(n&7)&1;i=i<<1|o}return i}function Ne(s,e,t,i){for(let r=0;r<t;r++){let n=t-1-r,a=i>>>n&1,o=e+r,h=o>>>3,l=1<<7-(o&7);a?s[h]|=l:s[h]&=~l}}function be(s,e){return Se(s,e,8)}function li(s,e,t){Ne(s,e,8,t)}function fi(s,e){if(typeof s!="bigint"||s<0n)throw D(O.ULDA_CONFIG_INVALID,"invalid age",{age:s});let t=1n<<BigInt(e*8);if(s>=t)throw D(O.ULDA_CONFIG_INVALID,"age does not fit",{ageBytes:e});let i=new Uint8Array(e),r=s;for(let n=e-1;n>=0;n--)i[n]=Number(r&0xffn),r>>=8n;return i}function ui(s){let e=0n;for(let t of s)e=e<<8n|BigInt(t);return e}function pi(s={}){let e=s.forceFields??{},t=0,i=[],r=s.N??j.N,n=s.algorithm??j.algorithm,a=s.mode??j.mode,o=s.age??j.age,h=s.ageBytes??4,l=s.backupActive===!0,d=s.backupDescriptor!==void 0&&s.backupDescriptor.length>0,f=s.backupSize!==void 0||e.backupSize===!0||d;if(a!=="S"&&a!=="X")throw D(O.ULDA_CONFIG_INVALID,"invalid mode",{mode:a});if(a==="X"&&(t|=U.MODE_X),l&&(t|=U.BACKUP_ACTIVE),(s.N!==void 0||e.N===!0)&&Et(r,"N"),(s.algorithm!==void 0||e.algorithm===!0)&&Et(n,"algorithm"),(s.age!==void 0||e.age===!0)&&h!==4&&h!==8)throw D(O.ULDA_CONFIG_INVALID,"invalid ageBytes",{ageBytes:h});s.backupDescriptor!==void 0&&hs(s.backupDescriptor,"backupDescriptor");let u=s.backupSize??s.backupDescriptor?.length??0;if(f&&Et(u,"backupSize"),d&&u!==s.backupDescriptor.length)throw D(O.ULDA_CONFIG_INVALID,"backupSize does not match backupDescriptor length",{backupSize:u,descriptorLength:s.backupDescriptor.length});f&&(t|=U.BACKUP_SIZE,i.push(u)),(s.N!==void 0&&r!==j.N||e.N===!0)&&(t|=U.N,i.push(r)),(s.algorithm!==void 0&&n!==j.algorithm||e.algorithm===!0)&&(t|=U.ALGORITHM,i.push(n)),(s.age!==void 0&&o!==j.age||e.age===!0)&&(t|=U.AGE,i.push(...fi(o,h))),d&&(t|=U.BACKUP_DESCRIPTOR,i.push(...s.backupDescriptor));let y=Ge+i.length;if(y>255)throw D(O.ULDA_FORMAT_SIZE,"compact header too large",{headerSize:y});let p=new Uint8Array(y);Ne(p,0,4,os),Ne(p,4,8,y),Ne(p,12,8,t);let m=cs;for(let g of i)li(p,m,g),m+=8;return Ne(p,m,4,as),p}function mi(s){if(hs(s,"input"),s.length<Ge)throw D(O.ULDA_FORMAT_SIZE,"compact header is too short",{inputLength:s.length});let e=Se(s,0,4);if(e!==os)throw D(O.ULDA_FORMAT_SENTINEL,"invalid compact header prefix",{prefix:e});let t=Se(s,4,8);if(t<Ge)throw D(O.ULDA_FORMAT_HEADER,"invalid compact header size",{headerSize:t});if(t>s.length)throw D(O.ULDA_FORMAT_SIZE,"compact header exceeds input length",{headerSize:t,inputLength:s.length});let i=Se(s,12,8),r={hasBackupSize:!!(i&U.BACKUP_SIZE),hasN:!!(i&U.N),hasAlgorithm:!!(i&U.ALGORITHM),hasAge:!!(i&U.AGE),hasBackupDescriptor:!!(i&U.BACKUP_DESCRIPTOR),modeX:!!(i&U.MODE_X),futureMode:!!(i&U.FUTURE_MODE),backupActive:!!(i&U.BACKUP_ACTIVE)};if(r.hasBackupDescriptor&&!r.hasBackupSize)throw D(O.ULDA_FORMAT_HEADER,"backup descriptor requires backupSize",{inclusive:i});let n=0;r.hasBackupSize&&(n+=1),r.hasN&&(n+=1),r.hasAlgorithm&&(n+=1);let a=cs,o=0;r.hasBackupSize&&(o=be(s,a),a+=8),r.hasBackupDescriptor&&(n+=o);let h=t-Ge,l=r.hasAge?h-n:0;if(r.hasAge&&l!==4&&l!==8)throw D(O.ULDA_FORMAT_HEADER,"unsupported compact header age length",{ageBytes:l});if(!r.hasAge&&h!==n)throw D(O.ULDA_FORMAT_HEADER,"invalid compact header optional field layout",{optionalByteCount:h,knownOptionalBytes:n});if(r.hasAge&&h!==n+l)throw D(O.ULDA_FORMAT_HEADER,"invalid compact header optional field layout",{optionalByteCount:h,knownOptionalBytes:n,ageBytes:l});let d=r.hasN?be(s,a):j.N;r.hasN&&(a+=8);let f=r.hasAlgorithm?be(s,a):j.algorithm;r.hasAlgorithm&&(a+=8);let u=j.age;if(r.hasAge){let m=new Uint8Array(l);for(let g=0;g<l;g++)m[g]=be(s,a),a+=8;u=ui(m)}let y=new Uint8Array(0);if(r.hasBackupDescriptor){y=new Uint8Array(o);for(let m=0;m<o;m++)y[m]=be(s,a),a+=8}let p=Se(s,a,4);if(p!==as)throw D(O.ULDA_FORMAT_SENTINEL,"invalid compact header suffix",{suffix:p});return{headerSize:t,inclusive:i,flags:r,N:d,algorithm:f,mode:r.modeX?"X":"S",age:u,ageBytes:l,backupSize:o,backupDescriptor:y,bodyOffset:t}}function es(s){let e=mi(s);return{header:e,body:s.slice(e.headerSize)}}var bt={mode:{S:1,X:2},algorithm:{"SHA-1":1,"SHA-256":2,"SHA-384":3,"SHA-512":4,"SHA3-256":5,"SHA3-512":6,BLAKE3:7,WHIRLPOOL:8,CUSTOM:255}},ds={mode:{1:"S",2:"X"},algorithm:Object.fromEntries(Object.entries(bt.algorithm).map(([s,e])=>[e,s]))};function gi(s={}){let e=s.encoder??bt,t=s.decoder??ds,i=s.getExportFormat??(()=>"hex"),r=s.getOriginSize??(()=>256),n=(u,y,p,m)=>{let g=new Uint8Array(5+m.length+1);return g.set([0,g.length,u,e.mode[y]??255,e.algorithm[p]??255]),g.set(m,5),g[g.length-1]=0,g},a=u=>{let y=Ie(u,i()),p=y[1];if(y[0]||y[p-1])throw new x(O.ULDA_FORMAT_SENTINEL,"sentinel",{operation:"decodeOrigin",details:{headerLength:p,actualSize:y.length}});let m=y[2],g=t.mode[y[3]]??"U",E=t.algorithm[y[4]]??"UNK",_=0n;for(let T=5;T<p-1;T++)_=_<<8n|BigInt(y[T]);let w=y.slice(p),b=w.length/m;if(!Number.isInteger(b))throw new x(O.ULDA_FORMAT_BODY_DIVISION,"div",{operation:"decodeOrigin",details:{N:m,bodyLength:w.length,blkLen:b}});let I=[];for(let T=0;T<m;T++)I.push(w.slice(T*b,(T+1)*b));return{bytes:y,N:m,mode:g,alg:E,index:_,blockLen:b,origin:I}},o=u=>{let y=Ie(u,i()),p=y[1],m=y[2],g=t.mode[y[3]]??"U",E=t.algorithm[y[4]]??"UNK",_=0n;for(let L=5;L<p-1;L++)_=_<<8n|BigInt(y[L]);let w=y.slice(p),b=(r()??256)>>>3,I=w.length-b,T=I/(m-1);if(I<0||!Number.isInteger(T))throw new x(O.ULDA_FORMAT_SIZE,"SigImporter sizes",{operation:"decodeWitness",details:{N:m,originLen:b,sigLength:w.length,rest:I,blkLen:T}});let he=[w.slice(0,b)];for(let L=0;L<m-1;L++)he.push(w.slice(b+L*T,b+(L+1)*T));return{bytes:y,N:m,mode:g,alg:E,index:_,sigBytes:w,originLen:b,blkLen:T,blocks:he}},h=(u,y=0n,p={})=>{let m=p.N??u.origin?.length??5,g=p.mode??"S",E=p.hash??p.alg??"SHA-256",_=n(m,g,E,wt(y));return ke(Te(_,...u.origin),i())},l=(u,y)=>{let p=y.hash??y.alg,m=n(y.N,y.mode,p,wt(y.index));return ke(Te(m,u),i())};return{makeHeader:n,decodeOrigin:a,decodeWitness:o,encodeOrigin:h,encodeWitness:l,packWitness:(u,y)=>l(u,y),splitWitnessBlocks:u=>u.blocks??(()=>{let{originLen:y,blkLen:p,sigBytes:m,N:g}=u,E=[m.slice(0,y)];for(let _=0;_<g-1;_++)E.push(m.slice(y+_*p,y+(_+1)*p));return E})()}}var ls=Object.freeze({exportFormat:"hex",originSize:256,N:5,mode:"S",algorithm:"SHA-256"}),St=4,yi=0xffffffffn;function Le(s,e,t){return new x(s,e,{operation:"compactV1",details:t})}function _i(s={}){return{...ls,...s}}function Ei(s){if(s!=="S"&&s!=="X")throw Le(O.ULDA_CONFIG_INVALID,"invalid mode",{mode:s})}function ts(s,e){let t=s.algorithm[e];if(!Number.isInteger(t)||t<0||t>255)throw Le(O.ULDA_CONFIG_INVALID,"invalid algorithm",{algorithm:e});return t}function Ai(s){if(s.ageBytes!==void 0&&s.ageBytes!==St)throw Le(O.ULDA_CONFIG_INVALID,"compactV1 ageBytes must be 4",{ageBytes:s.ageBytes})}function wi(s){if(typeof s=="bigint"&&s>yi)throw Le(O.ULDA_CONFIG_INVALID,"compactV1 age does not fit uint32",{age:s})}function ss(s){if(s.flags.hasAge&&s.ageBytes!==St)throw Le(O.ULDA_FORMAT_HEADER,"compactV1 age must be 4 bytes",{ageBytes:s.ageBytes})}function Oi(s={}){let e=s.encoder??bt,t=s.decoder??ds,i=_i(s.defaults),r=s.getExportFormat??(()=>i.exportFormat),n=s.getOriginSize??(()=>i.originSize),a=ts(e,i.algorithm),o=(g={})=>{let E=g.N??i.N,_=g.mode??i.mode,w=g.hash??g.alg??g.algorithm??i.algorithm,b=ts(e,w),I=g.index??g.age??0n;return Ei(_),Ai(g),wi(I),pi({N:E,algorithm:b,mode:_,age:I,ageBytes:St,backupActive:g.backupActive,backupSize:g.backupSize,backupDescriptor:g.backupDescriptor,forceFields:{...g.forceFields,algorithm:g.forceFields?.algorithm??b!==a}})},h=g=>{let E=Ie(g,r()),_=es(E).header;return ss(_),_},l=g=>{let E=Ie(g,r()),{header:_,body:w}=es(E);return ss(_),{bytes:E,header:_,body:w}},d=(g,E=0n,_={})=>{let w=o({..._,index:E,N:_.N??g.origin?.length??i.N});return ke(Te(w,...g.origin),r())},f=g=>{let{bytes:E,header:_,body:w}=l(g),b=_.N,I=_.mode,T=t.algorithm[_.algorithm]??"UNK",he=_.age,L=w.length/b;if(!Number.isInteger(L))throw new x(O.ULDA_FORMAT_BODY_DIVISION,"div",{operation:"decodeOrigin",details:{N:b,bodyLength:w.length,blockLen:L}});let ie=[];for(let J=0;J<b;J++)ie.push(w.slice(J*L,(J+1)*L));return{bytes:E,N:b,mode:I,alg:T,index:he,blockLen:L,origin:ie,header:_,body:w}},u=g=>g.blocks??(()=>{let{originLen:E,blkLen:_,sigBytes:w,N:b}=g,I=[w.slice(0,E)];for(let T=0;T<b-1;T++)I.push(w.slice(E+T*_,E+(T+1)*_));return I})(),y=(g,E={})=>{let _=o(E);return ke(Te(_,g),r())};return{encodeHeader:o,decodeHeader:h,encodeOrigin:d,decodeOrigin:f,encodeWitness:y,decodeWitness:g=>{let{bytes:E,header:_,body:w}=l(g),b=_.N,I=_.mode,T=t.algorithm[_.algorithm]??"UNK",he=_.age,L=w,ie=(n()??ls.originSize)>>>3,J=L.length-ie,We=J/(b-1);if(J<0||!Number.isInteger(We))throw new x(O.ULDA_FORMAT_SIZE,"SigImporter sizes",{operation:"decodeWitness",details:{N:b,originLen:ie,sigLength:L.length,rest:J,blkLen:We}});let ni=u({originLen:ie,blkLen:We,sigBytes:L,N:b});return{bytes:E,N:b,mode:I,alg:T,index:he,sigBytes:L,originLen:ie,blkLen:We,blocks:ni,header:_,body:w}},packWitness:(g,E)=>y(g,E),splitWitnessBlocks:u}}var Y=Object.freeze({SIMPLE_SIG:"simpleSig",V1:"v1",COMPACT_V1:"compactV1"});function bi(s){if(s==null)return Y.COMPACT_V1;if(s===Y.SIMPLE_SIG||s===Y.V1)return Y.SIMPLE_SIG;if(s===Y.COMPACT_V1||s==="compact")return Y.COMPACT_V1;throw new x(O.ULDA_CONFIG_INVALID,"unknown codec pack",{operation:"normalizeCodecPack",details:{pack:s}})}function Si(s={}){let{pack:e,encoder:t,decoder:i,getExportFormat:r,getOriginSize:n}=s,a=bi(e);return a===Y.COMPACT_V1?{id:a,codec:Oi({encoder:t,decoder:i,getExportFormat:r,getOriginSize:n})}:{id:Y.SIMPLE_SIG,codec:gi({encoder:t,decoder:i,getExportFormat:r,getOriginSize:n})}}var Ni="1",Ti="hex",le=Object.freeze({N:5,mode:"S",hash:"SHA-256",originSize:256,pack:"compactV1",ageBytes:4}),is=Object.freeze({mode:Object.freeze({S:1,X:2}),algorithm:Object.freeze({"SHA-1":1,"SHA-256":2,"SHA-384":3,"SHA-512":4,"SHA3-256":5,"SHA3-512":6,BLAKE3:7,WHIRLPOOL:8,CUSTOM:255})});function ki(){return{mode:{...is.mode},algorithm:{...is.algorithm}}}function Ii(s){return{mode:Object.fromEntries(Object.entries(s.mode).map(([e,t])=>[t,e])),algorithm:Object.fromEntries(Object.entries(s.algorithm).map(([e,t])=>[t,e]))}}function Li(s={}){let e=s?.sign?.ageBytes??le.ageBytes;if(e!==4)throw new x(O.ULDA_CONFIG_INVALID,"invalid ageBytes",{operation:"normalizeConfig",details:{ageBytes:e}});return{version:s.version??Ni,fmt:{export:s?.fmt?.export??Ti},sign:{N:s?.sign?.N??le.N,mode:s?.sign?.mode??le.mode,hash:s?.sign?.hash??le.hash,originSize:s?.sign?.originSize??le.originSize,pack:s?.sign?.pack??le.pack,ageBytes:e},externalHashers:s.externalHashers??{}}}function Ci(s){let{cfg:e,config:t,encoder:i,decoder:r}=s,n=e.sign??{};if(typeof n.func!="function")return;let a=n.hash??"CUSTOM";return n.hash||(t.sign.hash=a),t.externalHashers[a]={fn:n.func,output:n.output??"bytes",size:n.originSize??null,cdn:n.cdn??null,ready:!0},a in i.algorithm||(i.algorithm[a]=255),i.algorithm[a]===255&&(r.algorithm[255]=a),{id:a}}var Di=Object.freeze(["SHA-1","SHA-256","SHA-384","SHA-512"]);function Ri(s={}){let{externalHashers:e={},loadScriptOnce:t,cryptoImpl:i=globalThis.crypto}=s,r=async(a,o="SHA-256")=>{if(Di.includes(o))return new Uint8Array(await i.subtle.digest(o,a));let h=e[o];if(!h)throw new x(O.ULDA_HASHER_NOT_REGISTERED,`Hasher <${o}> not registered`,{operation:"hash",details:{hash:o}});h.cdn&&!h.ready&&(await t(h.cdn),h.ready=!0);let l=await h.fn(a),d=h.output??"bytes",f=d==="bytes"?l:d==="hex"?Ze(l):d==="base64"?Qe(l):(()=>{throw new x(O.ULDA_HASHER_OUTPUT_UNSUPPORTED,`Unsupported output ${d}`,{operation:"hash",details:{hash:o,output:d}})})();if(h.size&&f.length*8!==h.size)throw new x(O.ULDA_HASHER_SIZE_MISMATCH,`Hasher <${o}> size mismatch`,{operation:"hash",details:{hash:o,expectedSize:h.size,actualSize:f.length*8}});return f};return{hash:r,hashIter:async(a,o,h="SHA-256")=>{let l=a;for(let d=0;d<o;d++)l=await r(l,h);return l}}}function vi(s={}){let{cryptoImpl:e=globalThis.crypto}=s;return{randomBytes:i=>{if(!e||typeof e.getRandomValues!="function")throw new x(O.ULDA_RANDOM_UNAVAILABLE,"Random source unavailable",{operation:"randomBytes",details:{requestedLength:i}});return e.getRandomValues(new Uint8Array(i))}}}var $e={id:"S",ladder:async(s,e)=>{let t=[];for(let i=0;i<s.length;i++)t.push(await e.hashIter(s[i],i,e.alg));return{sigBlocks:t,final:t.at(-1)}},verify:async(s,e,t)=>{let i=e.index-s.index;if(i<=0n||i>=BigInt(s.N))return!1;let r=Number(i);if(s.originLen!==e.originLen||s.blkLen!==e.blkLen)return!1;let n=t.splitWitnessBlocks(s),a=t.splitWitnessBlocks(e);for(let o=0;o<s.N-r;o++)if(!t.equalBytes(await t.hashIter(a[o],r,s.alg),n[o+r]))return!1;return!0}},Je={id:"X",ladder:async(s,e)=>{if(!s?.length)throw new x(O.ULDA_MODE_EMPTY_BLOCKS,"_ladderX: empty blocks",{operation:"ladderX",details:{mode:"X"}});let t=[s[0]],i=s;for(let r=1;r<s.length;r++){let n=[];for(let a=0;a<i.length-1;a++)n.push(await e.hash(e.concatBytes(i[a],i[a+1]),e.alg));t.push(n[0]),i=n}return{sigBlocks:t,final:t.at(-1)}},verify:async(s,e,t)=>{if(e.index-s.index!==1n)return!1;let{N:i}=s;if(s.sigBytes.length!==e.sigBytes.length||s.sigBytes.length%i)return!1;let r=t.splitWitnessBlocks(s),n=t.splitWitnessBlocks(e);for(let a=1;a<i;a++)if(!t.equalBytes(await t.hash(t.concatBytes(r[a-1],n[a-1]),s.alg),r[a]))return!1;return!0}},Ar=Object.freeze({S:$e,X:Je});function Bi(s){let{N:e,originSize:t,randomBytes:i}=s,r=t>>>3;return{origin:Array.from({length:e},()=>i(r))}}async function Ui(s,e){let{modes:t,hash:i,hashIter:r,concatBytes:n}=e,a=s.mode==="X"?t.X:t.S,{sigBlocks:o}=await a.ladder(s.origin,{hash:i,hashIter:r,concatBytes:n,alg:s.alg});return{sigBytes:n(...o),sigBlocks:o,index:s.index,N:s.N,mode:s.mode,alg:s.alg}}function xi(s,e){let{randomBytes:t}=e,i=s.origin.slice(1);return i.push(t(s.blockLen)),{origin:i,index:s.index+1n}}async function Pi(s,e,t){let{modes:i,hash:r,hashIter:n,concatBytes:a,equalBytes:o,splitWitnessBlocks:h}=t;if(s.N!==e.N||s.mode!==e.mode||s.alg!==e.alg||e.index<=s.index)return!1;let l={hash:r,hashIter:n,concatBytes:a,equalBytes:o,splitWitnessBlocks:h};return s.mode==="S"?i.S.verify(s,e,l):s.mode==="X"?i.X.verify(s,e,l):!1}function Fi(s){let{config:e,codec:t,modes:i,hash:r,hashIter:n,randomBytes:a,concatBytes:o,equalBytes:h}=s,l=m=>a(m),d=()=>Bi({N:e.sign.N,originSize:e.sign.originSize,randomBytes:l});return{randomBlock:l,originGenerator:d,newOriginPackage:(m=0n)=>t.encodeOrigin(d(),m,{N:e.sign.N,mode:e.sign.mode,hash:e.sign.hash,ageBytes:e.sign.ageBytes}),stepUpPackage:m=>{let g=t.decodeOrigin(m),E=xi(g,{randomBytes:l});return t.encodeOrigin({origin:E.origin},E.index,{N:e.sign.N,mode:e.sign.mode,hash:e.sign.hash,ageBytes:e.sign.ageBytes})},signPackage:async m=>{let g=t.decodeOrigin(m),E=await Ui(g,{modes:i,hash:r,hashIter:n,concatBytes:o});return t.packWitness(E.sigBytes,{index:E.index,N:E.N,mode:E.mode,alg:E.alg,ageBytes:e.sign.ageBytes})},verifyPackages:async(m,g)=>{let E=t.decodeWitness(m),_=t.decodeWitness(g);return Pi(E,_,{modes:i,hash:r,hashIter:n,concatBytes:o,equalBytes:h,splitWitnessBlocks:t.splitWitnessBlocks})}}}var Mi=class fs{constructor(e={}){let t=this.globalConfig=Li(e);this.externalHashers=t.externalHashers,this.encoder=ki(),this.decoder=Ii(this.encoder),Ci({cfg:e,config:t,encoder:this.encoder,decoder:this.decoder});let i=Si({pack:t.sign.pack,encoder:this.encoder,decoder:this.decoder,getExportFormat:()=>t.fmt.export,getOriginSize:()=>t.sign.originSize});this.codecPack=i.id;let r=this.codec=i.codec,n=this.convert={bytesToHex:At,hexToBytes:Ze,bytesToBase64:rs,base64ToBytes:Qe,guessToBytes:ns,indexToBytes:wt,concatBytes:Te,equalBytes:ci,export:d=>ke(d,t.fmt.export),importToBytes:d=>Ie(d,t.fmt.export),splitSig:d=>r.splitWitnessBlocks(d)},a=this.hashProvider=Ri({externalHashers:t.externalHashers,loadScriptOnce:fs.loadScriptOnce,cryptoImpl:globalThis.crypto}),o=this.randomProvider=vi({cryptoImpl:globalThis.crypto}),h=this.enc={hash:a.hash,hashIter:a.hashIter,ladder:async(d,f="S",u="SHA-256")=>f==="X"?h._ladderX(d,u):h._ladderS(d,u),_ladderS:async(d,f)=>$e.ladder(d,{hashIter:h.hashIter,alg:f}),_ladderX:async(d,f="SHA-256")=>Je.ladder(d,{hash:h.hash,concatBytes:n.concatBytes,alg:f})},l=this.operations=Fi({config:t,codec:r,modes:{S:$e,X:Je},hash:h.hash,hashIter:h.hashIter,randomBytes:d=>o.randomBytes(d),concatBytes:n.concatBytes,equalBytes:n.equalBytes});this.actions={Sign:d=>l.signPackage(d),VerifyS:async(d,f)=>$e.verify(d,f,{hashIter:h.hashIter,equalBytes:n.equalBytes,splitWitnessBlocks:n.splitSig}),VerifyX:async(d,f)=>Je.verify(d,f,{hash:h.hash,concatBytes:n.concatBytes,equalBytes:n.equalBytes,splitWitnessBlocks:n.splitSig}),Verify:(d,f)=>l.verifyPackages(d,f),import:{signature:d=>r.decodeWitness(d),origin:d=>r.decodeOrigin(d)},OriginGenerator:()=>l.originGenerator(),RandomBlock:d=>l.randomBlock(d),_hdr:(d,f,u,y)=>{if(typeof r.makeHeader=="function")return r.makeHeader(d,f,u,y);throw new x(O.ULDA_CONFIG_INVALID,"Legacy v1 header is not available for compactV1",{operation:"actions._hdr",details:{pack:this.codecPack}})},NewExporter:(d,f=0n)=>{let{N:u,mode:y,hash:p}=t.sign;return r.encodeOrigin(d,f,{N:u,mode:y,hash:p,ageBytes:t.sign.ageBytes})},SignExporter:(d,f,u,y,p)=>r.encodeWitness(d,{index:f,N:u,mode:y,hash:p,ageBytes:t.sign.ageBytes}),PackSignature:(d,f)=>r.packWitness(d,f),StepUp:d=>l.stepUpPackage(d)}}static loadScriptOnce(e){return new Promise((t,i)=>{if(document.querySelector(`script[src="${e}"]`))return t();let r=document.createElement("script");r.src=e,r.onload=t,r.onerror=i,document.head.appendChild(r)})}New(e=0n){return this.operations.newOriginPackage(e)}stepUp(e){return this.operations.stepUpPackage(e)}sign(e){return this.operations.signPackage(e)}verify(e,t){return this.operations.verifyPackages(e,t)}},us=Mi;var fe=Object.fromEntries(["X","S"].map(s=>[s,new us({fmt:{export:"bytes"},sign:{mode:s,N:5,hash:"SHA-256",originSize:256,pack:"compactV1"}})]));function M(s){try{c(s instanceof Uint8Array&&s.length>=163&&s.length<=167,"UNSUPPORTED_PROFILE");let e=fe.X.actions.import.signature(s);c(e.N===5&&e.alg==="SHA-256"&&(e.mode==="X"||e.mode==="S")&&e.body.length===160,"UNSUPPORTED_PROFILE");let t=fe[e.mode].codec.encodeWitness(e.body,{index:e.index,mode:e.mode,N:5,hash:"SHA-256"});return c(v(t,s),"UNSUPPORTED_PROFILE"),{mode:e.mode,age:Number(e.index),N:5}}catch{q("UNSUPPORTED_PROFILE")}}var Nt=s=>{let e=F(s,167);return{bytes:e,...M(e)}};function et(s="X"){return c(s==="X"||s==="S"),fe[s].New()}function tt(s){let e=M(s);return c(e.age<4294967295,"LIMIT"),fe[e.mode].stepUp(s)}async function Ce(s){let e=M(s);return fe[e.mode].sign(s)}async function st(s,e){let t=M(s),i=M(e);if(t.mode!==i.mode)return!1;try{return await fe[t.mode].verify(s,e)}catch{return!1}}var ps=new Uint8Array([85,76,68,2]),ms=Z("ULDA-SDK/container/v2\0"),Vi=Z("ULDA-SDK/content-key/v2"),Tt=new WeakMap,Hi=6e5;function ue(){return c(globalThis.crypto?.subtle&&globalThis.crypto?.getRandomValues,"UNSUPPORTED"),globalThis.crypto.subtle}function zi(s){return c(typeof s=="string"&&s.length>0&&s.length<=1024),Z(s)}async function Ki(s,e){let t=zi(s);s=void 0;try{let i=await ue().importKey("raw",t,"PBKDF2",!1,["deriveKey"]);return t.fill(0),await ue().deriveKey({name:"PBKDF2",hash:"SHA-256",iterations:Hi,salt:e},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(i){if(i instanceof S)throw i;q("CRYPTO_FAILED")}finally{t.fill(0)}}async function kt(s,e=Oe(16)){c(e instanceof Uint8Array&&e.length===16);let t=Ki(s,e);return s=void 0,{salt:e.slice(),key:await t}}async function De(s,e=Oe(16)){c(e instanceof Uint8Array&&e.length===16);let t=re(s,32);s=void 0;try{c(t.length===32);let i=await ue().importKey("raw",t,"HKDF",!1,["deriveKey"]);return t.fill(0),{salt:e.slice(),key:await ue().deriveKey({name:"HKDF",hash:"SHA-256",salt:e,info:Vi},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}}catch(i){if(i instanceof S)throw i;q("CRYPTO_FAILED")}finally{t.fill(0)}}function gs(){let s=Oe(32);try{return Xe(s)}finally{s.fill(0)}}function ys(s){let e=re(s,32);try{c(e.length===32)}finally{e.fill(0)}}var It=gs,it=gs;function Q(s){let e=F(s);return c(e.length>=48&&v(e.subarray(0,4),ps),"INVALID_PACKET"),{bytes:e,salt:e.slice(4,20),nonce:e.slice(20,32),ciphertext:e.subarray(32),header:e.subarray(0,20)}}async function Re(s,e,t,i){ys(e);let r=await Ce(t);c(s.salt instanceof Uint8Array&&s.salt.length===16);let n=we(ps,s.salt),a=Oe(12),o=Z(JSON.stringify({token:e,origin:Xe(t),data:R(i)}));try{c(o.length<=N.payloadBytes-48,"LIMIT");let h=new Uint8Array(await ue().encrypt({name:"AES-GCM",iv:a,additionalData:we(ms,n,r),tagLength:128},s.key,o)),l=Object.freeze(Object.create(null));return Tt.set(l,Object.freeze({witness:r,payload:we(n,a,h)})),l}catch(h){if(h?.code==="LIMIT")throw h;q("CRYPTO_FAILED")}finally{o.fill(0)}}function W(s){c(Tt.has(s),"INVALID_PACKET");let{witness:e,payload:t}=Tt.get(s);return Object.freeze({witness:e.slice(),payload:t.slice()})}async function _s(s,e,t){let i,r,n=!1;try{let a=F(e.witness,167);M(a);let o=Q(e.payload);c(v(o.salt,s.salt)),i=new Uint8Array(await ue().decrypt({name:"AES-GCM",iv:o.nonce,additionalData:we(ms,o.header,a),tagLength:128},s.key,o.ciphertext));let h=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i));B(h,["token","origin","data"]),ys(h.token),c(t===void 0||h.token===t),r=re(h.origin,167),M(r),c(v(await Ce(r),a));let l={origin:r,token:h.token,data:R(h.data),witness:a,record:Object.freeze({id:e.id,witness:e.witness,payload:e.payload}),...M(a)};return n=!0,l}catch{q("CRYPTO_FAILED")}finally{i?.fill(0),n||r?.fill(0)}}var Lt=new WeakMap,Ct=new WeakMap,qi=new Set(["hello","read","create","update","delete","session.close"]),rt=(s,e)=>{let t=Object.freeze(Object.create(null));return Lt.set(t,{action:s,body:e}),t};function pe(s){c(Array.isArray(s)&&s.length>0&&s.length<=N.batch,"INVALID_PACKET")}function ne(s){pe(s),s.forEach(V),c(new Set(s).size===s.length,"INVALID_PACKET")}function ve(s){let e=0;for(let t of s)e+=F(t?.witness,167).byteLength,Object.hasOwn(t,"payload")&&(e+=F(t.payload).byteLength),c(e<=N.messageBytes,"LIMIT")}function Dt(s){return c(s==="hello"||s==="session.close"),rt(s,{})}function me(s){return ne(s),rt("read",[...s])}function oe(s,e){c(s==="create"||s==="update"),pe(e),s==="update"&&ne(e.map(i=>i.id));let t=e.map(i=>s==="create"?{...W(i.sealed)}:{id:V(i.id),...W(i.sealed)});return rt(s,t)}async function Rt(s,e){V(s);let t=Object.freeze(Object.create(null)),i=tt(e);try{Ct.set(t,{id:s,witness:await Ce(i)})}finally{i.fill(0)}return t}function vt(s,e=[]){pe(s);let t=s.map(i=>(c(Ct.has(i),"INVALID_PACKET"),{...Ct.get(i)}));c(Array.isArray(e),"INVALID_PACKET");for(let i of e)t.push({id:V(i.id),...W(i.sealed)});return pe(t),ve(t),ne(t.map(i=>i.id)),rt("delete",t)}function Es(s){c(Lt.has(s),"INVALID_PACKET");let{action:e,body:t}=Lt.get(s);return{action:e,body:Array.isArray(t)?t.map(i=>typeof i=="string"?i:{...i.id===void 0?{}:{id:i.id},witness:F(i.witness,167).slice(),...i.payload===void 0?{}:{payload:F(i.payload).slice()}}):{}}}function As(s){return B(s,["id","witness","payload"]),V(s.id),Nt(s.witness),Q(s.payload),Object.freeze({id:s.id,witness:F(s.witness,167).slice(),payload:F(s.payload).slice()})}function ws(s,e){if(c(qi.has(s),"INVALID_PACKET"),s==="hello"||s==="session.close"){B(e,[]);return}if(s==="read"){ne(e);return}pe(e),s!=="delete"||c(e.some(t=>!Object.hasOwn(t,"payload")),"INVALID_PACKET"),ve(e),s!=="create"&&ne(e.map(t=>t.id)),e.forEach(t=>{B(t,s==="create"?["witness","payload"]:s==="update"?["id","witness","payload"]:Object.hasOwn(t,"payload")?["id","witness","payload"]:["id","witness"]),Nt(t.witness),(s!=="delete"||Object.hasOwn(t,"payload"))&&Q(t.payload)})}function Os(s,e,t){if(c(t&&typeof t=="object"&&!Array.isArray(t),"INVALID_PACKET"),t.ok===!1){B(t,Object.hasOwn(t,"id")?["ok","error","id"]:["ok","error"]),Object.hasOwn(t,"id")&&V(t.id);let i={conflict:"CONFLICT",not_found:"NOT_FOUND",too_large:"LIMIT",unsupported_profile:"UNSUPPORTED_PROFILE",invalid_witness:"CONFLICT"};q(typeof t.error=="string"&&Object.hasOwn(i,t.error)?i[t.error]:"SERVER_ERROR")}if(c(t.ok===!0,"INVALID_PACKET"),s==="read"||s==="create"){if(B(t,["ok","data"]),pe(t.data),c(t.data.length===e.length,"INVALID_PACKET"),s==="create")return ne(t.data),[...t.data];ve(t.data);let i=t.data.map(As);return ne(i.map(r=>r.id)),c(i.every(r=>e.includes(r.id)),"INVALID_PACKET"),i}B(t,["ok"])}function bs(s){c(s&&typeof s=="object","INVALID_PACKET"),B(s,["updated","deleted"].filter(a=>Object.hasOwn(s,a)));let e=s.updated??[],t=s.deleted??[];c(Array.isArray(e)&&Array.isArray(t)&&e.length+t.length<=N.batch,"INVALID_PACKET"),ve(e);let i=e.map(As),r=t.map(V),n=[...i.map(a=>a.id),...r];return c(n.length>0&&new Set(n).size===n.length,"INVALID_PACKET"),{updated:i,deleted:r}}var K=Object.create(null);K.open="0";K.close="1";K.ping="2";K.pong="3";K.message="4";K.upgrade="5";K.noop="6";var Be=Object.create(null);Object.keys(K).forEach(s=>{Be[K[s]]=s});var Ue={type:"error",data:"parser error"};var Ts=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",ks=typeof ArrayBuffer=="function",Is=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,xe=({type:s,data:e},t,i)=>Ts&&e instanceof Blob?t?i(e):Ss(e,i):ks&&(e instanceof ArrayBuffer||Is(e))?t?i(e):Ss(new Blob([e]),i):i(K[s]+(e||"")),Ss=(s,e)=>{let t=new FileReader;return t.onload=function(){let i=t.result.split(",")[1];e("b"+(i||""))},t.readAsDataURL(s)};function Ns(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}var Bt;function Ls(s,e){if(Ts&&s.data instanceof Blob)return s.data.arrayBuffer().then(Ns).then(e);if(ks&&(s.data instanceof ArrayBuffer||Is(s.data)))return e(Ns(s.data));xe(s,!1,t=>{Bt||(Bt=new TextEncoder),e(Bt.encode(t))})}var Cs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Pe=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<Cs.length;s++)Pe[Cs.charCodeAt(s)]=s;var Ds=s=>{let e=s.length*.75,t=s.length,i,r=0,n,a,o,h;s[s.length-1]==="="&&(e--,s[s.length-2]==="="&&e--);let l=new ArrayBuffer(e),d=new Uint8Array(l);for(i=0;i<t;i+=4)n=Pe[s.charCodeAt(i)],a=Pe[s.charCodeAt(i+1)],o=Pe[s.charCodeAt(i+2)],h=Pe[s.charCodeAt(i+3)],d[r++]=n<<2|a>>4,d[r++]=(a&15)<<4|o>>2,d[r++]=(o&3)<<6|h&63;return l};var ji=typeof ArrayBuffer=="function",Fe=(s,e)=>{if(typeof s!="string")return{type:"message",data:Rs(s,e)};let t=s.charAt(0);return t==="b"?{type:"message",data:Yi(s.substring(1),e)}:Be[t]?s.length>1?{type:Be[t],data:s.substring(1)}:{type:Be[t]}:Ue},Yi=(s,e)=>{if(ji){let t=Ds(s);return Rs(t,e)}else return{base64:!0,data:s}},Rs=(s,e)=>{switch(e){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}};var vs="",Bs=(s,e)=>{let t=s.length,i=new Array(t),r=0;s.forEach((n,a)=>{xe(n,!1,o=>{i[a]=o,++r===t&&e(i.join(vs))})})},Us=(s,e)=>{let t=s.split(vs),i=[];for(let r=0;r<t.length;r++){let n=Fe(t[r],e);if(i.push(n),n.type==="error")break}return i};function xs(){return new TransformStream({transform(s,e){Ls(s,t=>{let i=t.length,r;if(i<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,i);else if(i<65536){r=new Uint8Array(3);let n=new DataView(r.buffer);n.setUint8(0,126),n.setUint16(1,i)}else{r=new Uint8Array(9);let n=new DataView(r.buffer);n.setUint8(0,127),n.setBigUint64(1,BigInt(i))}s.data&&typeof s.data!="string"&&(r[0]|=128),e.enqueue(r),e.enqueue(t)})}})}var Ut;function nt(s){return s.reduce((e,t)=>e+t.length,0)}function ot(s,e){if(s[0].length===e)return s.shift();let t=new Uint8Array(e),i=0;for(let r=0;r<e;r++)t[r]=s[0][i++],i===s[0].length&&(s.shift(),i=0);return s.length&&i<s[0].length&&(s[0]=s[0].slice(i)),t}function Ps(s,e){Ut||(Ut=new TextDecoder);let t=[],i=0,r=-1,n=!1;return new TransformStream({transform(a,o){for(t.push(a);;){if(i===0){if(nt(t)<1)break;let h=ot(t,1);n=(h[0]&128)===128,r=h[0]&127,r<126?i=3:r===126?i=1:i=2}else if(i===1){if(nt(t)<2)break;let h=ot(t,2);r=new DataView(h.buffer,h.byteOffset,h.length).getUint16(0),i=3}else if(i===2){if(nt(t)<8)break;let h=ot(t,8),l=new DataView(h.buffer,h.byteOffset,h.length),d=l.getUint32(0);if(d>Math.pow(2,21)-1){o.enqueue(Ue);break}r=d*Math.pow(2,32)+l.getUint32(4),i=3}else{if(nt(t)<r)break;let h=ot(t,r);o.enqueue(Fe(n?h:Ut.decode(h),e)),i=0}if(r===0||r>s){o.enqueue(Ue);break}}}})}var xt=4;function k(s){if(s)return Wi(s)}function Wi(s){for(var e in k.prototype)s[e]=k.prototype[e];return s}k.prototype.on=k.prototype.addEventListener=function(s,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(e),this};k.prototype.once=function(s,e){function t(){this.off(s,t),e.apply(this,arguments)}return t.fn=e,this.on(s,t),this};k.prototype.off=k.prototype.removeListener=k.prototype.removeAllListeners=k.prototype.removeEventListener=function(s,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+s];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var i,r=0;r<t.length;r++)if(i=t[r],i===e||i.fn===e){t.splice(r,1);break}return t.length===0&&delete this._callbacks["$"+s],this};k.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+s],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(t){t=t.slice(0);for(var i=0,r=t.length;i<r;++i)t[i].apply(this,e)}return this};k.prototype.emitReserved=k.prototype.emit;k.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};k.prototype.hasListeners=function(s){return!!this.listeners(s).length};var X=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),P=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Fs="arraybuffer";function at(s,...e){return e.reduce((t,i)=>(s.hasOwnProperty(i)&&(t[i]=s[i]),t),{})}var Xi=P.setTimeout,Gi=P.clearTimeout;function G(s,e){e.useNativeTimers?(s.setTimeoutFn=Xi.bind(P),s.clearTimeoutFn=Gi.bind(P)):(s.setTimeoutFn=P.setTimeout.bind(P),s.clearTimeoutFn=P.clearTimeout.bind(P))}var $i=1.33;function Ms(s){return typeof s=="string"?Ji(s):Math.ceil((s.byteLength||s.size)*$i)}function Ji(s){let e=0,t=0;for(let i=0,r=s.length;i<r;i++)e=s.charCodeAt(i),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(i++,t+=4);return t}function ct(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Vs(s){let e="";for(let t in s)s.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(s[t]));return e}function Hs(s){let e={},t=s.split("&");for(let i=0,r=t.length;i<r;i++){let n=t[i].split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return e}var ht=class extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}},$=class extends k{constructor(e){super(),this.writable=!1,G(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,i){return super.emitReserved("error",new ht(e,t,i)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=Fe(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=Vs(e);return t.length?"?"+t:""}};var Me=class extends ${constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let i=0;this._polling&&(i++,this.once("pollComplete",function(){--i||t()})),this.writable||(i++,this.once("drain",function(){--i||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=i=>{if(this.readyState==="opening"&&i.type==="open"&&this.onOpen(),i.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(i)};Us(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){let e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Bs(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=ct()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};var zs=!1;try{zs=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var Ks=zs;function Zi(){}var Pt=class extends Me{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",i=location.port;i||(i=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||i!==e.port}}doWrite(e,t){let i=this.request({method:"POST",data:e});i.on("success",t),i.on("error",(r,n)=>{this.onError("xhr post error",r,n)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,i)=>{this.onError("xhr poll error",t,i)}),this.pollXhr=e}},ee=class s extends k{constructor(e,t,i){super(),this.createRequest=e,G(this,i),this._opts=i,this._method=i.method||"GET",this._uri=t,this._data=i.data!==void 0?i.data:null,this._create()}_create(){var e;let t=at(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let i=this._xhr=this.createRequest(t);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&i.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{i.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var r;i.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(i.getResponseHeader("set-cookie"))),i.readyState===4&&(i.status===200||i.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof i.status=="number"?i.status:0)},0))},i.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=s.requestsCount++,s.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Zi,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete s.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ee.requestsCount=0;ee.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",qs);else if(typeof addEventListener=="function"){let s="onpagehide"in P?"pagehide":"unload";addEventListener(s,qs,!1)}}function qs(){for(let s in ee.requests)ee.requests.hasOwnProperty(s)&&ee.requests[s].abort()}var Qi=(function(){let s=js({xdomain:!1});return s&&s.responseType!==null})(),te=class extends Pt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=Qi&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new ee(js,this.uri(),e)}};function js(s){let e=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Ks))return new XMLHttpRequest}catch{}if(!e)try{return new P[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Ys=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Mt=class extends ${get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=Ys?{}:at(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],r=t===e.length-1;xe(i,this.supportsBinary,n=>{try{this.doWrite(i,n)}catch{}r&&X(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ct()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Ft=P.WebSocket||P.MozWebSocket,se=class extends Mt{createSocket(e,t,i){return Ys?new Ft(e,t,i):t?new Ft(e,t):new Ft(e)}doWrite(e,t){this.ws.send(t)}};var ge=class extends ${get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Ps(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),r=xs();r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();let n=()=>{i.read().then(({done:o,value:h})=>{o||(this.onPacket(h),n())}).catch(o=>{})};n();let a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],r=t===e.length-1;this._writer.write(i).then(()=>{r&&X(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};var Vt={websocket:se,webtransport:ge,polling:te};var er=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ye(s){if(s.length>8e3)throw"URI too long";let e=s,t=s.indexOf("["),i=s.indexOf("]");t!=-1&&i!=-1&&(s=s.substring(0,t)+s.substring(t,i).replace(/:/g,";")+s.substring(i,s.length));let r=er.exec(s||""),n={},a=14;for(;a--;)n[tr[a]]=r[a]||"";return t!=-1&&i!=-1&&(n.source=e,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=sr(n,n.path),n.queryKey=ir(n,n.query),n}function sr(s,e){let t=/\/{2,9}/g,i=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&i.splice(0,1),e.slice(-1)=="/"&&i.splice(i.length-1,1),i}function ir(s,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,r,n){r&&(t[r]=n)}),t}var Ht=typeof addEventListener=="function"&&typeof removeEventListener=="function",dt=[];Ht&&addEventListener("offline",()=>{dt.forEach(s=>s())},!1);var ae=class s extends k{constructor(e,t){if(super(),this.binaryType=Fs,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let i=ye(e);t.hostname=i.host,t.secure=i.protocol==="https"||i.protocol==="wss",t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=ye(t.host).host);G(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(i=>{let r=i.prototype.name;this.transports.push(r),this._transportsByName[r]=i}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Hs(this.opts.query)),Ht&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},dt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=xt,t.transport=e,this.id&&(t.sid=this.id);let i=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](i)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&s.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",s.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let i=0;i<this.writeBuffer.length;i++){let r=this.writeBuffer[i].data;if(r&&(t+=Ms(r)),i>0&&t>this._maxPayload)return this.writeBuffer.slice(0,i);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,X(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,i){return this._sendPacket("message",e,t,i),this}send(e,t,i){return this._sendPacket("message",e,t,i),this}_sendPacket(e,t,i,r){if(typeof t=="function"&&(r=t,t=void 0),typeof i=="function"&&(r=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;let n={type:e,data:t,options:i};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),r&&this.once("flush",r),this.flush()}close(){let e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():e()}):this.upgrading?i():e()),this}_onError(e){if(s.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Ht&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=dt.indexOf(this._offlineEventListener);i!==-1&&dt.splice(i,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};ae.protocol=xt;var lt=class extends ae{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),i=!1;ae.priorWebsocketSuccess=!1;let r=()=>{i||(t.send([{type:"ping",data:"probe"}]),t.once("packet",f=>{if(!i)if(f.type==="pong"&&f.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ae.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{i||this.readyState!=="closed"&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let u=new Error("probe error");u.transport=t.name,this.emitReserved("upgradeError",u)}}))};function n(){i||(i=!0,d(),t.close(),t=null)}let a=f=>{let u=new Error("probe error: "+f);u.transport=t.name,n(),this.emitReserved("upgradeError",u)};function o(){a("transport closed")}function h(){a("socket closed")}function l(f){t&&f.name!==t.name&&n()}let d=()=>{t.removeListener("open",r),t.removeListener("error",a),t.removeListener("close",o),this.off("close",h),this.off("upgrading",l)};t.once("open",r),t.once("error",a),t.once("close",o),this.once("close",h),this.once("upgrading",l),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}},_e=class extends lt{constructor(e,t={}){let i=typeof e=="object",r=i?{...e}:{...t};(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(n=>Vt[n]).filter(n=>!!n)),super(i?r:e,r)}};var Hn=_e.protocol;function Ws(s,e="",t){let i=s;t=t||typeof location<"u"&&location,s==null&&(s=t.protocol+"//"+t.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=t.protocol+s:s=t.host+s),/^(https?|wss?):\/\//.test(s)||(typeof t<"u"?s=t.protocol+"//"+s:s="https://"+s),i=ye(s)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";let n=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+e,i.href=i.protocol+"://"+n+(t&&t.port===i.port?"":":"+i.port),i}var qt={};ai(qt,{Decoder:()=>Ke,Encoder:()=>ze,PacketType:()=>A,isPacketValid:()=>fr,protocol:()=>pt});var nr=typeof ArrayBuffer=="function",or=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,Xs=Object.prototype.toString,ar=typeof Blob=="function"||typeof Blob<"u"&&Xs.call(Blob)==="[object BlobConstructor]",cr=typeof File=="function"||typeof File<"u"&&Xs.call(File)==="[object FileConstructor]";function He(s){return nr&&(s instanceof ArrayBuffer||or(s))||ar&&s instanceof Blob||cr&&s instanceof File}function Ve(s,e){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let t=0,i=s.length;t<i;t++)if(Ve(s[t]))return!0;return!1}if(He(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return Ve(s.toJSON(),!0);for(let t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&Ve(s[t]))return!0;return!1}function Gs(s){let e=[],t=s.data,i=s;return i.data=ft(t,e),i.attachments=e.length,{packet:i,buffers:e}}function ft(s,e,t){if(!s)return s;if(He(s)){let i={_placeholder:!0,num:e.length};return e.push(s),i}else if(Array.isArray(s)){let i=new Array(s.length);for(let r=0;r<s.length;r++)i[r]=ft(s[r],e);return i}else if(typeof s=="object"&&!(s instanceof Date)){if(s.toJSON&&typeof s.toJSON=="function"&&!t)return ft(s.toJSON(),e,!0);let i={};for(let r in s)Object.prototype.hasOwnProperty.call(s,r)&&(i[r]=ft(s[r],e));return i}return s}function $s(s,e){return s.data=zt(s.data,e),delete s.attachments,s}function zt(s,e){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<e.length)return e[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let t=0;t<s.length;t++)s[t]=zt(s[t],e);else if(typeof s=="object")for(let t in s)Object.prototype.hasOwnProperty.call(s,t)&&(s[t]=zt(s[t],e));return s}var Js=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],pt=5,A;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(A||(A={}));var ze=class{constructor(e){this.replacer=e}encode(e){return(e.type===A.EVENT||e.type===A.ACK)&&Ve(e)?this.encodeAsBinary({type:e.type===A.EVENT?A.BINARY_EVENT:A.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===A.BINARY_EVENT||e.type===A.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=Gs(e),i=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(i),r}},Ke=class s extends k{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let i=t.type===A.BINARY_EVENT;i||t.type===A.BINARY_ACK?(t.type=i?A.EVENT:A.ACK,this.reconstructor=new Kt(t)):super.emitReserved("decoded",t)}else if(He(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,i={type:Number(e.charAt(0))};if(A[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===A.BINARY_EVENT||i.type===A.BINARY_ACK){let n=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(n,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");let o=Number(a);if(!Zs(o)||o<1)throw new Error("Illegal attachments");if(o>this.opts.maxAttachments)throw new Error("too many attachments");i.attachments=o}if(e.charAt(t+1)==="/"){let n=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););i.nsp=e.substring(n,t)}else i.nsp="/";let r=e.charAt(t+1);if(r!==""&&Number(r)==r){let n=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}i.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){let n=this.tryParse(e.substr(t));if(s.isPayloadValid(i.type,n))i.data=n;else throw new Error("invalid payload")}return i}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case A.CONNECT:return ut(t);case A.DISCONNECT:return t===void 0;case A.CONNECT_ERROR:return typeof t=="string"||ut(t);case A.EVENT:case A.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Js.indexOf(t[0])===-1);case A.ACK:case A.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},Kt=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=$s(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function hr(s){return typeof s=="string"}var Zs=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function dr(s){return s===void 0||Zs(s)}function ut(s){return Object.prototype.toString.call(s)==="[object Object]"}function lr(s,e){switch(s){case A.CONNECT:return e===void 0||ut(e);case A.DISCONNECT:return e===void 0;case A.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Js.indexOf(e[0])===-1);case A.ACK:return Array.isArray(e);case A.CONNECT_ERROR:return typeof e=="string"||ut(e);default:return!1}}function fr(s){return hr(s.nsp)&&dr(s.id)&&lr(s.type,s.data)}function H(s,e,t){return s.on(e,t),function(){s.off(e,t)}}var ur=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ee=class extends k{constructor(e,t,i){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[H(e,"open",this.onopen.bind(this)),H(e,"packet",this.onpacket.bind(this)),H(e,"error",this.onerror.bind(this)),H(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var i,r,n;if(ur.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:A.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let d=this.ids++,f=t.pop();this._registerAckCallback(d,f),a.id=d}let o=(r=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||r===void 0?void 0:r.writable,h=this.connected&&!(!((n=this.io.engine)===null||n===void 0)&&n._hasPingExpired());return this.flags.volatile&&!o||(h?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(e,t){var i;let r=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(r===void 0){this.acks[e]=t;return}let n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let o=0;o<this.sendBuffer.length;o++)this.sendBuffer[o].id===e&&this.sendBuffer.splice(o,1);t.call(this,new Error("operation has timed out"))},r),a=(...o)=>{this.io.clearTimeoutFn(n),t.apply(this,o)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((i,r)=>{let n=(a,o)=>a?r(a):i(o);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((r,...n)=>i!==this._queue[0]?void 0:(r!==null?i.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(r)):(this._queue.shift(),t&&t(null,...n)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:A.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(i=>String(i.id)===e)){let i=this.acks[e];delete this.acks[e],i.withError&&i.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case A.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case A.EVENT:case A.BINARY_EVENT:this.onevent(e);break;case A.ACK:case A.BINARY_ACK:this.onack(e);break;case A.DISCONNECT:this.ondisconnect();break;case A.CONNECT_ERROR:this.destroy();let i=new Error(e.data.message);i.data=e.data.data,this.emitReserved("connect_error",i);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let i of t)i.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,i=!1;return function(...r){i||(i=!0,t.packet({type:A.ACK,id:e,data:r}))}}onack(e){let t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:A.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let i of t)i.apply(this,e.data)}}};function ce(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}ce.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*s);s=(Math.floor(e*10)&1)==0?s-t:s+t}return Math.min(s,this.max)|0};ce.prototype.reset=function(){this.attempts=0};ce.prototype.setMin=function(s){this.ms=s};ce.prototype.setMax=function(s){this.max=s};ce.prototype.setJitter=function(s){this.jitter=s};var Ae=class extends k{constructor(e,t){var i;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,G(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((i=t.randomizationFactor)!==null&&i!==void 0?i:.5),this.backoff=new ce({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let r=t.parser||qt;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new _e(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let r=H(t,"open",function(){i.onopen(),e&&e()}),n=o=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",o),e?e(o):this.maybeReconnectOnOpen()},a=H(t,"error",n);if(this._timeout!==!1){let o=this._timeout,h=this.setTimeoutFn(()=>{r(),n(new Error("timeout")),t.close()},o);this.opts.autoUnref&&h.unref(),this.subs.push(()=>{this.clearTimeoutFn(h)})}return this.subs.push(r),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(H(e,"ping",this.onping.bind(this)),H(e,"data",this.ondata.bind(this)),H(e,"error",this.onerror.bind(this)),H(e,"close",this.onclose.bind(this)),H(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){X(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new Ee(this,e,t),this.nsps[e]=i),i}_destroy(e){let t=Object.keys(this.nsps);for(let i of t)if(this.nsps[i].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;this.cleanup(),(i=this.engine)===null||i===void 0||i.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(r=>{r?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",r)):e.onreconnect()}))},t);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};var qe={};function je(s,e){typeof s=="object"&&(e=s,s=void 0),e=e||{};let t=Ws(s,e.path||"/socket.io"),i=t.source,r=t.id,n=t.path,a=qe[r]&&n in qe[r].nsps,o=e.forceNew||e["force new connection"]||e.multiplex===!1||a,h;return o?h=new Ae(i,e):(qe[r]||(qe[r]=new Ae(i,e)),h=qe[r]),t.query&&!e.query&&(e.query=t.queryKey),h.socket(t.path,e)}Object.assign(je,{Manager:Ae,Socket:Ee,io:je,connect:je});var Qs=new Set(["master.key.derive","master.key.ready","master.origin.new","master.sealed","master.local.accepted","master.read","master.header","master.decrypt","master.opened","master.catalog","content.read","content.key","content.decrypt","content.opened","content.staged","session.memory","write.queued","write.prepare","chain.advance","write.sealed","content.memory","content.new","content.empty.sealed","content.id","catalog.link","add.commit","add.memory","content.subscribed","changed.receive","chain.checked","snapshot.checked","changed.memory","refresh.begin","refresh.memory","delete.begin","catalog.unlink","delete.proof","delete.commit","delete.memory","superdelete.begin","superdelete.commit","session.clear","session.closed","resync.required","reconnect.waiting","reconnect.attempt","reconnect.restored","reconnect.stopped","reconnect.cancelled","repair.begin","repair.checked","repair.reserve","repair.commit","repair.memory","repair.resolved"]),pr=new Set(["request.validated","hello.ready","read.lookup","read.found","read.subscribed","create.validated","create.committed","create.subscribed","write.lookup","write.verified","write.committed","write.subscribed","reply.ok","reply.error","changed.sent","session.unsubscribed"]);function jt(s,e,t=[],i=0){return c(s.has(e),"INVALID_PACKET"),c(Array.isArray(t)&&t.length<=N.batch,"INVALID_PACKET"),c(Number.isSafeInteger(i)&&i>=0&&i<=N.batch,"INVALID_PACKET"),Object.freeze({step:e,ids:Object.freeze(t.map(V)),count:i})}function ei(s){return B(s,["step","ids","count","action"]),c(["hello","read","create","update","delete","session.close","changed"].includes(s.action),"INVALID_PACKET"),Object.freeze({...jt(pr,s.step,s.ids,s.count),event:`ulda:${s.action}`})}var ti=65536,Yt=class extends Ke{#t=0;constructor(){super({maxAttachments:N.batch*2}),this.on("decoded",()=>{this.#t=0})}add(e){try{if(typeof e=="string")c(e.length<=ti&&Z(e).byteLength<=ti,"LIMIT"),this.#t=0;else{let t=F(e);c(this.#t+t.byteLength<=N.messageBytes,"LIMIT"),this.#t+=t.byteLength}return super.add(e)}catch(t){throw this.destroy(),t}}destroy(){super.destroy(),this.#t=0}},si=Object.freeze({Encoder:ze,Decoder:Yt,protocol:pt});var Wt=Object.freeze({maxAttempts:5,initialDelay:500,maxDelay:5e3,jitter:.2,budget:3e4});function ii(s){if(s===!1)return{...Wt,automatic:!1};let e=s??{};c(e&&typeof e=="object"&&!Array.isArray(e)),c(Object.keys(e).every(i=>Object.hasOwn(Wt,i)));let t={...Wt,...e};for(let i of["maxAttempts","initialDelay","maxDelay","budget"])c(Number.isSafeInteger(t[i]));return c(t.maxAttempts>=1&&t.maxAttempts<=20),c(t.initialDelay>=10&&t.maxDelay>=t.initialDelay&&t.maxDelay<=6e4),c(t.budget>=50&&t.budget<=3e5),c(Number.isFinite(t.jitter)&&t.jitter>=0&&t.jitter<=1),{...t,automatic:!0}}function C(s){if(s?.aborted)throw s.reason}function Xt(s,e){return C(e),e?new Promise((t,i)=>{let r=()=>i(e.reason);e.addEventListener("abort",r,{once:!0}),Promise.resolve(s).then(t,i).finally(()=>e.removeEventListener("abort",r))}):s}function mr(s,e){return C(e),new Promise((t,i)=>{let r=()=>{clearTimeout(n),i(e.reason)},n=setTimeout(()=>{e.removeEventListener("abort",r),t()},s);e.addEventListener("abort",r,{once:!0})})}var mt=class{#t;#i;#c;#e;#a;constructor(e,t,i){this.#t=e,this.#i=t,this.#c=i}get running(){return!!this.#e}cancel(e="OFFLINE"){this.#a?.abort(new S(e))}run({automatic:e=!1}={}){if(this.#e)return this.#e;if(e&&!this.#t.automatic)return Promise.resolve();let t=new AbortController,{signal:i}=t;this.#a=t;let r=setTimeout(()=>t.abort(new S("TIMEOUT")),this.#t.budget),n,a=Promise.resolve().then(async()=>{let h=this.#t,l=new S("OFFLINE");for(let d=1;d<=h.maxAttempts;d++){if(C(i),e||d>1){let f=Math.min(h.maxDelay,h.initialDelay*2**(d-1)),u=Math.max(1,Math.round(f*(1-h.jitter+Math.random()*h.jitter)));this.#c({phase:"waiting",attempt:d,delayMs:u}),await mr(u,i)}this.#c({phase:"attempt",attempt:d}),C(i);try{let f=await Xt(this.#i(i),i);return C(i),n=d,f}catch(f){if(l=z(f),C(i),!["OFFLINE","TIMEOUT","BUSY"].includes(l.code))throw l}}throw l}),o=()=>{clearTimeout(r),this.#e=void 0,this.#a=void 0};return this.#e=a.then(h=>(o(),this.#c({phase:"restored",attempt:n}),h),h=>{let l=z(h);throw o(),this.#c({phase:i.aborted&&l.code!=="TIMEOUT"?"cancelled":"stopped",code:l.code}),l}),this.#e}};function Gt(s){return s.map(e=>({...e.id===void 0?{}:{id:e.id},witnessBytes:e.witness.byteLength,...e.payload===void 0?{}:{payloadBytes:e.payload.byteLength}}))}function ri(s){return s&&typeof s=="object"&&(Object.values(s).forEach(ri),Object.freeze(s)),s}var Ye=class{#t;#i;#c=new Set;#e=new Map;#a=!1;#n;#r=0;#f=0;#E=!1;constructor(e,{timeout:t=1e4,allowInsecureLocalhost:i=!1,diagnostics:r=!1}={}){let n;try{n=new URL(e)}catch{c(!1)}c(!n.username&&!n.password&&!n.search&&!n.hash);let a=["localhost","127.0.0.1","[::1]"].includes(n.hostname);c(n.protocol==="https:"||i&&a&&n.protocol==="http:"),c(Number.isSafeInteger(t)&&t>=50&&t<=6e4),this.#i=t,this.#t=je(n.href,{autoConnect:!1,forceNew:!0,multiplex:!1,transports:["websocket"],parser:si,reconnection:!1,retries:0,timeout:t,withCredentials:!1}),r&&this.#t.on("ulda:diagnostic",o=>{try{let h=ei(o);this.#u(()=>({phase:"server",...h}))}catch{}}),this.#t.on("disconnect",()=>{this.#u(()=>({phase:"connection",event:"disconnect"})),this.#r++,this.#p(),this.#_("disconnect",{intentional:this.#E||this.#a})}),this.#t.on("ulda:changed",o=>{try{let h=bs(o);this.#u(()=>({phase:"push",event:"ulda:changed",updated:Gt(h.updated),deleted:[...h.deleted]})),this.#_("changed",h)}catch{this.#u(()=>({phase:"push",event:"ulda:changed",code:"INVALID_PACKET"})),this.#_("error",new S("INVALID_PACKET"))}})}get connected(){return this.#t.connected&&!this.#a}on(e,t){c(["changed","disconnect","error","trace"].includes(e)&&typeof t=="function");let i=this.#e.get(e)??new Set;return i.add(t),this.#e.set(e,i),()=>i.delete(t)}#_(e,t){for(let i of this.#e.get(e)??[])try{i(t)}catch{}}#u(e){if(this.#e.get("trace")?.size)try{this.#_("trace",ri({time:Date.now(),...e()}))}catch{}}#p(){for(let e of[...this.#c])e()}async start({signal:e}={}){if(C(e),c(!this.#a,"CLOSED"),!this.connected){if(this.#n)return this.#n;this.#u(()=>({phase:"connection",event:"connecting"})),this.#n=new Promise((t,i)=>{let r=!1,n=f=>{r||(r=!0,clearTimeout(d),e?.removeEventListener("abort",l),this.#t.off("connect",a),this.#t.off("connect_error",o),this.#c.delete(h),this.#u(()=>({phase:"connection",event:f?"connect_failed":"connect",...f?{code:f.code}:{}})),f?i(f):t())},a=()=>n(),o=()=>n(new S("OFFLINE")),h=()=>n(new S("CLOSED")),l=()=>{n(e.reason),this.#t.disconnect()},d=setTimeout(()=>{n(new S("TIMEOUT")),this.#t.disconnect()},this.#i);e?.addEventListener("abort",l,{once:!0}),this.#c.add(h),this.#t.once("connect",a),this.#t.once("connect_error",o),this.#t.connect()});try{await this.#n}finally{this.#n=void 0}}}async send(e,{volatile:t=!1,signal:i}={}){C(i);let{action:r,body:n}=Es(e);ws(r,n),c(!this.#a,"CLOSED"),c(this.connected,"OFFLINE"),c(this.#c.size<N.queue,"LIMIT");let a=this.#r,o=["create","update","delete"].includes(r),h=!!this.#e.get("trace")?.size,l=h?++this.#f:0,d=h?performance.now():0,f=`ulda:${r}`;return new Promise((u,y)=>{let p=!1,m=(w,b,I=!1)=>{p||(p=!0,this.#c.delete(g),i?.removeEventListener("abort",E),h&&this.#u(()=>({phase:I?"ack":"failure",event:f,request:l,durationMs:Math.max(0,Math.round(performance.now()-d)),...w?{code:w.code}:{ok:!0},...!w&&r==="read"?{items:Gt(b)}:{},...!w&&r==="create"?{ids:[...b]}:{}})),w?y(w):u(b))},g=()=>m(new S(o?"UNKNOWN_OUTCOME":"OFFLINE")),E=()=>m(new S(o?"UNKNOWN_OUTCOME":i.reason.code));i?.addEventListener("abort",E,{once:!0}),this.#c.add(g);let _=this.#t.timeout(this.#i);t&&_.volatile,h&&this.#u(()=>({phase:"send",event:f,request:l,volatile:!!t,...r==="read"?{ids:[...n]}:{},...o?{items:Gt(n)}:{}})),_.emit(f,n,(w,b)=>{if(!p){if(w||a!==this.#r)return m(new S(o?"UNKNOWN_OUTCOME":"TIMEOUT"));try{m(void 0,Os(r,n,b),!0)}catch(I){let T=z(I);m(o&&(b?.ok!==!1||T.code==="INVALID_PACKET"||T.code==="INVALID_INPUT")?new S("UNKNOWN_OUTCOME"):T,void 0,!0)}}})})}disconnect(){let e=this.connected;this.#E=!0;try{this.#t.disconnect()}finally{this.#E=!1}!e&&!this.#a&&(this.#r++,this.#p(),this.#_("disconnect",{intentional:!0}))}close(){this.#a||(this.#a=!0,this.#r++,this.#p(),this.#t.disconnect(),this.#t.removeAllListeners(),this.#u(()=>({phase:"connection",event:"closed"})),this.#e.clear())}};var gt=class{#t;#i;#c=[];#e=new Map;#a=!1;#n=!1;#r=!1;#f=-1;#E;#_;#u;#p=new Set;#h;constructor(e,t,i,r){this.#t=this.#i=e,this.#E=t,this.#_=i,this.#u=r}get active(){return this.#a||this.#c.length>0||this.#e.size>0}get blocked(){return this.#n}idle(){return this.active?new Promise(e=>this.#p.add(e)):Promise.resolve()}#A(){if(!this.active){for(let e of this.#p)e();this.#p.clear()}}enqueue(e){return c(!this.#r,"CLOSED"),c(!this.#n,"NEEDS_RESYNC"),c(this.#c.length+this.#e.size<N.queue,"LIMIT"),new Promise((t,i)=>{this.#c.push({change:e,resolve:t,reject:i}),this.#g()})}#m(e){for(let t of this.#c.splice(0))t.reject(new S(e))}observe(e,{refresh:t=!1}={}){if(this.#r||e.age<this.#t.age)return;let i=[...this.#e.values()].some(n=>v(n.state.record.witness,e.record.witness)&&v(n.state.record.payload,e.record.payload)),r=v(this.#t.record.witness,e.record.witness)&&v(this.#t.record.payload,e.record.payload);this.#t=e,!i&&!r&&this.active&&(this.#n=!0,this.#m("CONFLICT")),this.active||(this.#i=e),t&&!this.active&&e.age>=this.#f&&(this.#n=!1,this.#i=e),this.#g()}async#g(){if(this.#a||this.#n||this.#r||!this.#c.length||(this.#i.mode==="X"?this.#e.size>0:this.#i.age+1-this.#t.age>=this.#i.N))return;this.#a=!0;let e=this.#c.shift();this.#h=e;try{let t=this.#i,i=this.#E(t,e.change);e.change=void 0;let r=await i;if(this.#r)throw new S("CLOSED");if(this.#n||t!==this.#i)throw new S("NEEDS_RESYNC");e.state=r,this.#i=r,this.#e.set(r.record.witness,e),this.#_(r).then(async()=>{if(this.#r)throw new S("CLOSED");await this.#u(r),this.#e.delete(r.record.witness),!this.#e.size&&!this.#a&&(this.#i=this.#t),e.resolve({ok:!0})}).catch(n=>{this.#e.delete(r.record.witness),n.code==="UNKNOWN_OUTCOME"&&(this.#f=Math.max(this.#f,r.age)),this.#n=!0,this.#m("NEEDS_RESYNC"),e.reject(n)}).finally(()=>{this.#e.delete(r.record.witness),!this.#e.size&&!this.#a&&(this.#i=this.#t),this.#g(),this.#A()})}catch(t){e.reject(t)}finally{this.#h=void 0,this.#a=!1,this.#g(),this.#A()}}stop(e="NEEDS_RESYNC"){this.#n=!0,this.#m(e),this.#A()}close(){this.#r=!0,this.#h?.reject(new S("CLOSED")),this.#m("CLOSED");for(let e of this.#e.values())e.reject(new S("CLOSED"));this.#e.clear(),this.#t=this.#i=void 0,this.#E=this.#_=this.#u=void 0,this.#A()}};function $t(s,e,t,i=[]){let r=a=>(e(),$t(s,e,t,[...i,String(a)])),n={get:()=>(e(),s.value(t,i)),update:a=>(e(),s.set(t,i,a)),delete:()=>(e(),i.length?s.remove(t,i):s.delete(t)),field:r,toJSON:()=>(e(),s.value(t,i))};return new Proxy(Object.create(null),{get:(a,o)=>{if(!(o==="then"||typeof o=="symbol"))return Object.hasOwn(n,o)?n[o]:r(o)},set:()=>{c(!1,"UNSUPPORTED")},deleteProperty:()=>{c(!1,"UNSUPPORTED")},defineProperty:()=>{c(!1,"UNSUPPORTED")}})}function Jt(s,e){return new Proxy(Object.create(null),{get:(t,i)=>{if(c(s.contextGeneration===e,"STALE_REFERENCE"),!(i==="then"||typeof i=="symbol"))return i==="toJSON"?()=>s.snapshot():i==="field"?r=>s.ref(r):s.ref(i)},set:()=>{c(!1,"UNSUPPORTED")},deleteProperty:()=>{c(!1,"UNSUPPORTED")},defineProperty:()=>{c(!1,"UNSUPPORTED")}})}var Zt=class{#t;#i="connecting";#c;#e;#a;#n=new Map;#r=new Map;#f=new Map;#E=Promise.resolve();#_=0;#u=Promise.resolve();#p=0;#h=0;#A=new Map;#m=new Map;#g=-1;#o=!1;#H;#U=!1;#I=!1;#R;#L;#W;#X=!1;#w=0;#z=Promise.resolve();#y=new AbortController;#K=[];#T;#O=0;constructor(e,t={}){c(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).every(r=>["transport","timeout","allowInsecureLocalhost","reconnect"].includes(r)));let i=ii(t.reconnect);this.#t=t.transport??new Ye(e,t),this.#L=new mt(i,r=>this.#Q(r),r=>{r.phase==="stopped"&&!this.#o&&(this.#i=this.#t.connected?"needsResync":"disconnected",this.#l("status",this.#i)),this.#s(`reconnect.${r.phase}`,[],r.attempt??0),this.#l("reconnect",Object.freeze(r)),r.phase==="stopped"&&!this.#o&&this.#l("error",new S(r.code))}),this.#K.push(this.#t.on("changed",r=>{let n=this.#w;if(this.#_>=N.incoming)return this.#F(new S("LIMIT"));this.#C(()=>n===this.#w?this.#se(r):void 0).catch(a=>{n===this.#w&&this.#F(a)})})),this.#K.push(this.#t.on("disconnect",r=>{if(this.#w++,!this.#o){this.#i="disconnected";for(let n of this.#r.values())n.stop();if(this.#l("status",this.#i),this.#o)return;r?.intentional?this.#L.cancel():this.#X&&this.#L.run({automatic:!0}).then(()=>{},()=>{})}})),this.#K.push(this.#t.on("error",r=>this.#F(r))),this.#W=this.#c=this.#G(this.#y.signal),this.#c.catch(()=>{})}get ready(){return this.#c}get status(){return this.#i}get contextGeneration(){return this.#h}get data(){return this.#b(),this.#R}on(e,t){c(!this.#o,"CLOSED"),c(["change","status","error","trace","reconnect"].includes(e)&&typeof t=="function");let i=this.#A.get(e)??new Set;return i.add(t),this.#A.set(e,i),()=>i.delete(t)}#l(e,t){for(let i of this.#A.get(e)??[])try{i(t)}catch{}}#F(e){if(!this.#o){this.#O++,this.#i="needsResync",this.#s("resync.required");for(let t of this.#r.values())t.stop();this.#l("status",this.#i),this.#l("error",z(e))}}#s(e,t=[],i=0){if(this.#A.get("trace")?.size)try{this.#l("trace",Object.freeze({time:Date.now(),phase:"client",event:e,...jt(Qs,e,t,i)}))}catch{}}async#v(e,t,i,r="content"){let n=this.#h;this.#d(n),this.#s(`${r}.decrypt`,[t.id]),this.#d(n);let a=await _s(e,t,i);try{this.#d(n)}catch(o){throw a.origin.fill(0),o}return this.#s(`${r}.opened`,[t.id]),a}#C(e){this.#_++;let t=this.#E.then(e);return this.#E=t.then(()=>{},()=>{}).finally(()=>this.#_--),t}async#G(e){let t=this.#O;try{C(e),await this.#t.start({signal:e}),c(!this.#o,"CLOSED"),C(e);let i=this.#w;await this.#t.send(Dt("hello"),{signal:e}),c(!this.#o,"CLOSED"),C(e),c(i===this.#w&&this.#t.connected,"OFFLINE"),this.#q(t),this.#X=!0,this.#i=this.#e?"needsResync":"ready"}catch(i){throw this.#o||(this.#i=i?.code==="NEEDS_RESYNC"&&this.#t.connected?"needsResync":"disconnected"),z(i)}}#b(e=!1){c(!this.#o,"CLOSED"),c(this.#e,"NOT_OPEN"),e&&(c(!this.#T,"NEEDS_RESYNC"),c(this.#i==="open"&&this.#t.connected,"NEEDS_RESYNC"),c(!this.#I,"BUSY"))}#d(e){c(!this.#o,"CLOSED"),c(e===this.#h,"STALE_REFERENCE")}#k(e,t,i){this.#d(e),C(i),c(t===this.#w&&this.#t.connected,"OFFLINE")}#q(e){c(e===this.#O,"NEEDS_RESYNC")}#D(e,t){this.#d(e),this.#q(t),c(this.#t.connected,"OFFLINE")}async#Q(e){return await Xt(Promise.all([this.#W.catch(()=>{}),this.#E,this.#u,this.#z,...[...this.#r.values()].map(t=>t.idle())]),e),C(e),c(!this.#o,"CLOSED"),this.#i="reconnecting",this.#l("status",this.#i),C(e),await this.#G(e),this.#e?await this.#$(e):this.#l("status",this.#i),C(e),c(!this.#o,"CLOSED"),c(this.#t.connected,"OFFLINE"),c(this.#i==="open"||this.#i==="ready","NEEDS_RESYNC"),this.#R}#B(e){B(e,["contents"]),c(Array.isArray(e.contents)&&e.contents.length<N.resources,"LIMIT");let t=new Set,i=new Set;for(let r of e.contents)B(r,["id","name","key","token"]),V(r.id),de(r.name),c(re(r.key,32).length===32&&re(r.token,32).length===32),c(!t.has(r.name)&&!i.has(r.id)),t.add(r.name),i.add(r.id);return e.contents}#x(e){this.#b(),de(e);let t=this.#e.data.contents.find(i=>i.name===e);return c(t,"NOT_FOUND"),t}async#P(e,t,i){let r=this.#h;this.#d(r),this.#s("write.prepare",[e.id]);let n=R(i(R(e.data))),a=tt(e.origin);try{this.#s("chain.advance",[e.id]);let o=await Re(t,e.token,a,n);this.#d(r),this.#s("write.sealed",[e.id]);let h=W(o);return{id:e.id,origin:a,token:e.token,data:n,witness:h.witness,record:{id:e.id,...h},sealed:o,...M(a)}}catch(o){throw a.fill(0),o}}async#S(e,t,i=!1){if(e){if(c(t.mode===e.mode&&t.token===e.token,"CRYPTO_FAILED"),c(t.age>=e.age,"ROLLBACK"),t.age===e.age){c(v(t.record.witness,e.record.witness)&&v(t.record.payload,e.record.payload),"ROLLBACK");return}if(!i){let r=await st(e.witness,t.witness);if(!r){let n=[...this.#f.get(t.id)??[]].filter(o=>o.age>e.age&&o.age<t.age).sort((o,h)=>o.age-h.age),a=[e];for(let o of n)for(let h of a)if(await st(h.witness,o.witness)){a.push(o);break}for(let o of a.slice(1))if(await st(o.witness,t.witness)){r=!0;break}}c(r,"NEEDS_RESYNC")}this.#s(i?"snapshot.checked":"chain.checked",[t.id??t.record.id])}}#N(e,t=1/0){let i=this.#f.get(e);if(i){for(let r of i)r.age<=t&&i.delete(r);i.size||this.#f.delete(e)}}async#j(e,t){c(!this.#o,"CLOSED");for(let i of t){let r=this.#f.get(i.id)??new Set;r.add(i),this.#f.set(i.id,r)}try{await this.#t.send(e,{volatile:!0,signal:this.#y.signal})}catch(i){if(i.code!=="UNKNOWN_OUTCOME")for(let r of t){let n=this.#f.get(r.id);n?.delete(r),n?.size||this.#f.delete(r.id)}throw i}}#M(e,t){let i=this.#h;return new gt(e,async(r,n)=>{this.#d(i);let a=await this.#P(r,t,n);return this.#d(i),a},r=>(this.#d(i),this.#j(oe("update",[{id:r.id,sealed:r.sealed}]),[r])),r=>this.#C(async()=>{this.#d(i),await this.#ee(r)}))}async#ee(e,t=!1){let i=this.#n.get(e.id);i&&e.age<i.state.age||(await this.#S(i?.state,e,t),i&&(i.state=e,this.#N(e.id,e.age),this.#r.get(e.id)?.observe(e,{refresh:t}),this.#s("content.memory",[e.id]),this.#l("change",{id:e.id,kind:"updated"})))}async register(e){await this.#c,c(!this.#o,"CLOSED"),c(!this.#e&&!this.#U,"BUSY"),c(this.#i==="ready","NEEDS_RESYNC"),this.#U=!0;try{return await this.#C(async()=>{let t=this.#h;this.#d(t);let i=this.#O;this.#s("master.key.derive");let r=kt(e);e=void 0;let n=await r;this.#d(t),this.#s("master.key.ready");let a=et("X"),o=it(),h=R({contents:[]});try{this.#s("master.origin.new");let l=await Re(n,o,a,h);this.#s("master.sealed"),this.#D(t,i);let[d]=await this.#t.send(oe("create",[{sealed:l}]),{volatile:!0,signal:this.#y.signal});this.#d(t);let f=W(l);return this.#h++,this.#e={id:d,origin:a,token:o,data:h,witness:f.witness,record:{id:d,...f},...M(a)},this.#a=n,this.#R=Jt(this,this.#h),this.#t.connected?this.#i!=="needsResync"&&(this.#i="open"):this.#i="disconnected",this.#s("master.local.accepted",[d]),this.#s("session.memory",[d],0),d}finally{this.#e?.origin!==a&&a.fill(0)}})}finally{e=void 0,this.#U=!1}}async connect(e,t){V(e),await this.#c,c(!this.#e&&!this.#U,"BUSY"),c(!this.#o,"CLOSED"),this.#U=!0;try{return await this.#C(async()=>{let i=this.#h;this.#d(i);let r=this.#O;this.#s("master.read",[e]);let n=this.#w,[a]=await this.#t.send(me([e]),{signal:this.#y.signal});this.#k(i,n);let o=Q(a.payload);this.#s("master.header",[e]),this.#s("master.key.derive",[e]);let h=kt(t,o.salt);t=void 0;let l=await h;this.#k(i,n),this.#s("master.key.ready",[e]);let d={id:e,...await this.#v(l,a,void 0,"master")};c(d.mode==="X","UNSUPPORTED_PROFILE");let f=this.#B(d.data);this.#s("master.catalog",[e],f.length);let u=await this.#V(f);this.#k(i,n),this.#q(r),this.#h++,this.#e=d,this.#a=l,this.#n=u;for(let[y,p]of u)this.#r.set(y,this.#M(p.state,p.credentials));return this.#R=Jt(this,this.#h),this.#i="open",this.#s("session.memory",[e],u.size),this.#R})}catch(i){throw i.code!=="NEEDS_RESYNC"&&this.#t.disconnect(),z(i)}finally{t=void 0,this.#U=!1}}async#V(e,t=!1,i=this.#y.signal){let r=new Map;if(!e.length)return r;this.#s("content.read",e.map(a=>a.id),e.length);let n=await this.#Y(e.map(a=>a.id),i);for(let a of e){C(i);let o=n.find(d=>d.id===a.id),h=await De(a.key,Q(o.payload).salt);this.#s("content.key",[a.id]);let l={id:a.id,...await this.#v(h,o,a.token)};await this.#S(this.#n.get(a.id)?.state,l,t),r.set(a.id,{state:l,credentials:h}),this.#s("content.staged",[a.id])}return r}async#Y(e,t=this.#y.signal){try{return await this.#t.send(me(e),{signal:t})}catch(i){if(i.code!=="LIMIT"||e.length<2)throw i;let r=Math.ceil(e.length/2);return[...await this.#Y(e.slice(0,r),t),...await this.#Y(e.slice(r),t)]}}snapshot(){this.#b();let e=Object.create(null);for(let t of this.#e.data.contents){let i=this.#n.get(t.id);i&&Object.defineProperty(e,t.name,{value:R(i.state.data),enumerable:!0})}return e}value(e,t=[]){let i=this.#x(e),r=this.#n.get(i.id);return c(r,"NOT_FOUND"),R(yt(r.state.data,t))}ref(e){let t=this.#x(e).id,i=this.#h;return $t(this,()=>{c(this.#h===i,"STALE_REFERENCE"),c(this.#n.has(t)&&this.#e?.data.contents.some(n=>n.id===t&&n.name===e),"STALE_REFERENCE")},e)}update(e,t){return this.set(e,[],t)}set(e,t,i){this.#b(!0);let r=this.#x(e);c(Array.isArray(t));let n=R(i),a=[...t],o=this.#r.get(r.id);return c(o,"NOT_FOUND"),this.#s("write.queued",[r.id]),o.enqueue(h=>_t(h,a,n))}remove(e,t){this.#b(!0);let i=this.#x(e);c(Array.isArray(t));let r=[...t];c(r.length>0,"UNSUPPORTED");let n=this.#r.get(i.id);return c(n,"NOT_FOUND"),n.enqueue(a=>_t(a,r,null,!0))}#te(e){this.#b(!0),c(this.#p<N.queue,"LIMIT"),this.#p++;let t=this.#h,i=this.#u.then(()=>(this.#d(t),this.#b(!0),c(this.#g<0,"NEEDS_RESYNC"),e())).finally(()=>this.#p--);return this.#u=i.catch(()=>{}),i}add(e,t,i="X"){de(e),c(i==="X"||i==="S");let r=R(t);return this.#te(async()=>{let n=this.#h,a=this.#O;c(!this.#e.data.contents.some(d=>d.name===e),"EXISTS"),c(this.#e.data.contents.length+1<N.resources,"LIMIT");let o=this.#m.get(e);if(o)c(o.mode===i&&JSON.stringify(o.data)===JSON.stringify(r),"BUSY");else{this.#s("content.new");let d=It(),f=it(),u=await De(d),y=et(i),p=await Re(u,f,y,null);this.#s("content.empty.sealed"),this.#D(n,a),o={key:d,token:f,credentials:u,mode:i,data:r,state:{origin:y,token:f,data:null,...M(y)}};try{let[m]=await this.#t.send(oe("create",[{sealed:p}]),{volatile:!0,signal:this.#y.signal});o.id=m,this.#s("content.id",[m]),o.state.id=m,o.state.record={id:m,...W(p)},o.state.witness=o.state.record.witness}catch(m){throw!this.#o&&m.code==="UNKNOWN_OUTCOME"&&(this.#g=1/0),m}this.#d(n),this.#m.set(e,o)}this.#D(n,a);let h=await this.#P(o.state,o.credentials,()=>r);this.#d(n);let l=await this.#P(this.#e,this.#a,d=>(c(!d.contents.some(f=>f.name===e),"EXISTS"),d.contents.push({id:o.id,name:e,key:o.key,token:o.token}),this.#s("catalog.link",[this.#e.id,o.id]),this.#B(d),d));this.#d(n);try{this.#s("add.commit",[o.id,this.#e.id]),this.#D(n,a),await this.#j(oe("update",[{id:o.id,sealed:h.sealed},{id:this.#e.id,sealed:l.sealed}]),[h,l])}catch(d){throw!this.#o&&d.code==="UNKNOWN_OUTCOME"&&(this.#g=l.age,this.#i="needsResync"),d}return await this.#C(async()=>{if(this.#d(n),l.age>=this.#e.age&&(await this.#S(this.#e,l),this.#e=l),!this.#n.has(o.id)&&this.#e.data.contents.some(d=>d.id===o.id&&d.token===o.token)){let d=o.received&&o.received.age>h.age?o.received:h;this.#n.set(o.id,{state:d,credentials:o.credentials}),this.#r.set(o.id,this.#M(d,o.credentials))}this.#m.delete(e),this.#N(this.#e.id,this.#e.age),this.#N(o.id,this.#n.get(o.id)?.state.age??1/0),this.#s("add.memory",[o.id,this.#e.id])}),this.#s("content.subscribed",[o.id]),{ok:!0,name:e,subscriptionReady:this.#t.connected}})}async#se(e){if(this.#o||!this.#e)return;this.#s("changed.receive",[...e.updated.map(f=>f.id),...e.deleted]);let t=this.#h,i=this.#w,r=e.deleted.includes(this.#e.id),n=e.updated.find(f=>f.id===this.#e.id),a=this.#e;if(n){let f={id:this.#e.id,...await this.#v(this.#a,n,this.#e.token,"master")};f.age>=this.#e.age&&(await this.#S(this.#e,f),this.#B(f.data),a=f)}for(let f of a.data.contents){let u=this.#e.data.contents.find(y=>y.id===f.id);u&&c(f.key===u.key&&f.token===u.token,"UNSUPPORTED_PROFILE")}let o=new Map,h=new Map;for(let f of e.updated){let u=a.data.contents.find(g=>g.id===f.id);if(!u){let g=[...this.#m.values()].find(E=>E.id===f.id);if(g){let E={id:f.id,...await this.#v(g.credentials,f,g.token)},_=g.received??g.state;E.age>=_.age&&(await this.#S(_,E),h.set(g,E))}continue}let y=await De(u.key,Q(f.payload).salt),p={id:u.id,...await this.#v(y,f,u.token)},m=this.#n.get(u.id)?.state;m&&p.age<m.age||(await this.#S(m,p),o.set(u.id,{state:p,credentials:y}))}if(r){this.#k(t,i),await this.close();return}let l=a.data.contents.filter(f=>!this.#n.has(f.id)&&!o.has(f.id)&&!e.deleted.includes(f.id));for(let[f,u]of await this.#V(l))o.set(f,u);this.#k(t,i);for(let[f,u]of h)f.received=u;this.#e=a,this.#N(a.id,a.age);let d=new Set(a.data.contents.map(f=>f.id));for(let f of this.#n.keys())(!d.has(f)||e.deleted.includes(f))&&(this.#r.get(f)?.close(),this.#r.delete(f),this.#n.delete(f),this.#N(f));for(let[f,u]of o)this.#n.set(f,u),this.#N(f,u.state.age),this.#r.has(f)?this.#r.get(f).observe(u.state):this.#r.set(f,this.#M(u.state,u.credentials));this.#l("change",{ids:[...o.keys()],kind:"updated"}),this.#s("changed.memory",[...o.keys(),...e.deleted]),e.deleted.length&&this.#l("change",{ids:[...e.deleted],kind:"deleted"})}async refresh(){return c(!this.#L.running,"BUSY"),this.#$()}async#$(e=this.#y.signal){return this.#b(),c(!this.#p&&![...this.#r.values()].some(t=>t.active),"BUSY"),this.#C(async()=>{let t=this.#h,i=this.#w;this.#k(t,i,e);let r=this.#O;this.#s("refresh.begin",[this.#e.id]),this.#s("master.read",[this.#e.id]);let[n]=await this.#t.send(me([this.#e.id]),{signal:e}),a={id:this.#e.id,...await this.#v(this.#a,n,this.#e.token,"master")};await this.#S(this.#e,a,!0),this.#s("master.catalog",[this.#e.id],this.#B(a.data).length);let o=await this.#V(this.#B(a.data),!0,e);this.#k(t,i,e),this.#q(r),this.#e=a,this.#N(a.id,a.age);for(let[h,l]of this.#r)o.has(h)||(l.close(),this.#r.delete(h),this.#N(h));this.#n=o;for(let[h,l]of o)this.#N(h,l.state.age),this.#r.has(h)?this.#r.get(h).observe(l.state,{refresh:!0}):this.#r.set(h,this.#M(l.state,l.credentials));a.age>=this.#g&&(this.#g=-1);for(let[h,l]of this.#m)a.data.contents.some(d=>d.name===h&&d.id===l.id&&d.token===l.token)&&this.#m.delete(h);return this.#i=!this.#T&&this.#g<0&&![...this.#r.values()].some(h=>h.blocked)?"open":"needsResync",this.#s("refresh.memory",[this.#e.id],o.size),this.#l("status",this.#i),this.#k(t,i,e),this.#R}).catch(t=>{let i=z(t);throw this.#t.connected&&!e?.aborted&&this.#F(i),i})}reconnect(){if(this.#o)return Promise.reject(new S("CLOSED"));let e=this.#L.running,t=this.#L.run();if(!e){this.#i="reconnecting";for(let i of this.#r.values())i.stop();this.#l("status",this.#i)}return this.#c=t.then(()=>{}),this.#c.catch(()=>{}),t}async recoverContent(e){this.#b(),de(e),c(this.#t.connected,"OFFLINE"),c(!this.#I&&!this.#L.running&&!this.#p&&![...this.#r.values()].some(i=>i.active),"BUSY"),c(!this.#T||this.#T.content===e,"BUSY"),c(this.#g<0&&!this.#m.size&&(this.#T||!this.#f.size),"NEEDS_RESYNC"),this.#I=!0;let t;this.#z=new Promise(i=>{t=i});try{return await this.#C(async()=>{let i=this.#h,r=this.#w,n=this.#O,a=()=>this.#k(i,r,this.#y.signal);a();let o=this.#T;if(!o){let p=this.#x(e),m=this.#n.get(p.id)?.state;c(m,"NOT_FOUND"),o={content:e,entry:R(p),source:R(m.data),sourceAge:m.age,mode:m.mode,phase:"prepared"},this.#T=o}this.#i="needsResync";for(let p of this.#r.values())p.stop();this.#s("repair.begin",[o.entry.id]),a(),c(o.phase!=="createUnknown","UNKNOWN_OUTCOME");let[h]=await this.#t.send(me([this.#e.id]),{signal:this.#y.signal});a();let l={id:this.#e.id,...await this.#v(this.#a,h,this.#e.token,"master")};await this.#S(this.#e,l,!0);let d=this.#B(l.data),f=d.find(p=>p.name===e),u=(p,m)=>p?.id===m.id&&p.key===m.key&&p.token===m.token;if(a(),o.id&&u(f,{id:o.id,key:o.key,token:o.token})){c(o.candidate&&["commitUnknown","committed"].includes(o.phase),"CONFLICT"),await this.#S(o.master,l,!0);let p=await this.#V(d,!0);await this.#S(o.candidate,p.get(o.id).state,!0),a();let m=this.#J(o,l,p,n,!0);return this.#s("repair.resolved",[m.previousId,m.id]),m}c(!["commitUnknown","committed"].includes(o.phase),"UNKNOWN_OUTCOME"),c(u(f,o.entry),"CONFLICT");let y=await this.#V(d.filter(p=>p.id!==o.entry.id),!0);if(a(),this.#s("repair.checked",[l.id,o.entry.id]),a(),o.id){let[p]=await this.#t.send(me([o.id]),{signal:this.#y.signal});a(),c(v(p.witness,o.base.record.witness)&&v(p.payload,o.base.record.payload),"CONFLICT")}else{if(!o.base){o.key=It(),o.token=it(),o.credentials=await De(o.key),a();let p=et(o.mode);o.base={origin:p,token:o.token,data:null,...M(p)}}o.empty||(o.empty=await Re(o.credentials,o.token,o.base.origin,null),a()),this.#s("repair.reserve"),a(),this.#D(i,n);try{let[p]=await this.#t.send(oe("create",[{sealed:o.empty}]),{volatile:!0,signal:this.#y.signal});this.#d(i),o.phase="createUnknown",c(p!==l.id&&!d.some(g=>g.id===p),"UNKNOWN_OUTCOME"),o.id=p;let m=W(o.empty);Object.assign(o.base,{id:p,witness:m.witness,record:{id:p,...m}}),o.phase="reserved"}catch(p){throw p.code==="UNKNOWN_OUTCOME"&&!this.#o&&(o.phase="createUnknown"),p}a()}o.candidate=await this.#P(o.base,o.credentials,()=>o.source),a(),o.master=await this.#P(l,this.#a,p=>{let m=p.contents.find(g=>g.name===e);return c(u(m,o.entry),"CONFLICT"),Object.assign(m,{id:o.id,key:o.key,token:o.token}),this.#B(p),p}),a(),this.#s("repair.commit",[o.id,l.id]),a(),this.#D(i,n);try{await this.#j(oe("update",[{id:o.id,sealed:o.candidate.sealed},{id:l.id,sealed:o.master.sealed}]),[o.candidate,o.master]),o.phase="committed"}catch(p){throw this.#o||(o.phase=p.code==="UNKNOWN_OUTCOME"?"commitUnknown":"reserved"),p}return this.#d(i),y.set(o.id,{state:o.candidate,credentials:o.credentials}),this.#J(o,o.master,y,n,!1)})}catch(i){throw!this.#o&&this.#T&&this.#t.connected&&this.#F(i),z(i)}finally{this.#I=!1,t()}}#J(e,t,i,r,n){let a=Object.freeze({ok:!0,previousId:e.entry.id,id:e.id,sourceAge:e.sourceAge,reconciled:n});for(let o of this.#r.values())o.close();this.#r.clear(),this.#e=t,this.#n=i,this.#f.clear();for(let[o,h]of i)this.#r.set(o,this.#M(h.state,h.credentials));return this.#Z(),this.#i=this.#t.connected?this.#O===r?"open":"needsResync":"disconnected",this.#s("repair.memory",[a.previousId,a.id,t.id]),this.#o||this.#l("change",{ids:[a.previousId,a.id],kind:"recovered"}),this.#o||this.#l("status",this.#i),a}#Z(){let e=this.#T;if(!e)return;let t=new Set([this.#e?.origin,...[...this.#n.values()].map(i=>i.state.origin)]);for(let i of[e.base,e.candidate,e.master])i&&!t.has(i.origin)&&i.origin.fill(0);this.#T=void 0}async delete(e){this.#b(!0),de(e),c(!this.#p&&![...this.#r.values()].some(i=>i.active),"BUSY"),this.#I=!0;let t;this.#z=new Promise(i=>{t=i});try{let i=this.#O;this.#s("delete.begin"),await this.refresh();let r=this.#x(e),n=this.#n.get(r.id)?.state;c(n,"NOT_FOUND");let a=this.#h,o=await Rt(r.id,n.origin);this.#s("delete.proof",[r.id]);let h=await this.#P(this.#e,this.#a,l=>(l.contents=l.contents.filter(d=>d.id!==r.id),this.#s("catalog.unlink",[this.#e.id,r.id]),l));this.#d(a),this.#s("delete.commit",[r.id,this.#e.id]);try{this.#D(a,i),await this.#j(vt([o],[{id:this.#e.id,sealed:h.sealed}]),[h])}catch(l){throw this.#o||(l.code==="UNKNOWN_OUTCOME"&&(this.#g=h.age),this.#i="needsResync",this.#s("resync.required")),l}return await this.#C(async()=>{this.#d(a),h.age>=this.#e.age&&(await this.#S(this.#e,h),this.#e=h),this.#r.get(r.id)?.close(),this.#r.delete(r.id),this.#n.delete(r.id),this.#N(r.id),this.#N(this.#e.id,this.#e.age),this.#s("delete.memory",[r.id,this.#e.id]),this.#l("change",{ids:[r.id],kind:"deleted"})}),{ok:!0}}finally{this.#I=!1,t()}}async superDelete(){this.#b(!0),c(!this.#p&&![...this.#r.values()].some(t=>t.active),"BUSY"),this.#I=!0;let e;this.#z=new Promise(t=>{e=t});try{let t=this.#O;this.#s("superdelete.begin",[this.#e.id]),await this.refresh();let i=[...this.#n.values()].map(a=>a.state);i.push(this.#e);let r=this.#h,n=[];for(let a of i)n.push(await Rt(a.id,a.origin));this.#d(r);try{this.#s("superdelete.commit",i.map(a=>a.id),i.length),this.#D(r,t),await this.#t.send(vt(n),{volatile:!0,signal:this.#y.signal})}catch(a){throw!this.#o&&a.code==="UNKNOWN_OUTCOME"&&(this.#g=1/0,this.#i="needsResync"),a}return await this.close(),{ok:!0}}finally{this.#I=!1,e()}}close(){if(this.#H)return this.#H;let e,t;return this.#H=new Promise((i,r)=>{e=i,t=r}),this.#ie().then(e,t),this.#H}async#ie(){if(this.#o)return;this.#o=!0,this.#L.cancel("CLOSED"),this.#i="closed",this.#h++,this.#y.abort(new S("CLOSED"));for(let t of this.#K.splice(0))try{t?.()}catch{}let e=t=>t?.origin?.fill(0);e(this.#e);for(let{state:t}of this.#n.values())e(t);for(let t of this.#f.values())for(let i of t)e(i);for(let t of this.#m.values())e(t.state),e(t.received);this.#Z();for(let t of this.#r.values())t.close();this.#e=void 0,this.#a=void 0,this.#n.clear(),this.#r.clear(),this.#f.clear(),this.#m.clear(),this.#R=void 0,this.#s("session.clear");try{this.#t.connected&&await this.#t.send(Dt("session.close"))}catch{}finally{this.#t.close(),this.#s("session.closed"),this.#l("status","closed");for(let t of this.#A.values())t.clear();this.#A.clear()}}};export{Ye as SocketIoTransport,Zt as Ulda,S as UldaError};
2
+ var hi=Object.defineProperty;var di=(s,e)=>{for(var t in e)hi(s,t,{get:e[t],enumerable:!0})};var ns=Object.freeze({INVALID_INPUT:"Invalid input.",INVALID_PACKET:"Invalid protocol packet.",UNSUPPORTED_PROFILE:"Unsupported resource profile.",CRYPTO_FAILED:"Cannot authenticate or decrypt resource.",CLOSED:"Client is closed.",OFFLINE:"Transport is not ready.",NOT_OPEN:"Open a master first.",UNKNOWN_OUTCOME:"The request may have committed. Automatic replay is disabled.",CONFLICT:"Resource changed. Refresh before applying the intention again.",NOT_FOUND:"Resource does not exist.",EXISTS:"Name already exists.",NEEDS_RESYNC:"Refresh is required before further writes.",ROLLBACK:"Older or inconsistent state rejected.",LIMIT:"SDK limit exceeded.",UNSUPPORTED:"Operation requires an agreed protocol extension.",SERVER_ERROR:"Server rejected the request.",STALE_REFERENCE:"Reference belongs to an old context.",BUSY:"An operation is still running.",TIMEOUT:"Operation timed out."}),b=class extends Error{constructor(e){let t=typeof e=="string"&&Object.hasOwn(ns,e)?e:"SERVER_ERROR";super(ns[t]),this.name="UldaError",this.code=t}},j=s=>{throw new b(s)},c=(s,e="INVALID_INPUT")=>{s||j(e)},H=s=>s instanceof b?s:new b("SERVER_ERROR");var _=Object.freeze({jsonBytes:1048576,payloadBytes:11e5,messageBytes:8388608,incoming:8,batch:64,resourceBytes:64*1048576,transferBytes:128*1048576,queue:128,depth:48,nodes:4e4}),Q=s=>new TextEncoder().encode(s),D=(s,e)=>s.length===e.length&&s.every((t,i)=>t===e[i]);function we(...s){let e=new Uint8Array(s.reduce((i,n)=>i+n.length,0)),t=0;for(let i of s)e.set(i,t),t+=i.length;return e}var Oe=s=>globalThis.crypto.getRandomValues(new Uint8Array(s));function C(s,e=_.payloadBytes){let t;return s instanceof ArrayBuffer?t=new Uint8Array(s):s instanceof Uint8Array&&s.buffer instanceof ArrayBuffer?t=new Uint8Array(s.buffer,s.byteOffset,s.byteLength):c(!1,"INVALID_PACKET"),c(t.byteLength>0&&t.byteLength<=e,"INVALID_PACKET"),t}function Ge(s){let e="";for(let t=0;t<s.length;t+=8192)e+=String.fromCharCode(...s.subarray(t,t+8192));return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function re(s,e=_.payloadBytes){c(typeof s=="string"&&s.length>0&&s.length<=Math.ceil(e*4/3)&&/^[A-Za-z0-9_-]+$/.test(s)&&s.length%4!==1,"INVALID_PACKET");let t;try{t=Uint8Array.from(atob(s.replaceAll("-","+").replaceAll("_","/")),i=>i.charCodeAt(0))}catch{c(!1,"INVALID_PACKET")}return c(t.length<=e&&Ge(t)===s,"INVALID_PACKET"),t}function P(s){return c(typeof s=="string"&&/^[1-9][0-9]{0,39}$/.test(s)),s}function de(s){return c(typeof s=="string"&&s.length>0&&s.length<=256),s}function I(s,e){c(s!==null&&typeof s=="object"&&!Array.isArray(s),"INVALID_PACKET"),c(Object.keys(s).length===e.length&&e.every(t=>Object.hasOwn(s,t)),"INVALID_PACKET")}function U(s,e=!1){let t=e?_.resourceBytes-4096:_.jsonBytes,i=e?t:_.nodes,n=new Set,r=0,a=0;function o(d,l){if(c(++r<=i&&l<=_.depth,"LIMIT"),typeof d=="string")return a+=d.length,c(a<=t,"LIMIT"),d;if(d===null||typeof d=="boolean")return d;if(typeof d=="number")return c(Number.isFinite(d)),d;c(d&&typeof d=="object"&&!n.has(d));let f=Array.isArray(d),p=Object.getPrototypeOf(d);c(f?p===Array.prototype:p===Object.prototype||p===null),n.add(d);let m=f?[]:Object.create(null),u=Reflect.ownKeys(d).filter(y=>!(f&&y==="length"));f&&c(u.length===d.length&&d.length<=i);for(let y of u){c(typeof y=="string"),a+=y.length,c(a<=t,"LIMIT"),f&&c(/^(0|[1-9][0-9]*)$/.test(y)&&Number(y)<d.length);let g=Object.getOwnPropertyDescriptor(d,y);c(g.enumerable&&Object.hasOwn(g,"value")),Object.defineProperty(m,y,{value:o(g.value,l+1),enumerable:!0,writable:!0,configurable:!0})}return n.delete(d),m}let h=o(s,0);return c(Q(JSON.stringify(h)).length<=t,"LIMIT"),h}function At(s,e){let t=s;for(let i of e)c(t!==null&&typeof t=="object"&&Object.hasOwn(t,i),"NOT_FOUND"),t=t[i];return t}function wt(s,e,t,i=!1){if(c(Array.isArray(e)&&e.length<=_.depth&&e.every(o=>typeof o=="string"||Number.isSafeInteger(o))),!e.length)return c(!i,"UNSUPPORTED"),U(t);let n=U(s),r=At(n,e.slice(0,-1)),a=String(e.at(-1));return c(r!==null&&typeof r=="object"),Array.isArray(r)&&c(/^(0|[1-9][0-9]*)$/.test(a)&&Number(a)<r.length),i?(c(Object.hasOwn(r,a),"NOT_FOUND"),Array.isArray(r)?r.splice(Number(a),1):delete r[a]):Object.defineProperty(r,a,{value:U(t),enumerable:!0,writable:!0,configurable:!0}),n}function bt(s){return[...s].map(e=>e.toString(16).padStart(2,"0")).join("")}function Qe(s){return Uint8Array.from(s.match(/../g).map(e=>parseInt(e,16)))}function hs(s){return btoa(String.fromCharCode(...s))}function et(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function ds(s){return/^[0-9a-f]+$/i.test(s)&&s.length%2===0?Qe(s):et(s)}function Nt(s){let e=typeof s=="bigint"?s:BigInt(s);if(e===0n)return Uint8Array.of(0);let t=[];for(;e>0n;)t.unshift(Number(e&0xffn)),e>>=8n;return Uint8Array.from(t)}function Se(...s){let e=new Uint8Array(s.reduce((i,n)=>i+n.length,0)),t=0;return s.forEach(i=>(e.set(i,t),t+=i.length)),e}function li(s,e){return s.length===e.length&&s.every((t,i)=>t===e[i])}function ke(s,e){return({base64:hs,bytes:t=>t,hex:bt}[e]??bt)(s)}function Ie(s,e){return s instanceof Uint8Array?s:({hex:Qe,base64:et}[e]??ds)(s)}var N=Object.freeze({ULDA_FORMAT_SENTINEL:"ULDA_FORMAT_SENTINEL",ULDA_FORMAT_HEADER:"ULDA_FORMAT_HEADER",ULDA_FORMAT_SIZE:"ULDA_FORMAT_SIZE",ULDA_FORMAT_BODY_DIVISION:"ULDA_FORMAT_BODY_DIVISION",ULDA_FORMAT_UNKNOWN_MODE:"ULDA_FORMAT_UNKNOWN_MODE",ULDA_FORMAT_UNKNOWN_ALGORITHM:"ULDA_FORMAT_UNKNOWN_ALGORITHM",ULDA_HASHER_NOT_REGISTERED:"ULDA_HASHER_NOT_REGISTERED",ULDA_HASHER_OUTPUT_UNSUPPORTED:"ULDA_HASHER_OUTPUT_UNSUPPORTED",ULDA_HASHER_SIZE_MISMATCH:"ULDA_HASHER_SIZE_MISMATCH",ULDA_MODE_UNSUPPORTED:"ULDA_MODE_UNSUPPORTED",ULDA_MODE_EMPTY_BLOCKS:"ULDA_MODE_EMPTY_BLOCKS",ULDA_VERIFY_INCOMPATIBLE_PARAMS:"ULDA_VERIFY_INCOMPATIBLE_PARAMS",ULDA_VERIFY_INVALID_GAP:"ULDA_VERIFY_INVALID_GAP",ULDA_CONFIG_INVALID:"ULDA_CONFIG_INVALID",ULDA_RANDOM_UNAVAILABLE:"ULDA_RANDOM_UNAVAILABLE",ULDA_INTERNAL_ERROR:"ULDA_INTERNAL_ERROR"}),fi=new Set(["origin","blocks","sigBytes","bytes","raw","secret","privateKey","preimage"]);function ui(s){if(s===null||typeof s!="object")return!1;let e=Object.getPrototypeOf(s);return e===Object.prototype||e===null}function Tt(s){if(Array.isArray(s))return s.map(t=>Tt(t));if(!ui(s))return s;let e={};for(let[t,i]of Object.entries(s))fi.has(t)||(e[t]=Tt(i));return e}var M=class extends Error{constructor(s,e,t={}){super(e,{cause:t.cause}),this.name="UldaError",this.code=s,this.operation=t.operation,this.details=t.details,this.cause=t.cause}toLogObject(){return{name:this.name,code:this.code,message:this.message,operation:this.operation,details:Tt(this.details),causeName:this.cause?.name,causeMessage:this.cause?.message}}},ls=0,fs=0,x=Object.freeze({BACKUP_SIZE:128,N:64,ALGORITHM:32,AGE:16,BACKUP_DESCRIPTOR:8,MODE_X:4,FUTURE_MODE:2,BACKUP_ACTIVE:1}),Y=Object.freeze({N:5,algorithm:2,mode:"S",age:0n}),$e=3,us=20;function v(s,e,t){return new M(s,e,{operation:"compactHeader",details:t})}function Ot(s,e){if(!Number.isInteger(s)||s<0||s>255)throw v(N.ULDA_CONFIG_INVALID,`invalid ${e}`,{[e]:s})}function ps(s,e){if(!(s instanceof Uint8Array))throw v(N.ULDA_CONFIG_INVALID,`invalid ${e}`,{type:typeof s})}function Ne(s,e,t){let i=0;for(let n=0;n<t;n++){let r=e+n,o=s[r>>>3]>>>7-(r&7)&1;i=i<<1|o}return i}function Te(s,e,t,i){for(let n=0;n<t;n++){let r=t-1-n,a=i>>>r&1,o=e+n,h=o>>>3,d=1<<7-(o&7);a?s[h]|=d:s[h]&=~d}}function be(s,e){return Ne(s,e,8)}function pi(s,e,t){Te(s,e,8,t)}function yi(s,e){if(typeof s!="bigint"||s<0n)throw v(N.ULDA_CONFIG_INVALID,"invalid age",{age:s});let t=1n<<BigInt(e*8);if(s>=t)throw v(N.ULDA_CONFIG_INVALID,"age does not fit",{ageBytes:e});let i=new Uint8Array(e),n=s;for(let r=e-1;r>=0;r--)i[r]=Number(n&0xffn),n>>=8n;return i}function gi(s){let e=0n;for(let t of s)e=e<<8n|BigInt(t);return e}function mi(s={}){let e=s.forceFields??{},t=0,i=[],n=s.N??Y.N,r=s.algorithm??Y.algorithm,a=s.mode??Y.mode,o=s.age??Y.age,h=s.ageBytes??4,d=s.backupActive===!0,l=s.backupDescriptor!==void 0&&s.backupDescriptor.length>0,f=s.backupSize!==void 0||e.backupSize===!0||l;if(a!=="S"&&a!=="X")throw v(N.ULDA_CONFIG_INVALID,"invalid mode",{mode:a});if(a==="X"&&(t|=x.MODE_X),d&&(t|=x.BACKUP_ACTIVE),(s.N!==void 0||e.N===!0)&&Ot(n,"N"),(s.algorithm!==void 0||e.algorithm===!0)&&Ot(r,"algorithm"),(s.age!==void 0||e.age===!0)&&h!==4&&h!==8)throw v(N.ULDA_CONFIG_INVALID,"invalid ageBytes",{ageBytes:h});s.backupDescriptor!==void 0&&ps(s.backupDescriptor,"backupDescriptor");let p=s.backupSize??s.backupDescriptor?.length??0;if(f&&Ot(p,"backupSize"),l&&p!==s.backupDescriptor.length)throw v(N.ULDA_CONFIG_INVALID,"backupSize does not match backupDescriptor length",{backupSize:p,descriptorLength:s.backupDescriptor.length});f&&(t|=x.BACKUP_SIZE,i.push(p)),(s.N!==void 0&&n!==Y.N||e.N===!0)&&(t|=x.N,i.push(n)),(s.algorithm!==void 0&&r!==Y.algorithm||e.algorithm===!0)&&(t|=x.ALGORITHM,i.push(r)),(s.age!==void 0&&o!==Y.age||e.age===!0)&&(t|=x.AGE,i.push(...yi(o,h))),l&&(t|=x.BACKUP_DESCRIPTOR,i.push(...s.backupDescriptor));let m=$e+i.length;if(m>255)throw v(N.ULDA_FORMAT_SIZE,"compact header too large",{headerSize:m});let u=new Uint8Array(m);Te(u,0,4,ls),Te(u,4,8,m),Te(u,12,8,t);let y=us;for(let g of i)pi(u,y,g),y+=8;return Te(u,y,4,fs),u}function _i(s){if(ps(s,"input"),s.length<$e)throw v(N.ULDA_FORMAT_SIZE,"compact header is too short",{inputLength:s.length});let e=Ne(s,0,4);if(e!==ls)throw v(N.ULDA_FORMAT_SENTINEL,"invalid compact header prefix",{prefix:e});let t=Ne(s,4,8);if(t<$e)throw v(N.ULDA_FORMAT_HEADER,"invalid compact header size",{headerSize:t});if(t>s.length)throw v(N.ULDA_FORMAT_SIZE,"compact header exceeds input length",{headerSize:t,inputLength:s.length});let i=Ne(s,12,8),n={hasBackupSize:!!(i&x.BACKUP_SIZE),hasN:!!(i&x.N),hasAlgorithm:!!(i&x.ALGORITHM),hasAge:!!(i&x.AGE),hasBackupDescriptor:!!(i&x.BACKUP_DESCRIPTOR),modeX:!!(i&x.MODE_X),futureMode:!!(i&x.FUTURE_MODE),backupActive:!!(i&x.BACKUP_ACTIVE)};if(n.hasBackupDescriptor&&!n.hasBackupSize)throw v(N.ULDA_FORMAT_HEADER,"backup descriptor requires backupSize",{inclusive:i});let r=0;n.hasBackupSize&&(r+=1),n.hasN&&(r+=1),n.hasAlgorithm&&(r+=1);let a=us,o=0;n.hasBackupSize&&(o=be(s,a),a+=8),n.hasBackupDescriptor&&(r+=o);let h=t-$e,d=n.hasAge?h-r:0;if(n.hasAge&&d!==4&&d!==8)throw v(N.ULDA_FORMAT_HEADER,"unsupported compact header age length",{ageBytes:d});if(!n.hasAge&&h!==r)throw v(N.ULDA_FORMAT_HEADER,"invalid compact header optional field layout",{optionalByteCount:h,knownOptionalBytes:r});if(n.hasAge&&h!==r+d)throw v(N.ULDA_FORMAT_HEADER,"invalid compact header optional field layout",{optionalByteCount:h,knownOptionalBytes:r,ageBytes:d});let l=n.hasN?be(s,a):Y.N;n.hasN&&(a+=8);let f=n.hasAlgorithm?be(s,a):Y.algorithm;n.hasAlgorithm&&(a+=8);let p=Y.age;if(n.hasAge){let y=new Uint8Array(d);for(let g=0;g<d;g++)y[g]=be(s,a),a+=8;p=gi(y)}let m=new Uint8Array(0);if(n.hasBackupDescriptor){m=new Uint8Array(o);for(let y=0;y<o;y++)m[y]=be(s,a),a+=8}let u=Ne(s,a,4);if(u!==fs)throw v(N.ULDA_FORMAT_SENTINEL,"invalid compact header suffix",{suffix:u});return{headerSize:t,inclusive:i,flags:n,N:l,algorithm:f,mode:n.modeX?"X":"S",age:p,ageBytes:d,backupSize:o,backupDescriptor:m,bodyOffset:t}}function rs(s){let e=_i(s);return{header:e,body:s.slice(e.headerSize)}}var St={mode:{S:1,X:2},algorithm:{"SHA-1":1,"SHA-256":2,"SHA-384":3,"SHA-512":4,"SHA3-256":5,"SHA3-512":6,BLAKE3:7,WHIRLPOOL:8,CUSTOM:255}},ys={mode:{1:"S",2:"X"},algorithm:Object.fromEntries(Object.entries(St.algorithm).map(([s,e])=>[e,s]))};function Ei(s={}){let e=s.encoder??St,t=s.decoder??ys,i=s.getExportFormat??(()=>"hex"),n=s.getOriginSize??(()=>256),r=(p,m,u,y)=>{let g=new Uint8Array(5+y.length+1);return g.set([0,g.length,p,e.mode[m]??255,e.algorithm[u]??255]),g.set(y,5),g[g.length-1]=0,g},a=p=>{let m=Ie(p,i()),u=m[1];if(m[0]||m[u-1])throw new M(N.ULDA_FORMAT_SENTINEL,"sentinel",{operation:"decodeOrigin",details:{headerLength:u,actualSize:m.length}});let y=m[2],g=t.mode[m[3]]??"U",A=t.algorithm[m[4]]??"UNK",E=0n;for(let S=5;S<u-1;S++)E=E<<8n|BigInt(m[S]);let T=m.slice(u),O=T.length/y;if(!Number.isInteger(O))throw new M(N.ULDA_FORMAT_BODY_DIVISION,"div",{operation:"decodeOrigin",details:{N:y,bodyLength:T.length,blkLen:O}});let L=[];for(let S=0;S<y;S++)L.push(T.slice(S*O,(S+1)*O));return{bytes:m,N:y,mode:g,alg:A,index:E,blockLen:O,origin:L}},o=p=>{let m=Ie(p,i()),u=m[1],y=m[2],g=t.mode[m[3]]??"U",A=t.algorithm[m[4]]??"UNK",E=0n;for(let R=5;R<u-1;R++)E=E<<8n|BigInt(m[R]);let T=m.slice(u),O=(n()??256)>>>3,L=T.length-O,S=L/(y-1);if(L<0||!Number.isInteger(S))throw new M(N.ULDA_FORMAT_SIZE,"SigImporter sizes",{operation:"decodeWitness",details:{N:y,originLen:O,sigLength:T.length,rest:L,blkLen:S}});let q=[T.slice(0,O)];for(let R=0;R<y-1;R++)q.push(T.slice(O+R*S,O+(R+1)*S));return{bytes:m,N:y,mode:g,alg:A,index:E,sigBytes:T,originLen:O,blkLen:S,blocks:q}},h=(p,m=0n,u={})=>{let y=u.N??p.origin?.length??5,g=u.mode??"S",A=u.hash??u.alg??"SHA-256",E=r(y,g,A,Nt(m));return ke(Se(E,...p.origin),i())},d=(p,m)=>{let u=m.hash??m.alg,y=r(m.N,m.mode,u,Nt(m.index));return ke(Se(y,p),i())};return{makeHeader:r,decodeOrigin:a,decodeWitness:o,encodeOrigin:h,encodeWitness:d,packWitness:(p,m)=>d(p,m),splitWitnessBlocks:p=>p.blocks??(()=>{let{originLen:m,blkLen:u,sigBytes:y,N:g}=p,A=[y.slice(0,m)];for(let E=0;E<g-1;E++)A.push(y.slice(m+E*u,m+(E+1)*u));return A})()}}var gs=Object.freeze({exportFormat:"hex",originSize:256,N:5,mode:"S",algorithm:"SHA-256"}),kt=4,Ai=0xffffffffn;function Le(s,e,t){return new M(s,e,{operation:"compactV1",details:t})}function wi(s={}){return{...gs,...s}}function Oi(s){if(s!=="S"&&s!=="X")throw Le(N.ULDA_CONFIG_INVALID,"invalid mode",{mode:s})}function os(s,e){let t=s.algorithm[e];if(!Number.isInteger(t)||t<0||t>255)throw Le(N.ULDA_CONFIG_INVALID,"invalid algorithm",{algorithm:e});return t}function bi(s){if(s.ageBytes!==void 0&&s.ageBytes!==kt)throw Le(N.ULDA_CONFIG_INVALID,"compactV1 ageBytes must be 4",{ageBytes:s.ageBytes})}function Ni(s){if(typeof s=="bigint"&&s>Ai)throw Le(N.ULDA_CONFIG_INVALID,"compactV1 age does not fit uint32",{age:s})}function as(s){if(s.flags.hasAge&&s.ageBytes!==kt)throw Le(N.ULDA_FORMAT_HEADER,"compactV1 age must be 4 bytes",{ageBytes:s.ageBytes})}function Ti(s={}){let e=s.encoder??St,t=s.decoder??ys,i=wi(s.defaults),n=s.getExportFormat??(()=>i.exportFormat),r=s.getOriginSize??(()=>i.originSize),a=os(e,i.algorithm),o=(g={})=>{let A=g.N??i.N,E=g.mode??i.mode,T=g.hash??g.alg??g.algorithm??i.algorithm,O=os(e,T),L=g.index??g.age??0n;return Oi(E),bi(g),Ni(L),mi({N:A,algorithm:O,mode:E,age:L,ageBytes:kt,backupActive:g.backupActive,backupSize:g.backupSize,backupDescriptor:g.backupDescriptor,forceFields:{...g.forceFields,algorithm:g.forceFields?.algorithm??O!==a}})},h=g=>{let A=Ie(g,n()),E=rs(A).header;return as(E),E},d=g=>{let A=Ie(g,n()),{header:E,body:T}=rs(A);return as(E),{bytes:A,header:E,body:T}},l=(g,A=0n,E={})=>{let T=o({...E,index:A,N:E.N??g.origin?.length??i.N});return ke(Se(T,...g.origin),n())},f=g=>{let{bytes:A,header:E,body:T}=d(g),O=E.N,L=E.mode,S=t.algorithm[E.algorithm]??"UNK",q=E.age,R=T.length/O;if(!Number.isInteger(R))throw new M(N.ULDA_FORMAT_BODY_DIVISION,"div",{operation:"decodeOrigin",details:{N:O,bodyLength:T.length,blockLen:R}});let ne=[];for(let Z=0;Z<O;Z++)ne.push(T.slice(Z*R,(Z+1)*R));return{bytes:A,N:O,mode:L,alg:S,index:q,blockLen:R,origin:ne,header:E,body:T}},p=g=>g.blocks??(()=>{let{originLen:A,blkLen:E,sigBytes:T,N:O}=g,L=[T.slice(0,A)];for(let S=0;S<O-1;S++)L.push(T.slice(A+S*E,A+(S+1)*E));return L})(),m=(g,A={})=>{let E=o(A);return ke(Se(E,g),n())};return{encodeHeader:o,decodeHeader:h,encodeOrigin:l,decodeOrigin:f,encodeWitness:m,decodeWitness:g=>{let{bytes:A,header:E,body:T}=d(g),O=E.N,L=E.mode,S=t.algorithm[E.algorithm]??"UNK",q=E.age,R=T,ne=(r()??gs.originSize)>>>3,Z=R.length-ne,Xe=Z/(O-1);if(Z<0||!Number.isInteger(Xe))throw new M(N.ULDA_FORMAT_SIZE,"SigImporter sizes",{operation:"decodeWitness",details:{N:O,originLen:ne,sigLength:R.length,rest:Z,blkLen:Xe}});let ci=p({originLen:ne,blkLen:Xe,sigBytes:R,N:O});return{bytes:A,N:O,mode:L,alg:S,index:q,sigBytes:R,originLen:ne,blkLen:Xe,blocks:ci,header:E,body:T}},packWitness:(g,A)=>m(g,A),splitWitnessBlocks:p}}var W=Object.freeze({SIMPLE_SIG:"simpleSig",V1:"v1",COMPACT_V1:"compactV1"});function Si(s){if(s==null)return W.COMPACT_V1;if(s===W.SIMPLE_SIG||s===W.V1)return W.SIMPLE_SIG;if(s===W.COMPACT_V1||s==="compact")return W.COMPACT_V1;throw new M(N.ULDA_CONFIG_INVALID,"unknown codec pack",{operation:"normalizeCodecPack",details:{pack:s}})}function ki(s={}){let{pack:e,encoder:t,decoder:i,getExportFormat:n,getOriginSize:r}=s,a=Si(e);return a===W.COMPACT_V1?{id:a,codec:Ti({encoder:t,decoder:i,getExportFormat:n,getOriginSize:r})}:{id:W.SIMPLE_SIG,codec:Ei({encoder:t,decoder:i,getExportFormat:n,getOriginSize:r})}}var Ii="1",Li="hex",le=Object.freeze({N:5,mode:"S",hash:"SHA-256",originSize:256,pack:"compactV1",ageBytes:4}),cs=Object.freeze({mode:Object.freeze({S:1,X:2}),algorithm:Object.freeze({"SHA-1":1,"SHA-256":2,"SHA-384":3,"SHA-512":4,"SHA3-256":5,"SHA3-512":6,BLAKE3:7,WHIRLPOOL:8,CUSTOM:255})});function Ci(){return{mode:{...cs.mode},algorithm:{...cs.algorithm}}}function Di(s){return{mode:Object.fromEntries(Object.entries(s.mode).map(([e,t])=>[t,e])),algorithm:Object.fromEntries(Object.entries(s.algorithm).map(([e,t])=>[t,e]))}}function Ri(s={}){let e=s?.sign?.ageBytes??le.ageBytes;if(e!==4)throw new M(N.ULDA_CONFIG_INVALID,"invalid ageBytes",{operation:"normalizeConfig",details:{ageBytes:e}});return{version:s.version??Ii,fmt:{export:s?.fmt?.export??Li},sign:{N:s?.sign?.N??le.N,mode:s?.sign?.mode??le.mode,hash:s?.sign?.hash??le.hash,originSize:s?.sign?.originSize??le.originSize,pack:s?.sign?.pack??le.pack,ageBytes:e},externalHashers:s.externalHashers??{}}}function Bi(s){let{cfg:e,config:t,encoder:i,decoder:n}=s,r=e.sign??{};if(typeof r.func!="function")return;let a=r.hash??"CUSTOM";return r.hash||(t.sign.hash=a),t.externalHashers[a]={fn:r.func,output:r.output??"bytes",size:r.originSize??null,cdn:r.cdn??null,ready:!0},a in i.algorithm||(i.algorithm[a]=255),i.algorithm[a]===255&&(n.algorithm[255]=a),{id:a}}var vi=Object.freeze(["SHA-1","SHA-256","SHA-384","SHA-512"]);function Ui(s={}){let{externalHashers:e={},loadScriptOnce:t,cryptoImpl:i=globalThis.crypto}=s,n=async(a,o="SHA-256")=>{if(vi.includes(o))return new Uint8Array(await i.subtle.digest(o,a));let h=e[o];if(!h)throw new M(N.ULDA_HASHER_NOT_REGISTERED,`Hasher <${o}> not registered`,{operation:"hash",details:{hash:o}});h.cdn&&!h.ready&&(await t(h.cdn),h.ready=!0);let d=await h.fn(a),l=h.output??"bytes",f=l==="bytes"?d:l==="hex"?Qe(d):l==="base64"?et(d):(()=>{throw new M(N.ULDA_HASHER_OUTPUT_UNSUPPORTED,`Unsupported output ${l}`,{operation:"hash",details:{hash:o,output:l}})})();if(h.size&&f.length*8!==h.size)throw new M(N.ULDA_HASHER_SIZE_MISMATCH,`Hasher <${o}> size mismatch`,{operation:"hash",details:{hash:o,expectedSize:h.size,actualSize:f.length*8}});return f};return{hash:n,hashIter:async(a,o,h="SHA-256")=>{let d=a;for(let l=0;l<o;l++)d=await n(d,h);return d}}}function Pi(s={}){let{cryptoImpl:e=globalThis.crypto}=s;return{randomBytes:i=>{if(!e||typeof e.getRandomValues!="function")throw new M(N.ULDA_RANDOM_UNAVAILABLE,"Random source unavailable",{operation:"randomBytes",details:{requestedLength:i}});return e.getRandomValues(new Uint8Array(i))}}}var Je={id:"S",ladder:async(s,e)=>{let t=[];for(let i=0;i<s.length;i++)t.push(await e.hashIter(s[i],i,e.alg));return{sigBlocks:t,final:t.at(-1)}},verify:async(s,e,t)=>{let i=e.index-s.index;if(i<=0n||i>=BigInt(s.N))return!1;let n=Number(i);if(s.originLen!==e.originLen||s.blkLen!==e.blkLen)return!1;let r=t.splitWitnessBlocks(s),a=t.splitWitnessBlocks(e);for(let o=0;o<s.N-n;o++)if(!t.equalBytes(await t.hashIter(a[o],n,s.alg),r[o+n]))return!1;return!0}},Ze={id:"X",ladder:async(s,e)=>{if(!s?.length)throw new M(N.ULDA_MODE_EMPTY_BLOCKS,"_ladderX: empty blocks",{operation:"ladderX",details:{mode:"X"}});let t=[s[0]],i=s;for(let n=1;n<s.length;n++){let r=[];for(let a=0;a<i.length-1;a++)r.push(await e.hash(e.concatBytes(i[a],i[a+1]),e.alg));t.push(r[0]),i=r}return{sigBlocks:t,final:t.at(-1)}},verify:async(s,e,t)=>{if(e.index-s.index!==1n)return!1;let{N:i}=s;if(s.sigBytes.length!==e.sigBytes.length||s.sigBytes.length%i)return!1;let n=t.splitWitnessBlocks(s),r=t.splitWitnessBlocks(e);for(let a=1;a<i;a++)if(!t.equalBytes(await t.hash(t.concatBytes(n[a-1],r[a-1]),s.alg),n[a]))return!1;return!0}},Nn=Object.freeze({S:Je,X:Ze});function xi(s){let{N:e,originSize:t,randomBytes:i}=s,n=t>>>3;return{origin:Array.from({length:e},()=>i(n))}}async function Mi(s,e){let{modes:t,hash:i,hashIter:n,concatBytes:r}=e,a=s.mode==="X"?t.X:t.S,{sigBlocks:o}=await a.ladder(s.origin,{hash:i,hashIter:n,concatBytes:r,alg:s.alg});return{sigBytes:r(...o),sigBlocks:o,index:s.index,N:s.N,mode:s.mode,alg:s.alg}}function Fi(s,e){let{randomBytes:t}=e,i=s.origin.slice(1);return i.push(t(s.blockLen)),{origin:i,index:s.index+1n}}async function Vi(s,e,t){let{modes:i,hash:n,hashIter:r,concatBytes:a,equalBytes:o,splitWitnessBlocks:h}=t;if(s.N!==e.N||s.mode!==e.mode||s.alg!==e.alg||e.index<=s.index)return!1;let d={hash:n,hashIter:r,concatBytes:a,equalBytes:o,splitWitnessBlocks:h};return s.mode==="S"?i.S.verify(s,e,d):s.mode==="X"?i.X.verify(s,e,d):!1}function Ki(s){let{config:e,codec:t,modes:i,hash:n,hashIter:r,randomBytes:a,concatBytes:o,equalBytes:h}=s,d=y=>a(y),l=()=>xi({N:e.sign.N,originSize:e.sign.originSize,randomBytes:d});return{randomBlock:d,originGenerator:l,newOriginPackage:(y=0n)=>t.encodeOrigin(l(),y,{N:e.sign.N,mode:e.sign.mode,hash:e.sign.hash,ageBytes:e.sign.ageBytes}),stepUpPackage:y=>{let g=t.decodeOrigin(y),A=Fi(g,{randomBytes:d});return t.encodeOrigin({origin:A.origin},A.index,{N:e.sign.N,mode:e.sign.mode,hash:e.sign.hash,ageBytes:e.sign.ageBytes})},signPackage:async y=>{let g=t.decodeOrigin(y),A=await Mi(g,{modes:i,hash:n,hashIter:r,concatBytes:o});return t.packWitness(A.sigBytes,{index:A.index,N:A.N,mode:A.mode,alg:A.alg,ageBytes:e.sign.ageBytes})},verifyPackages:async(y,g)=>{let A=t.decodeWitness(y),E=t.decodeWitness(g);return Vi(A,E,{modes:i,hash:n,hashIter:r,concatBytes:o,equalBytes:h,splitWitnessBlocks:t.splitWitnessBlocks})}}}var Hi=class ms{constructor(e={}){let t=this.globalConfig=Ri(e);this.externalHashers=t.externalHashers,this.encoder=Ci(),this.decoder=Di(this.encoder),Bi({cfg:e,config:t,encoder:this.encoder,decoder:this.decoder});let i=ki({pack:t.sign.pack,encoder:this.encoder,decoder:this.decoder,getExportFormat:()=>t.fmt.export,getOriginSize:()=>t.sign.originSize});this.codecPack=i.id;let n=this.codec=i.codec,r=this.convert={bytesToHex:bt,hexToBytes:Qe,bytesToBase64:hs,base64ToBytes:et,guessToBytes:ds,indexToBytes:Nt,concatBytes:Se,equalBytes:li,export:l=>ke(l,t.fmt.export),importToBytes:l=>Ie(l,t.fmt.export),splitSig:l=>n.splitWitnessBlocks(l)},a=this.hashProvider=Ui({externalHashers:t.externalHashers,loadScriptOnce:ms.loadScriptOnce,cryptoImpl:globalThis.crypto}),o=this.randomProvider=Pi({cryptoImpl:globalThis.crypto}),h=this.enc={hash:a.hash,hashIter:a.hashIter,ladder:async(l,f="S",p="SHA-256")=>f==="X"?h._ladderX(l,p):h._ladderS(l,p),_ladderS:async(l,f)=>Je.ladder(l,{hashIter:h.hashIter,alg:f}),_ladderX:async(l,f="SHA-256")=>Ze.ladder(l,{hash:h.hash,concatBytes:r.concatBytes,alg:f})},d=this.operations=Ki({config:t,codec:n,modes:{S:Je,X:Ze},hash:h.hash,hashIter:h.hashIter,randomBytes:l=>o.randomBytes(l),concatBytes:r.concatBytes,equalBytes:r.equalBytes});this.actions={Sign:l=>d.signPackage(l),VerifyS:async(l,f)=>Je.verify(l,f,{hashIter:h.hashIter,equalBytes:r.equalBytes,splitWitnessBlocks:r.splitSig}),VerifyX:async(l,f)=>Ze.verify(l,f,{hash:h.hash,concatBytes:r.concatBytes,equalBytes:r.equalBytes,splitWitnessBlocks:r.splitSig}),Verify:(l,f)=>d.verifyPackages(l,f),import:{signature:l=>n.decodeWitness(l),origin:l=>n.decodeOrigin(l)},OriginGenerator:()=>d.originGenerator(),RandomBlock:l=>d.randomBlock(l),_hdr:(l,f,p,m)=>{if(typeof n.makeHeader=="function")return n.makeHeader(l,f,p,m);throw new M(N.ULDA_CONFIG_INVALID,"Legacy v1 header is not available for compactV1",{operation:"actions._hdr",details:{pack:this.codecPack}})},NewExporter:(l,f=0n)=>{let{N:p,mode:m,hash:u}=t.sign;return n.encodeOrigin(l,f,{N:p,mode:m,hash:u,ageBytes:t.sign.ageBytes})},SignExporter:(l,f,p,m,u)=>n.encodeWitness(l,{index:f,N:p,mode:m,hash:u,ageBytes:t.sign.ageBytes}),PackSignature:(l,f)=>n.packWitness(l,f),StepUp:l=>d.stepUpPackage(l)}}static loadScriptOnce(e){return new Promise((t,i)=>{if(document.querySelector(`script[src="${e}"]`))return t();let n=document.createElement("script");n.src=e,n.onload=t,n.onerror=i,document.head.appendChild(n)})}New(e=0n){return this.operations.newOriginPackage(e)}stepUp(e){return this.operations.stepUpPackage(e)}sign(e){return this.operations.signPackage(e)}verify(e,t){return this.operations.verifyPackages(e,t)}},_s=Hi;var fe=Object.fromEntries(["X","S"].map(s=>[s,new _s({fmt:{export:"bytes"},sign:{mode:s,N:5,hash:"SHA-256",originSize:256,pack:"compactV1"}})]));function V(s){try{c(s instanceof Uint8Array&&s.length>=163&&s.length<=167,"UNSUPPORTED_PROFILE");let e=fe.X.actions.import.signature(s);c(e.N===5&&e.alg==="SHA-256"&&(e.mode==="X"||e.mode==="S")&&e.body.length===160,"UNSUPPORTED_PROFILE");let t=fe[e.mode].codec.encodeWitness(e.body,{index:e.index,mode:e.mode,N:5,hash:"SHA-256"});return c(D(t,s),"UNSUPPORTED_PROFILE"),{mode:e.mode,age:Number(e.index),N:5}}catch{j("UNSUPPORTED_PROFILE")}}var It=s=>{let e=C(s,167);return{bytes:e,...V(e)}};function tt(s="X"){return c(s==="X"||s==="S"),fe[s].New()}function st(s){let e=V(s);return c(e.age<4294967295,"LIMIT"),fe[e.mode].stepUp(s)}async function Ce(s){let e=V(s);return fe[e.mode].sign(s)}async function it(s,e){let t=V(s),i=V(e);if(t.mode!==i.mode)return!1;try{return await fe[t.mode].verify(s,e)}catch{return!1}}var Es=new Uint8Array([85,76,68,2]),As=Q("ULDA-SDK/container/v2\0"),zi=Q("ULDA-SDK/content-key/v2"),Lt=new WeakMap,qi=6e5;function ue(){return c(globalThis.crypto?.subtle&&globalThis.crypto?.getRandomValues,"UNSUPPORTED"),globalThis.crypto.subtle}function ji(s){return c(typeof s=="string"&&s.length>0&&s.length<=1024),Q(s)}async function Yi(s,e){let t=ji(s);s=void 0;try{let i=await ue().importKey("raw",t,"PBKDF2",!1,["deriveKey"]);return t.fill(0),await ue().deriveKey({name:"PBKDF2",hash:"SHA-256",iterations:qi,salt:e},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(i){if(i instanceof b)throw i;j("CRYPTO_FAILED")}finally{t.fill(0)}}async function Ct(s,e=Oe(16)){c(e instanceof Uint8Array&&e.length===16);let t=Yi(s,e);return s=void 0,{salt:e.slice(),key:await t}}async function De(s,e=Oe(16)){c(e instanceof Uint8Array&&e.length===16);let t=re(s,32);s=void 0;try{c(t.length===32);let i=await ue().importKey("raw",t,"HKDF",!1,["deriveKey"]);return t.fill(0),{salt:e.slice(),key:await ue().deriveKey({name:"HKDF",hash:"SHA-256",salt:e,info:zi},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}}catch(i){if(i instanceof b)throw i;j("CRYPTO_FAILED")}finally{t.fill(0)}}function ws(){let s=Oe(32);try{return Ge(s)}finally{s.fill(0)}}function Os(s){let e=re(s,32);try{c(e.length===32)}finally{e.fill(0)}}var Dt=ws,nt=ws;function ee(s){let e=C(s,_.resourceBytes);return c(e.length>=48&&D(e.subarray(0,4),Es),"INVALID_PACKET"),{bytes:e,salt:e.slice(4,20),nonce:e.slice(20,32),ciphertext:e.subarray(32),header:e.subarray(0,20)}}async function Re(s,e,t,i,n=!1){Os(e);let r=await Ce(t);c(s.salt instanceof Uint8Array&&s.salt.length===16);let a=we(Es,s.salt),o=Oe(12),h=Q(JSON.stringify({token:e,origin:Ge(t),data:U(i,n)}));try{c(h.length<=(n?_.resourceBytes:_.payloadBytes)-48,"LIMIT");let d=new Uint8Array(await ue().encrypt({name:"AES-GCM",iv:o,additionalData:we(As,a,r),tagLength:128},s.key,h)),l=Object.freeze(Object.create(null));return Lt.set(l,Object.freeze({witness:r,payload:we(a,o,d)})),l}catch(d){if(d?.code==="LIMIT")throw d;j("CRYPTO_FAILED")}finally{h.fill(0)}}function X(s){c(Lt.has(s),"INVALID_PACKET");let{witness:e,payload:t}=Lt.get(s);return Object.freeze({witness:e.slice(),payload:t.slice()})}async function bs(s,e,t,i=!1){let n,r,a=!1;try{let o=C(e.witness,167);V(o);let h=ee(e.payload);c(D(h.salt,s.salt)),n=new Uint8Array(await ue().decrypt({name:"AES-GCM",iv:h.nonce,additionalData:we(As,h.header,o),tagLength:128},s.key,h.ciphertext));let d=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n));I(d,["token","origin","data"]),Os(d.token),c(t===void 0||d.token===t),r=re(d.origin,167),V(r),c(D(await Ce(r),o));let l={origin:r,token:d.token,data:U(d.data,i),witness:o,record:Object.freeze({id:e.id,witness:e.witness,payload:e.payload}),...V(o)};return a=!0,l}catch{j("CRYPTO_FAILED")}finally{n?.fill(0),a||r?.fill(0)}}var Rt=new WeakMap,Bt=new WeakMap,Wi=new Set(["hello","read","create","update","delete","session.close"]),rt=(s,e)=>{let t=Object.freeze(Object.create(null));return Rt.set(t,{action:s,body:e}),t};function pe(s,e=!1){c(Array.isArray(s)&&s.length>0&&s.length<=(e?Math.floor(_.transferBytes/256):_.batch),"INVALID_PACKET")}function oe(s,e=!1){pe(s,e),s.forEach(P),c(new Set(s).size===s.length,"INVALID_PACKET")}function Be(s,e=!1){let t=e?s.length*256:0;for(let i of s)t+=C(i?.witness,167).byteLength,Object.hasOwn(i,"payload")&&(t+=C(i.payload,e?_.resourceBytes:_.payloadBytes).byteLength),c(t<=(e?_.transferBytes:_.messageBytes),"LIMIT")}function vt(s){return c(s==="hello"||s==="session.close"),rt(s,{})}function ye(s){return oe(s),rt("read",[...s])}function ae(s,e){c(s==="create"||s==="update"),pe(e,!0),s==="update"&&oe(e.map(i=>i.id),!0);let t=e.map(i=>s==="create"?{...X(i.sealed)}:{id:P(i.id),...X(i.sealed)});return rt(s,t)}async function Ut(s,e){P(s);let t=Object.freeze(Object.create(null)),i=st(e);try{Bt.set(t,{id:s,witness:await Ce(i)})}finally{i.fill(0)}return t}function Pt(s,e=[]){pe(s,!0);let t=s.map(i=>(c(Bt.has(i),"INVALID_PACKET"),{...Bt.get(i)}));c(Array.isArray(e),"INVALID_PACKET");for(let i of e)t.push({id:P(i.id),...X(i.sealed)});return pe(t,!0),Be(t,!0),oe(t.map(i=>i.id),!0),rt("delete",t)}function Ns(s){c(Rt.has(s),"INVALID_PACKET");let{action:e,body:t}=Rt.get(s);return{action:e,body:Array.isArray(t)?t.map(i=>typeof i=="string"?i:{...i.id===void 0?{}:{id:i.id},witness:C(i.witness,167).slice(),...i.payload===void 0?{}:{payload:C(i.payload,_.resourceBytes).slice()}}):{}}}function ot(s){return I(s,["id","witness","payload"]),P(s.id),It(s.witness),ee(s.payload),Object.freeze({id:s.id,witness:C(s.witness,167).slice(),payload:C(s.payload,_.resourceBytes).slice()})}function Ts(s,e,t=!1){if(c(Wi.has(s),"INVALID_PACKET"),s==="hello"||s==="session.close"){I(e,[]);return}if(s==="read"){oe(e);return}pe(e,t),s!=="delete"||c(e.some(i=>!Object.hasOwn(i,"payload")),"INVALID_PACKET"),Be(e,t),s!=="create"&&oe(e.map(i=>i.id),t),e.forEach(i=>{I(i,s==="create"?["witness","payload"]:s==="update"?["id","witness","payload"]:Object.hasOwn(i,"payload")?["id","witness","payload"]:["id","witness"]),It(i.witness),(s!=="delete"||Object.hasOwn(i,"payload"))&&ee(i.payload)})}function ve(s,e,t,i=!1){if(c(t&&typeof t=="object"&&!Array.isArray(t),"INVALID_PACKET"),t.ok===!1){I(t,Object.hasOwn(t,"id")?["ok","error","id"]:["ok","error"]),Object.hasOwn(t,"id")&&P(t.id);let n={conflict:"CONFLICT",not_found:"NOT_FOUND",too_large:"LIMIT",unsupported_profile:"UNSUPPORTED_PROFILE",invalid_witness:"CONFLICT"};j(typeof t.error=="string"&&Object.hasOwn(n,t.error)?n[t.error]:"SERVER_ERROR")}if(c(t.ok===!0,"INVALID_PACKET"),s==="read"||s==="create"){if(I(t,["ok","data"]),pe(t.data,i),c(t.data.length===e.length,"INVALID_PACKET"),s==="create")return oe(t.data,i),[...t.data];Be(t.data);let n=t.data.map(ot);return oe(n.map(r=>r.id)),c(n.every(r=>e.includes(r.id)),"INVALID_PACKET"),n}I(t,["ok"])}function xt(s,e=!1){c(s&&typeof s=="object","INVALID_PACKET"),I(s,["updated","deleted"].filter(o=>Object.hasOwn(s,o)));let t=s.updated??[],i=s.deleted??[];c(Array.isArray(t)&&Array.isArray(i)&&t.length+i.length<=(e?Math.floor(_.transferBytes/256):_.batch),"INVALID_PACKET"),Be(t,e);let n=t.map(ot),r=i.map(P),a=[...n.map(o=>o.id),...r];return c(a.length>0&&new Set(a).size===a.length,"INVALID_PACKET"),{updated:n,deleted:r}}var z=Object.create(null);z.open="0";z.close="1";z.ping="2";z.pong="3";z.message="4";z.upgrade="5";z.noop="6";var Ue=Object.create(null);Object.keys(z).forEach(s=>{Ue[z[s]]=s});var Pe={type:"error",data:"parser error"};var Is=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Ls=typeof ArrayBuffer=="function",Cs=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,xe=({type:s,data:e},t,i)=>Is&&e instanceof Blob?t?i(e):Ss(e,i):Ls&&(e instanceof ArrayBuffer||Cs(e))?t?i(e):Ss(new Blob([e]),i):i(z[s]+(e||"")),Ss=(s,e)=>{let t=new FileReader;return t.onload=function(){let i=t.result.split(",")[1];e("b"+(i||""))},t.readAsDataURL(s)};function ks(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}var Mt;function Ds(s,e){if(Is&&s.data instanceof Blob)return s.data.arrayBuffer().then(ks).then(e);if(Ls&&(s.data instanceof ArrayBuffer||Cs(s.data)))return e(ks(s.data));xe(s,!1,t=>{Mt||(Mt=new TextEncoder),e(Mt.encode(t))})}var Rs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Me=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<Rs.length;s++)Me[Rs.charCodeAt(s)]=s;var Bs=s=>{let e=s.length*.75,t=s.length,i,n=0,r,a,o,h;s[s.length-1]==="="&&(e--,s[s.length-2]==="="&&e--);let d=new ArrayBuffer(e),l=new Uint8Array(d);for(i=0;i<t;i+=4)r=Me[s.charCodeAt(i)],a=Me[s.charCodeAt(i+1)],o=Me[s.charCodeAt(i+2)],h=Me[s.charCodeAt(i+3)],l[n++]=r<<2|a>>4,l[n++]=(a&15)<<4|o>>2,l[n++]=(o&3)<<6|h&63;return d};var Xi=typeof ArrayBuffer=="function",Fe=(s,e)=>{if(typeof s!="string")return{type:"message",data:vs(s,e)};let t=s.charAt(0);return t==="b"?{type:"message",data:Gi(s.substring(1),e)}:Ue[t]?s.length>1?{type:Ue[t],data:s.substring(1)}:{type:Ue[t]}:Pe},Gi=(s,e)=>{if(Xi){let t=Bs(s);return vs(t,e)}else return{base64:!0,data:s}},vs=(s,e)=>{switch(e){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}};var Us="",Ps=(s,e)=>{let t=s.length,i=new Array(t),n=0;s.forEach((r,a)=>{xe(r,!1,o=>{i[a]=o,++n===t&&e(i.join(Us))})})},xs=(s,e)=>{let t=s.split(Us),i=[];for(let n=0;n<t.length;n++){let r=Fe(t[n],e);if(i.push(r),r.type==="error")break}return i};function Ms(){return new TransformStream({transform(s,e){Ds(s,t=>{let i=t.length,n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);let r=new DataView(n.buffer);r.setUint8(0,126),r.setUint16(1,i)}else{n=new Uint8Array(9);let r=new DataView(n.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(i))}s.data&&typeof s.data!="string"&&(n[0]|=128),e.enqueue(n),e.enqueue(t)})}})}var Ft;function at(s){return s.reduce((e,t)=>e+t.length,0)}function ct(s,e){if(s[0].length===e)return s.shift();let t=new Uint8Array(e),i=0;for(let n=0;n<e;n++)t[n]=s[0][i++],i===s[0].length&&(s.shift(),i=0);return s.length&&i<s[0].length&&(s[0]=s[0].slice(i)),t}function Fs(s,e){Ft||(Ft=new TextDecoder);let t=[],i=0,n=-1,r=!1;return new TransformStream({transform(a,o){for(t.push(a);;){if(i===0){if(at(t)<1)break;let h=ct(t,1);r=(h[0]&128)===128,n=h[0]&127,n<126?i=3:n===126?i=1:i=2}else if(i===1){if(at(t)<2)break;let h=ct(t,2);n=new DataView(h.buffer,h.byteOffset,h.length).getUint16(0),i=3}else if(i===2){if(at(t)<8)break;let h=ct(t,8),d=new DataView(h.buffer,h.byteOffset,h.length),l=d.getUint32(0);if(l>Math.pow(2,21)-1){o.enqueue(Pe);break}n=l*Math.pow(2,32)+d.getUint32(4),i=3}else{if(at(t)<n)break;let h=ct(t,n);o.enqueue(Fe(r?h:Ft.decode(h),e)),i=0}if(n===0||n>s){o.enqueue(Pe);break}}}})}var Vt=4;function k(s){if(s)return $i(s)}function $i(s){for(var e in k.prototype)s[e]=k.prototype[e];return s}k.prototype.on=k.prototype.addEventListener=function(s,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(e),this};k.prototype.once=function(s,e){function t(){this.off(s,t),e.apply(this,arguments)}return t.fn=e,this.on(s,t),this};k.prototype.off=k.prototype.removeListener=k.prototype.removeAllListeners=k.prototype.removeEventListener=function(s,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+s];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var i,n=0;n<t.length;n++)if(i=t[n],i===e||i.fn===e){t.splice(n,1);break}return t.length===0&&delete this._callbacks["$"+s],this};k.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+s],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(t){t=t.slice(0);for(var i=0,n=t.length;i<n;++i)t[i].apply(this,e)}return this};k.prototype.emitReserved=k.prototype.emit;k.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};k.prototype.hasListeners=function(s){return!!this.listeners(s).length};var G=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),F=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Vs="arraybuffer";function ht(s,...e){return e.reduce((t,i)=>(s.hasOwnProperty(i)&&(t[i]=s[i]),t),{})}var Ji=F.setTimeout,Zi=F.clearTimeout;function $(s,e){e.useNativeTimers?(s.setTimeoutFn=Ji.bind(F),s.clearTimeoutFn=Zi.bind(F)):(s.setTimeoutFn=F.setTimeout.bind(F),s.clearTimeoutFn=F.clearTimeout.bind(F))}var Qi=1.33;function Ks(s){return typeof s=="string"?en(s):Math.ceil((s.byteLength||s.size)*Qi)}function en(s){let e=0,t=0;for(let i=0,n=s.length;i<n;i++)e=s.charCodeAt(i),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(i++,t+=4);return t}function dt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Hs(s){let e="";for(let t in s)s.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(s[t]));return e}function zs(s){let e={},t=s.split("&");for(let i=0,n=t.length;i<n;i++){let r=t[i].split("=");e[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return e}var lt=class extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}},J=class extends k{constructor(e){super(),this.writable=!1,$(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,i){return super.emitReserved("error",new lt(e,t,i)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=Fe(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=Hs(e);return t.length?"?"+t:""}};var Ve=class extends J{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let i=0;this._polling&&(i++,this.once("pollComplete",function(){--i||t()})),this.writable||(i++,this.once("drain",function(){--i||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=i=>{if(this.readyState==="opening"&&i.type==="open"&&this.onOpen(),i.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(i)};xs(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){let e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Ps(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=dt()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}};var qs=!1;try{qs=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var js=qs;function tn(){}var Kt=class extends Ve{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",i=location.port;i||(i=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||i!==e.port}}doWrite(e,t){let i=this.request({method:"POST",data:e});i.on("success",t),i.on("error",(n,r)=>{this.onError("xhr post error",n,r)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,i)=>{this.onError("xhr poll error",t,i)}),this.pollXhr=e}},te=class s extends k{constructor(e,t,i){super(),this.createRequest=e,$(this,i),this._opts=i,this._method=i.method||"GET",this._uri=t,this._data=i.data!==void 0?i.data:null,this._create()}_create(){var e;let t=ht(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let i=this._xhr=this.createRequest(t);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&i.setRequestHeader(n,this._opts.extraHeaders[n])}}catch{}if(this._method==="POST")try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{i.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var n;i.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.parseCookies(i.getResponseHeader("set-cookie"))),i.readyState===4&&(i.status===200||i.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof i.status=="number"?i.status:0)},0))},i.send(this._data)}catch(n){this.setTimeoutFn(()=>{this._onError(n)},0);return}typeof document<"u"&&(this._index=s.requestsCount++,s.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=tn,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete s.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};te.requestsCount=0;te.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ys);else if(typeof addEventListener=="function"){let s="onpagehide"in F?"pagehide":"unload";addEventListener(s,Ys,!1)}}function Ys(){for(let s in te.requests)te.requests.hasOwnProperty(s)&&te.requests[s].abort()}var sn=(function(){let s=Ws({xdomain:!1});return s&&s.responseType!==null})(),se=class extends Kt{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=sn&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new te(Ws,this.uri(),e)}};function Ws(s){let e=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||js))return new XMLHttpRequest}catch{}if(!e)try{return new F[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Xs=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",zt=class extends J{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,i=Xs?{}:ht(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}catch(n){return this.emitReserved("error",n)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],n=t===e.length-1;xe(i,this.supportsBinary,r=>{try{this.doWrite(i,r)}catch{}n&&G(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=dt()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Ht=F.WebSocket||F.MozWebSocket,ie=class extends zt{createSocket(e,t,i){return Xs?new Ht(e,t,i):t?new Ht(e,t):new Ht(e)}doWrite(e,t){this.ws.send(t)}};var ge=class extends J{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Fs(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),n=Ms();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();let r=()=>{i.read().then(({done:o,value:h})=>{o||(this.onPacket(h),r())}).catch(o=>{})};r();let a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let i=e[t],n=t===e.length-1;this._writer.write(i).then(()=>{n&&G(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}};var qt={websocket:ie,webtransport:ge,polling:se};var nn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,rn=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function me(s){if(s.length>8e3)throw"URI too long";let e=s,t=s.indexOf("["),i=s.indexOf("]");t!=-1&&i!=-1&&(s=s.substring(0,t)+s.substring(t,i).replace(/:/g,";")+s.substring(i,s.length));let n=nn.exec(s||""),r={},a=14;for(;a--;)r[rn[a]]=n[a]||"";return t!=-1&&i!=-1&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=on(r,r.path),r.queryKey=an(r,r.query),r}function on(s,e){let t=/\/{2,9}/g,i=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&i.splice(0,1),e.slice(-1)=="/"&&i.splice(i.length-1,1),i}function an(s,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,n,r){n&&(t[n]=r)}),t}var jt=typeof addEventListener=="function"&&typeof removeEventListener=="function",ft=[];jt&&addEventListener("offline",()=>{ft.forEach(s=>s())},!1);var ce=class s extends k{constructor(e,t){if(super(),this.binaryType=Vs,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let i=me(e);t.hostname=i.host,t.secure=i.protocol==="https"||i.protocol==="wss",t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=me(t.host).host);$(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(i=>{let n=i.prototype.name;this.transports.push(n),this._transportsByName[n]=i}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=zs(this.opts.query)),jt&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ft.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=Vt,t.transport=e,this.id&&(t.sid=this.id);let i=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](i)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&s.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",s.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let i=0;i<this.writeBuffer.length;i++){let n=this.writeBuffer[i].data;if(n&&(t+=Ks(n)),i>0&&t>this._maxPayload)return this.writeBuffer.slice(0,i);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,G(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,i){return this._sendPacket("message",e,t,i),this}send(e,t,i){return this._sendPacket("message",e,t,i),this}_sendPacket(e,t,i,n){if(typeof t=="function"&&(n=t,t=void 0),typeof i=="function"&&(n=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;let r={type:e,data:t,options:i};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),n&&this.once("flush",n),this.flush()}close(){let e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():e()}):this.upgrading?i():e()),this}_onError(e){if(s.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),jt&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let i=ft.indexOf(this._offlineEventListener);i!==-1&&ft.splice(i,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};ce.protocol=Vt;var ut=class extends ce{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),i=!1;ce.priorWebsocketSuccess=!1;let n=()=>{i||(t.send([{type:"ping",data:"probe"}]),t.once("packet",f=>{if(!i)if(f.type==="pong"&&f.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ce.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{i||this.readyState!=="closed"&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let p=new Error("probe error");p.transport=t.name,this.emitReserved("upgradeError",p)}}))};function r(){i||(i=!0,l(),t.close(),t=null)}let a=f=>{let p=new Error("probe error: "+f);p.transport=t.name,r(),this.emitReserved("upgradeError",p)};function o(){a("transport closed")}function h(){a("socket closed")}function d(f){t&&f.name!==t.name&&r()}let l=()=>{t.removeListener("open",n),t.removeListener("error",a),t.removeListener("close",o),this.off("close",h),this.off("upgrading",d)};t.once("open",n),t.once("error",a),t.once("close",o),this.once("close",h),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}},_e=class extends ut{constructor(e,t={}){let i=typeof e=="object",n=i?{...e}:{...t};(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(r=>qt[r]).filter(r=>!!r)),super(i?n:e,n)}};var qr=_e.protocol;function Gs(s,e="",t){let i=s;t=t||typeof location<"u"&&location,s==null&&(s=t.protocol+"//"+t.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=t.protocol+s:s=t.host+s),/^(https?|wss?):\/\//.test(s)||(typeof t<"u"?s=t.protocol+"//"+s:s="https://"+s),i=me(s)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";let r=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+r+":"+i.port+e,i.href=i.protocol+"://"+r+(t&&t.port===i.port?"":":"+i.port),i}var Xt={};di(Xt,{Decoder:()=>qe,Encoder:()=>ze,PacketType:()=>w,isPacketValid:()=>gn,protocol:()=>gt});var hn=typeof ArrayBuffer=="function",dn=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,$s=Object.prototype.toString,ln=typeof Blob=="function"||typeof Blob<"u"&&$s.call(Blob)==="[object BlobConstructor]",fn=typeof File=="function"||typeof File<"u"&&$s.call(File)==="[object FileConstructor]";function He(s){return hn&&(s instanceof ArrayBuffer||dn(s))||ln&&s instanceof Blob||fn&&s instanceof File}function Ke(s,e){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let t=0,i=s.length;t<i;t++)if(Ke(s[t]))return!0;return!1}if(He(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return Ke(s.toJSON(),!0);for(let t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&Ke(s[t]))return!0;return!1}function Js(s){let e=[],t=s.data,i=s;return i.data=pt(t,e),i.attachments=e.length,{packet:i,buffers:e}}function pt(s,e,t){if(!s)return s;if(He(s)){let i={_placeholder:!0,num:e.length};return e.push(s),i}else if(Array.isArray(s)){let i=new Array(s.length);for(let n=0;n<s.length;n++)i[n]=pt(s[n],e);return i}else if(typeof s=="object"&&!(s instanceof Date)){if(s.toJSON&&typeof s.toJSON=="function"&&!t)return pt(s.toJSON(),e,!0);let i={};for(let n in s)Object.prototype.hasOwnProperty.call(s,n)&&(i[n]=pt(s[n],e));return i}return s}function Zs(s,e){return s.data=Yt(s.data,e),delete s.attachments,s}function Yt(s,e){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<e.length)return e[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let t=0;t<s.length;t++)s[t]=Yt(s[t],e);else if(typeof s=="object")for(let t in s)Object.prototype.hasOwnProperty.call(s,t)&&(s[t]=Yt(s[t],e));return s}var Qs=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],gt=5,w;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(w||(w={}));var ze=class{constructor(e){this.replacer=e}encode(e){return(e.type===w.EVENT||e.type===w.ACK)&&Ke(e)?this.encodeAsBinary({type:e.type===w.EVENT?w.BINARY_EVENT:w.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===w.BINARY_EVENT||e.type===w.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=Js(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}},qe=class s extends k{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let i=t.type===w.BINARY_EVENT;i||t.type===w.BINARY_ACK?(t.type=i?w.EVENT:w.ACK,this.reconstructor=new Wt(t)):super.emitReserved("decoded",t)}else if(He(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,i={type:Number(e.charAt(0))};if(w[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===w.BINARY_EVENT||i.type===w.BINARY_ACK){let r=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let a=e.substring(r,t);if(a!=Number(a)||e.charAt(t)!=="-")throw new Error("Illegal attachments");let o=Number(a);if(!ei(o)||o<1)throw new Error("Illegal attachments");if(o>this.opts.maxAttachments)throw new Error("too many attachments");i.attachments=o}if(e.charAt(t+1)==="/"){let r=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););i.nsp=e.substring(r,t)}else i.nsp="/";let n=e.charAt(t+1);if(n!==""&&Number(n)==n){let r=t+1;for(;++t;){let a=e.charAt(t);if(a==null||Number(a)!=a){--t;break}if(t===e.length)break}i.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){let r=this.tryParse(e.substr(t));if(s.isPayloadValid(i.type,r))i.data=r;else throw new Error("invalid payload")}return i}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case w.CONNECT:return yt(t);case w.DISCONNECT:return t===void 0;case w.CONNECT_ERROR:return typeof t=="string"||yt(t);case w.EVENT:case w.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Qs.indexOf(t[0])===-1);case w.ACK:case w.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},Wt=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=Zs(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function un(s){return typeof s=="string"}var ei=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function pn(s){return s===void 0||ei(s)}function yt(s){return Object.prototype.toString.call(s)==="[object Object]"}function yn(s,e){switch(s){case w.CONNECT:return e===void 0||yt(e);case w.DISCONNECT:return e===void 0;case w.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Qs.indexOf(e[0])===-1);case w.ACK:return Array.isArray(e);case w.CONNECT_ERROR:return typeof e=="string"||yt(e);default:return!1}}function gn(s){return un(s.nsp)&&pn(s.id)&&yn(s.type,s.data)}function K(s,e,t){return s.on(e,t),function(){s.off(e,t)}}var mn=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ee=class extends k{constructor(e,t,i){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[K(e,"open",this.onopen.bind(this)),K(e,"packet",this.onpacket.bind(this)),K(e,"error",this.onerror.bind(this)),K(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var i,n,r;if(mn.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:w.EVENT,data:t};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let l=this.ids++,f=t.pop();this._registerAckCallback(l,f),a.id=l}let o=(n=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||n===void 0?void 0:n.writable,h=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!o||(h?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(e,t){var i;let n=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(n===void 0){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let o=0;o<this.sendBuffer.length;o++)this.sendBuffer[o].id===e&&this.sendBuffer.splice(o,1);t.call(this,new Error("operation has timed out"))},n),a=(...o)=>{this.io.clearTimeoutFn(r),t.apply(this,o)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((i,n)=>{let r=(a,o)=>a?n(a):i(o);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((n,...r)=>i!==this._queue[0]?void 0:(n!==null?i.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(n)):(this._queue.shift(),t&&t(null,...r)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:w.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(i=>String(i.id)===e)){let i=this.acks[e];delete this.acks[e],i.withError&&i.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case w.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case w.EVENT:case w.BINARY_EVENT:this.onevent(e);break;case w.ACK:case w.BINARY_ACK:this.onack(e);break;case w.DISCONNECT:this.ondisconnect();break;case w.CONNECT_ERROR:this.destroy();let i=new Error(e.data.message);i.data=e.data.data,this.emitReserved("connect_error",i);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let i of t)i.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,i=!1;return function(...n){i||(i=!0,t.packet({type:w.ACK,id:e,data:n}))}}onack(e){let t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:w.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let i of t)i.apply(this,e.data)}}};function he(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}he.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*s);s=(Math.floor(e*10)&1)==0?s-t:s+t}return Math.min(s,this.max)|0};he.prototype.reset=function(){this.attempts=0};he.prototype.setMin=function(s){this.ms=s};he.prototype.setMax=function(s){this.max=s};he.prototype.setJitter=function(s){this.jitter=s};var Ae=class extends k{constructor(e,t){var i;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,$(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((i=t.randomizationFactor)!==null&&i!==void 0?i:.5),this.backoff=new he({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let n=t.parser||Xt;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new _e(this.uri,this.opts);let t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;let n=K(t,"open",function(){i.onopen(),e&&e()}),r=o=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",o),e?e(o):this.maybeReconnectOnOpen()},a=K(t,"error",r);if(this._timeout!==!1){let o=this._timeout,h=this.setTimeoutFn(()=>{n(),r(new Error("timeout")),t.close()},o);this.opts.autoUnref&&h.unref(),this.subs.push(()=>{this.clearTimeoutFn(h)})}return this.subs.push(n),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(K(e,"ping",this.onping.bind(this)),K(e,"data",this.ondata.bind(this)),K(e,"error",this.onerror.bind(this)),K(e,"close",this.onclose.bind(this)),K(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){G(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new Ee(this,e,t),this.nsps[e]=i),i}_destroy(e){let t=Object.keys(this.nsps);for(let i of t)if(this.nsps[i].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var i;this.cleanup(),(i=this.engine)===null||i===void 0||i.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let i=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(n=>{n?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",n)):e.onreconnect()}))},t);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}};var je={};function Ye(s,e){typeof s=="object"&&(e=s,s=void 0),e=e||{};let t=Gs(s,e.path||"/socket.io"),i=t.source,n=t.id,r=t.path,a=je[n]&&r in je[n].nsps,o=e.forceNew||e["force new connection"]||e.multiplex===!1||a,h;return o?h=new Ae(i,e):(je[n]||(je[n]=new Ae(i,e)),h=je[n]),t.query&&!e.query&&(e.query=t.queryKey),h.socket(t.path,e)}Object.assign(Ye,{Manager:Ae,Socket:Ee,io:Ye,connect:Ye});function ti(s){return s.length>_.batch||s.some(e=>(e.payload?.byteLength??0)>_.payloadBytes)||s.reduce((e,t)=>e+t.witness.byteLength+(t.payload?.byteLength??0),0)>_.messageBytes}function*si(s){let e=[],t=0;for(let i of s){let n=i.witness.byteLength+(i.payload?.byteLength??0);if(e.length&&(e.length===_.batch||t+n>_.messageBytes||n>_.payloadBytes)&&(yield{kind:"append",items:e},e=[],t=0),(i.payload?.byteLength??0)>_.payloadBytes)for(let r=0;r<i.payload.length;r+=_.jsonBytes)yield{kind:"part",...i.id===void 0?{}:{resourceId:i.id},witness:i.witness,total:i.payload.length,offset:r,payload:i.payload.subarray(r,r+_.jsonBytes)};else e.push(i),t+=n}e.length&&(yield{kind:"append",items:e})}var mt=class{#t=[];#s;#o;constructor(e){c(Number.isSafeInteger(e)&&e>0&&e*256<=_.transferBytes,"LIMIT"),this.count=e,this.#o=e*256}accept(e){if(c(this.#t.length<this.count,"INVALID_PACKET"),e.kind==="append"){I(e,["kind","items"]),c(!this.#s&&Array.isArray(e.items)&&e.items.length>0&&e.items.length<=_.batch,"INVALID_PACKET"),c(this.#t.length+e.items.length<=this.count,"INVALID_PACKET");let t=e.items.map(n=>{let r=Object.hasOwn(n,"payload");I(n,r?["id","witness","payload"]:["id"]);let a=r?C(n.witness,167):void 0,o=r?C(n.payload):void 0;return{id:P(n.id),...r?{witness:a,payload:o}:{}}}),i=t.reduce((n,r)=>n+(r.witness?.length??0)+(r.payload?.length??0),0);c(i<=_.messageBytes&&this.#o+i<=_.transferBytes,"LIMIT"),this.#o+=i;for(let n of t)this.#t.push({...n,...n.payload?{witness:n.witness.slice(),payload:n.payload.slice()}:{}})}else{I(e,["kind","resourceId","witness","total","offset","payload"]),c(e.kind==="part","INVALID_PACKET"),P(e.resourceId);let t=C(e.witness,167),i=C(e.payload,_.jsonBytes);c(Number.isSafeInteger(e.total)&&e.total>0&&e.total<=_.resourceBytes,"LIMIT"),c(Number.isSafeInteger(e.offset)&&e.offset>=0&&e.offset+i.length<=e.total,"INVALID_PACKET"),this.#s||(c(e.offset===0&&this.#o+e.total+t.length<=_.transferBytes,"LIMIT"),this.#o+=e.total+t.length,this.#s={id:e.resourceId,witness:t.slice(),payload:new Uint8Array(e.total),offset:0});let n=this.#s;c(n.id===e.resourceId&&n.offset===e.offset&&n.payload.length===e.total&&D(n.witness,t),"INVALID_PACKET"),n.payload.set(i,n.offset),n.offset+=i.length,n.offset===n.payload.length&&(this.#t.push({id:n.id,witness:n.witness,payload:n.payload}),this.#s=void 0)}}finish(){c(!this.#s&&this.#t.length===this.count,"INVALID_PACKET");let e=[],t=[];for(let i of this.#t)i.payload===void 0?t.push(i.id):e.push(i);return this.#t=[],{updated:e,deleted:t}}};var Gt=new Set(["master.key.derive","master.key.ready","master.origin.new","master.sealed","master.local.accepted","master.read","master.header","master.decrypt","master.opened","master.catalog","content.read","content.key","content.decrypt","content.opened","content.staged","session.memory","write.queued","write.prepare","chain.advance","write.sealed","content.memory","content.new","content.empty.sealed","content.id","catalog.link","add.commit","add.memory","content.subscribed","changed.receive","chain.checked","snapshot.checked","changed.memory","refresh.begin","refresh.memory","delete.begin","catalog.unlink","delete.proof","delete.commit","delete.memory","superdelete.begin","superdelete.commit","session.clear","session.closed","resync.required","reconnect.waiting","reconnect.attempt","reconnect.restored","reconnect.stopped","reconnect.cancelled","repair.begin","repair.checked","repair.reserve","repair.commit","repair.memory","repair.resolved"]),_n=new Set(["request.validated","hello.ready","read.lookup","read.found","read.subscribed","create.validated","create.committed","create.subscribed","write.lookup","write.verified","write.committed","write.subscribed","reply.ok","reply.error","changed.sent","session.unsubscribed"]);function $t(s,e,t=[],i=0){return c(s.has(e),"INVALID_PACKET"),c(Array.isArray(t)&&t.length<=_.batch,"INVALID_PACKET"),c(Number.isSafeInteger(i)&&i>=0&&(s===Gt||i<=_.batch),"INVALID_PACKET"),Object.freeze({step:e,ids:Object.freeze(t.map(P)),count:i})}function ii(s){return I(s,["step","ids","count","action"]),c(["hello","read","create","update","delete","session.close","changed"].includes(s.action),"INVALID_PACKET"),Object.freeze({...$t(_n,s.step,s.ids,s.count),event:`ulda:${s.action}`})}var ni=65536,Jt=class extends qe{#t=0;constructor(){super({maxAttachments:_.batch*2}),this.on("decoded",()=>{this.#t=0})}add(e){try{if(typeof e=="string")c(e.length<=ni&&Q(e).byteLength<=ni,"LIMIT"),this.#t=0;else{let t=C(e);c(this.#t+t.byteLength<=_.messageBytes,"LIMIT"),this.#t+=t.byteLength}return super.add(e)}catch(t){throw this.destroy(),t}}destroy(){super.destroy(),this.#t=0}},ri=Object.freeze({Encoder:ze,Decoder:Jt,protocol:gt});var Zt=Object.freeze({maxAttempts:5,initialDelay:500,maxDelay:5e3,jitter:.2,budget:3e4});function oi(s){if(s===!1)return{...Zt,automatic:!1};let e=s??{};c(e&&typeof e=="object"&&!Array.isArray(e)),c(Object.keys(e).every(i=>Object.hasOwn(Zt,i)));let t={...Zt,...e};for(let i of["maxAttempts","initialDelay","maxDelay","budget"])c(Number.isSafeInteger(t[i]));return c(t.maxAttempts>=1&&t.maxAttempts<=20),c(t.initialDelay>=10&&t.maxDelay>=t.initialDelay&&t.maxDelay<=6e4),c(t.budget>=50&&t.budget<=3e5),c(Number.isFinite(t.jitter)&&t.jitter>=0&&t.jitter<=1),{...t,automatic:!0}}function B(s){if(s?.aborted)throw s.reason}function Qt(s,e){return B(e),e?new Promise((t,i)=>{let n=()=>i(e.reason);e.addEventListener("abort",n,{once:!0}),Promise.resolve(s).then(t,i).finally(()=>e.removeEventListener("abort",n))}):s}function En(s,e){return B(e),new Promise((t,i)=>{let n=()=>{clearTimeout(r),i(e.reason)},r=setTimeout(()=>{e.removeEventListener("abort",n),t()},s);e.addEventListener("abort",n,{once:!0})})}var _t=class{#t;#s;#o;#e;#h;constructor(e,t,i){this.#t=e,this.#s=t,this.#o=i}get running(){return!!this.#e}cancel(e="OFFLINE"){this.#h?.abort(new b(e))}run({automatic:e=!1}={}){if(this.#e)return this.#e;if(e&&!this.#t.automatic)return Promise.resolve();let t=new AbortController,{signal:i}=t;this.#h=t;let n=setTimeout(()=>t.abort(new b("TIMEOUT")),this.#t.budget),r,a=Promise.resolve().then(async()=>{let h=this.#t,d=new b("OFFLINE");for(let l=1;l<=h.maxAttempts;l++){if(B(i),e||l>1){let f=Math.min(h.maxDelay,h.initialDelay*2**(l-1)),p=Math.max(1,Math.round(f*(1-h.jitter+Math.random()*h.jitter)));this.#o({phase:"waiting",attempt:l,delayMs:p}),await En(p,i)}this.#o({phase:"attempt",attempt:l}),B(i);try{let f=await Qt(this.#s(i),i);return B(i),r=l,f}catch(f){if(d=H(f),B(i),!["OFFLINE","TIMEOUT","BUSY"].includes(d.code))throw d}}throw d}),o=()=>{clearTimeout(n),this.#e=void 0,this.#h=void 0};return this.#e=a.then(h=>(o(),this.#o({phase:"restored",attempt:r}),h),h=>{let d=H(h);throw o(),this.#o({phase:i.aborted&&d.code!=="TIMEOUT"?"cancelled":"stopped",code:d.code}),d}),this.#e}};function es(s){return s.map(e=>({...e.id===void 0?{}:{id:e.id},witnessBytes:e.witness.byteLength,...e.payload===void 0?{}:{payloadBytes:e.payload.byteLength}}))}function ai(s){return s&&typeof s=="object"&&(Object.values(s).forEach(ai),Object.freeze(s)),s}var We=class{#t;#s;#o=new Set;#e=new Map;#h=!1;#r;#n=0;#y=0;#E=!1;#S=Promise.resolve();#k=Promise.resolve();#A=0;#f;#c;constructor(e,{timeout:t=1e4,allowInsecureLocalhost:i=!1,diagnostics:n=!1}={}){let r;try{r=new URL(e)}catch{c(!1)}c(!r.username&&!r.password&&!r.search&&!r.hash);let a=["localhost","127.0.0.1","[::1]"].includes(r.hostname);c(r.protocol==="https:"||i&&a&&r.protocol==="http:"),c(Number.isSafeInteger(t)&&t>=50&&t<=6e4),this.#s=t,this.#t=Ye(r.href,{autoConnect:!1,forceNew:!0,multiplex:!1,transports:["websocket"],parser:ri,reconnection:!1,retries:0,timeout:t,withCredentials:!1,auth:{uldaTransfer:1}}),n&&this.#t.on("ulda:diagnostic",o=>{try{let h=ii(o);this.#l(()=>({phase:"server",...h}))}catch{}}),this.#t.on("disconnect",()=>{clearTimeout(this.#c),this.#f=void 0,this.#l(()=>({phase:"connection",event:"disconnect"})),this.#n++,this.#_(),this.#u("disconnect",{intentional:this.#E||this.#h})}),this.#t.on("ulda:changed.part",o=>{try{if(o?.kind==="begin")I(o,["kind","count"]),c(!this.#f,"INVALID_PACKET"),this.#f=new mt(o.count),this.#c=setTimeout(()=>{this.#f=void 0,this.#u("error",new b("TIMEOUT"))},this.#s);else if(c(this.#f,"INVALID_PACKET"),o?.kind==="end"){I(o,["kind"]);let h=xt(this.#f.finish(),!0);clearTimeout(this.#c),this.#f=void 0,this.#u("changed",h)}else this.#f.accept(o)}catch{clearTimeout(this.#c),this.#f=void 0,this.#u("error",new b("INVALID_PACKET"))}}),this.#t.on("ulda:changed",o=>{try{c(!this.#f,"INVALID_PACKET");let h=xt(o);this.#l(()=>({phase:"push",event:"ulda:changed",updated:es(h.updated),deleted:[...h.deleted]})),this.#u("changed",h)}catch{this.#l(()=>({phase:"push",event:"ulda:changed",code:"INVALID_PACKET"})),this.#u("error",new b("INVALID_PACKET"))}})}get connected(){return this.#t.connected&&!this.#h}on(e,t){c(["changed","disconnect","error","trace"].includes(e)&&typeof t=="function");let i=this.#e.get(e)??new Set;return i.add(t),this.#e.set(e,i),()=>i.delete(t)}#u(e,t){for(let i of this.#e.get(e)??[])try{i(t)}catch{}}#l(e){if(this.#e.get("trace")?.size)try{this.#u("trace",ai({time:Date.now(),...e()}))}catch{}}#_(){for(let e of[...this.#o])e()}async start({signal:e}={}){if(B(e),c(!this.#h,"CLOSED"),!this.connected){if(this.#r)return this.#r;this.#l(()=>({phase:"connection",event:"connecting"})),this.#r=new Promise((t,i)=>{let n=!1,r=f=>{n||(n=!0,clearTimeout(l),e?.removeEventListener("abort",d),this.#t.off("connect",a),this.#t.off("connect_error",o),this.#o.delete(h),this.#l(()=>({phase:"connection",event:f?"connect_failed":"connect",...f?{code:f.code}:{}})),f?i(f):t())},a=()=>r(),o=()=>r(new b("OFFLINE")),h=()=>r(new b("CLOSED")),d=()=>{r(e.reason),this.#t.disconnect()},l=setTimeout(()=>{r(new b("TIMEOUT")),this.#t.disconnect()},this.#s);e?.addEventListener("abort",d,{once:!0}),this.#o.add(h),this.#t.once("connect",a),this.#t.once("connect_error",o),this.#t.connect()});try{await this.#r}finally{this.#r=void 0}}}async send(e,{volatile:t=!1,signal:i}={}){B(i);let{action:n,body:r}=Ns(e);if(Ts(n,r,!0),["create","update","delete"].includes(n)&&ti(r))return this.#a("write",()=>this.#v(n,r,i));try{return await this.#g(n,r,{volatile:t,signal:i})}catch(a){if(n==="read"&&r.length===1&&a.code==="LIMIT")return this.#a("read",()=>this.#C(r[0],i));if(["create","update","delete"].includes(n)&&a.code==="LIMIT")return this.#a("write",()=>this.#v(n,r,i));throw a}}#a(e,t){c(this.#A<_.queue,"LIMIT"),this.#A++;let i=this.#n,n=(e==="write"?this.#S:this.#k).then(()=>(c(i===this.#n,"OFFLINE"),t())),r=n.then(()=>{},()=>{}).finally(()=>this.#A--);return e==="write"?this.#S=r:this.#k=r,n}async#v(e,t,i){let n;try{n=await this.#g("transfer",{kind:"begin",action:e,count:t.length},{signal:i},r=>(r?.ok===!1&&ve("hello",{},r),I(r,["ok","token"]),c(r.ok===!0&&/^[a-f0-9]{32}$/.test(r.token),"INVALID_PACKET"),r.token));for(let r of si(t))await this.#g("transfer",{...r,token:n},{signal:i});return await this.#g("transfer",{kind:"commit",token:n},{signal:i,commit:!0,volatile:!0},r=>ve(e,t,r,!0))}catch(r){throw(n||r.code==="TIMEOUT"||r.code==="INVALID_PACKET")&&this.disconnect(),r}}async#C(e,t){let i,n=0;try{do{let r=await this.#g("transfer",{kind:"read",resourceId:e,offset:n},{signal:t},a=>{a?.ok===!1&&ve("hello",{},a),I(a,["ok","data"]),c(a.ok===!0,"INVALID_PACKET");let o=a.data;I(o,["id","witness","payload","total","offset"]),c(o.id===e&&o.offset===n,"INVALID_PACKET"),c(Number.isSafeInteger(o.total)&&o.total>0&&o.total<=_.resourceBytes,"LIMIT");let h=C(o.witness,167),d=C(o.payload,_.jsonBytes);return c(n+d.length<=o.total,"INVALID_PACKET"),{...o,witness:h,payload:d}});i||(i={id:e,witness:r.witness.slice(),payload:new Uint8Array(r.total)}),c(i.payload.length===r.total&&D(i.witness,r.witness),"INVALID_PACKET"),i.payload.set(r.payload,n),n+=r.payload.length}while(n<i.payload.length);return[ot(i)]}catch(r){throw this.disconnect(),r}}async#g(e,t,{volatile:i=!1,signal:n,commit:r=!1}={},a=o=>ve(e,t,o)){B(n),c(!this.#h,"CLOSED"),c(this.connected,"OFFLINE"),c(this.#o.size<_.queue,"LIMIT");let o=this.#n,h=r||["create","update","delete"].includes(e),d=!!this.#e.get("trace")?.size,l=d?++this.#y:0,f=d?performance.now():0,p=`ulda:${e}`;return new Promise((m,u)=>{let y=!1,g=(O,L,S=!1)=>{y||(y=!0,this.#o.delete(A),n?.removeEventListener("abort",E),d&&this.#l(()=>({phase:S?"ack":"failure",event:p,request:l,durationMs:Math.max(0,Math.round(performance.now()-f)),...O?{code:O.code}:{ok:!0},...!O&&e==="read"?{items:es(L)}:{},...!O&&e==="create"?{ids:[...L]}:{}})),O?u(O):m(L))},A=()=>g(new b(h?"UNKNOWN_OUTCOME":"OFFLINE")),E=()=>g(new b(h?"UNKNOWN_OUTCOME":n.reason.code));n?.addEventListener("abort",E,{once:!0}),this.#o.add(A);let T=this.#t.timeout(this.#s);i&&T.volatile,d&&this.#l(()=>({phase:"send",event:p,request:l,volatile:!!i,...e==="read"?{ids:[...t]}:{},...h&&Array.isArray(t)?{items:es(t)}:{},...e==="transfer"?{step:t.kind}:{}})),T.emit(p,t,(O,L)=>{if(!y){if(O||o!==this.#n)return g(new b(h?"UNKNOWN_OUTCOME":"TIMEOUT"));try{g(void 0,a(L),!0)}catch(S){let q=H(S);g(h&&(L?.ok!==!1||q.code==="INVALID_PACKET"||q.code==="INVALID_INPUT")?new b("UNKNOWN_OUTCOME"):q,void 0,!0)}}})})}disconnect(){let e=this.connected;this.#E=!0;try{this.#t.disconnect()}finally{this.#E=!1}!e&&!this.#h&&(this.#n++,this.#_(),this.#u("disconnect",{intentional:!0}))}close(){this.#h||(this.#h=!0,clearTimeout(this.#c),this.#f=void 0,this.#n++,this.#_(),this.#t.disconnect(),this.#t.removeAllListeners(),this.#l(()=>({phase:"connection",event:"closed"})),this.#e.clear())}};var Et=class{#t;#s;#o=[];#e=new Map;#h=!1;#r=!1;#n=!1;#y=-1;#E;#S;#k;#A=new Set;#f;constructor(e,t,i,n){this.#t=this.#s=e,this.#E=t,this.#S=i,this.#k=n}get active(){return this.#h||this.#o.length>0||this.#e.size>0}get blocked(){return this.#r}idle(){return this.active?new Promise(e=>this.#A.add(e)):Promise.resolve()}#c(){if(!this.active){for(let e of this.#A)e();this.#A.clear()}}enqueue(e){return c(!this.#n,"CLOSED"),c(!this.#r,"NEEDS_RESYNC"),c(this.#o.length+this.#e.size<_.queue,"LIMIT"),new Promise((t,i)=>{this.#o.push({change:e,resolve:t,reject:i}),this.#l()})}#u(e){for(let t of this.#o.splice(0))t.reject(new b(e))}observe(e,{refresh:t=!1}={}){if(this.#n||e.age<this.#t.age)return;let i=[...this.#e.values()].some(r=>D(r.state.record.witness,e.record.witness)&&D(r.state.record.payload,e.record.payload)),n=D(this.#t.record.witness,e.record.witness)&&D(this.#t.record.payload,e.record.payload);this.#t=e,!i&&!n&&this.active&&(this.#r=!0,this.#u("CONFLICT")),this.active||(this.#s=e),t&&!this.active&&e.age>=this.#y&&(this.#r=!1,this.#s=e),this.#l()}async#l(){if(this.#h||this.#r||this.#n||!this.#o.length||(this.#s.mode==="X"?this.#e.size>0:this.#s.age+1-this.#t.age>=this.#s.N))return;this.#h=!0;let e=this.#o.shift();this.#f=e;try{let t=this.#s,i=this.#E(t,e.change);e.change=void 0;let n=await i;if(this.#n)throw new b("CLOSED");if(this.#r||t!==this.#s)throw new b("NEEDS_RESYNC");e.state=n,this.#s=n,this.#e.set(n.record.witness,e),this.#S(n).then(async()=>{if(this.#n)throw new b("CLOSED");await this.#k(n),this.#e.delete(n.record.witness),!this.#e.size&&!this.#h&&(this.#s=this.#t),e.resolve({ok:!0})}).catch(r=>{this.#e.delete(n.record.witness),r.code==="UNKNOWN_OUTCOME"&&(this.#y=Math.max(this.#y,n.age)),this.#r=!0,this.#u("NEEDS_RESYNC"),e.reject(r)}).finally(()=>{this.#e.delete(n.record.witness),!this.#e.size&&!this.#h&&(this.#s=this.#t),this.#l(),this.#c()})}catch(t){e.reject(t)}finally{this.#f=void 0,this.#h=!1,this.#l(),this.#c()}}stop(e="NEEDS_RESYNC"){this.#r=!0,this.#u(e),this.#c()}close(){this.#n=!0,this.#f?.reject(new b("CLOSED")),this.#u("CLOSED");for(let e of this.#e.values())e.reject(new b("CLOSED"));this.#e.clear(),this.#t=this.#s=void 0,this.#E=this.#S=this.#k=void 0,this.#c()}};function ts(s,e,t,i=[]){let n=a=>(e(),ts(s,e,t,[...i,String(a)])),r={get:()=>(e(),s.value(t,i)),update:a=>(e(),s.set(t,i,a)),delete:()=>(e(),i.length?s.remove(t,i):s.delete(t)),field:n,toJSON:()=>(e(),s.value(t,i))};return new Proxy(Object.create(null),{get:(a,o)=>{if(!(o==="then"||typeof o=="symbol"))return Object.hasOwn(r,o)?r[o]:n(o)},set:()=>{c(!1,"UNSUPPORTED")},deleteProperty:()=>{c(!1,"UNSUPPORTED")},defineProperty:()=>{c(!1,"UNSUPPORTED")}})}function ss(s,e){return new Proxy(Object.create(null),{get:(t,i)=>{if(c(s.contextGeneration===e,"STALE_REFERENCE"),!(i==="then"||typeof i=="symbol"))return i==="toJSON"?()=>s.snapshot():i==="field"?n=>s.ref(n):s.ref(i)},set:()=>{c(!1,"UNSUPPORTED")},deleteProperty:()=>{c(!1,"UNSUPPORTED")},defineProperty:()=>{c(!1,"UNSUPPORTED")}})}var is=class{#t;#s="connecting";#o;#e;#h;#r=new Map;#n=new Map;#y=new Map;#E=Promise.resolve();#S=0;#k=0;#A=Promise.resolve();#f=0;#c=0;#u=new Map;#l=new Map;#_=-1;#a=!1;#v;#C=!1;#g=!1;#U;#D;#X;#G=!1;#w=0;#z=Promise.resolve();#m=new AbortController;#q=[];#I;#O=0;constructor(e,t={}){c(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).every(n=>["transport","timeout","allowInsecureLocalhost","reconnect"].includes(n)));let i=oi(t.reconnect);this.#t=t.transport??new We(e,t),this.#D=new _t(i,n=>this.#ee(n),n=>{n.phase==="stopped"&&!this.#a&&(this.#s=this.#t.connected?"needsResync":"disconnected",this.#p("status",this.#s)),this.#i(`reconnect.${n.phase}`,[],n.attempt??0),this.#p("reconnect",Object.freeze(n)),n.phase==="stopped"&&!this.#a&&this.#p("error",new b(n.code))}),this.#q.push(this.#t.on("changed",n=>{let r=this.#w,a=n.updated.reduce((o,h)=>o+h.witness.length+h.payload.length+256,n.deleted.length*256);if(this.#S>=_.incoming||this.#k+a>_.transferBytes)return this.#V(new b("LIMIT"));this.#k+=a,this.#R(()=>r===this.#w?this.#ie(n):void 0).catch(o=>{r===this.#w&&this.#V(o)}).finally(()=>{this.#k-=a})})),this.#q.push(this.#t.on("disconnect",n=>{if(this.#w++,!this.#a){this.#s="disconnected";for(let r of this.#n.values())r.stop();if(this.#p("status",this.#s),this.#a)return;n?.intentional?this.#D.cancel():this.#G&&this.#D.run({automatic:!0}).then(()=>{},()=>{})}})),this.#q.push(this.#t.on("error",n=>this.#V(n))),this.#X=this.#o=this.#$(this.#m.signal),this.#o.catch(()=>{})}get ready(){return this.#o}get status(){return this.#s}get contextGeneration(){return this.#c}get data(){return this.#b(),this.#U}on(e,t){c(!this.#a,"CLOSED"),c(["change","status","error","trace","reconnect"].includes(e)&&typeof t=="function");let i=this.#u.get(e)??new Set;return i.add(t),this.#u.set(e,i),()=>i.delete(t)}#p(e,t){for(let i of this.#u.get(e)??[])try{i(t)}catch{}}#V(e){if(!this.#a){this.#O++,this.#s="needsResync",this.#i("resync.required");for(let t of this.#n.values())t.stop();this.#p("status",this.#s),this.#p("error",H(e))}}#i(e,t=[],i=0){if(this.#u.get("trace")?.size)try{this.#p("trace",Object.freeze({time:Date.now(),phase:"client",event:e,...$t(Gt,e,t.slice(0,_.batch),i)}))}catch{}}async#P(e,t,i,n="content"){let r=this.#c;this.#d(r),this.#i(`${n}.decrypt`,[t.id]),this.#d(r);let a=await bs(e,t,i,n==="master");try{this.#d(r)}catch(o){throw a.origin.fill(0),o}return this.#i(`${n}.opened`,[t.id]),a}#R(e){this.#S++;let t=this.#E.then(e);return this.#E=t.then(()=>{},()=>{}).finally(()=>this.#S--),t}async#$(e){let t=this.#O;try{B(e),await this.#t.start({signal:e}),c(!this.#a,"CLOSED"),B(e);let i=this.#w;await this.#t.send(vt("hello"),{signal:e}),c(!this.#a,"CLOSED"),B(e),c(i===this.#w&&this.#t.connected,"OFFLINE"),this.#j(t),this.#G=!0,this.#s=this.#e?"needsResync":"ready"}catch(i){throw this.#a||(this.#s=i?.code==="NEEDS_RESYNC"&&this.#t.connected?"needsResync":"disconnected"),H(i)}}#b(e=!1){c(!this.#a,"CLOSED"),c(this.#e,"NOT_OPEN"),e&&(c(!this.#I,"NEEDS_RESYNC"),c(this.#s==="open"&&this.#t.connected,"NEEDS_RESYNC"),c(!this.#g,"BUSY"))}#d(e){c(!this.#a,"CLOSED"),c(e===this.#c,"STALE_REFERENCE")}#L(e,t,i){this.#d(e),B(i),c(t===this.#w&&this.#t.connected,"OFFLINE")}#j(e){c(e===this.#O,"NEEDS_RESYNC")}#B(e,t){this.#d(e),this.#j(t),c(this.#t.connected,"OFFLINE")}async#ee(e){return await Qt(Promise.all([this.#X.catch(()=>{}),this.#E,this.#A,this.#z,...[...this.#n.values()].map(t=>t.idle())]),e),B(e),c(!this.#a,"CLOSED"),this.#s="reconnecting",this.#p("status",this.#s),B(e),await this.#$(e),this.#e?await this.#J(e):this.#p("status",this.#s),B(e),c(!this.#a,"CLOSED"),c(this.#t.connected,"OFFLINE"),c(this.#s==="open"||this.#s==="ready","NEEDS_RESYNC"),this.#U}#x(e){I(e,["contents"]),c(Array.isArray(e.contents),"LIMIT");let t=new Set,i=new Set;for(let n of e.contents)I(n,["id","name","key","token"]),P(n.id),de(n.name),c(re(n.key,32).length===32&&re(n.token,32).length===32),c(!t.has(n.name)&&!i.has(n.id)),t.add(n.name),i.add(n.id);return e.contents}#M(e){this.#b(),de(e);let t=this.#e.data.contents.find(i=>i.name===e);return c(t,"NOT_FOUND"),t}async#F(e,t,i){let n=this.#c;this.#d(n),this.#i("write.prepare",[e.id]);let r=e.id===this.#e?.id,a=U(i(U(e.data,r)),r),o=st(e.origin);try{this.#i("chain.advance",[e.id]);let h=await Re(t,e.token,o,a,r);this.#d(n),this.#i("write.sealed",[e.id]);let d=X(h);return{id:e.id,origin:o,token:e.token,data:a,witness:d.witness,record:{id:e.id,...d},sealed:h,...V(o)}}catch(h){throw o.fill(0),h}}async#N(e,t,i=!1){if(e){if(c(t.mode===e.mode&&t.token===e.token,"CRYPTO_FAILED"),c(t.age>=e.age,"ROLLBACK"),t.age===e.age){c(D(t.record.witness,e.record.witness)&&D(t.record.payload,e.record.payload),"ROLLBACK");return}if(!i){let n=await it(e.witness,t.witness);if(!n){let r=[...this.#y.get(t.id)??[]].filter(o=>o.age>e.age&&o.age<t.age).sort((o,h)=>o.age-h.age),a=[e];for(let o of r)for(let h of a)if(await it(h.witness,o.witness)){a.push(o);break}for(let o of a.slice(1))if(await it(o.witness,t.witness)){n=!0;break}}c(n,"NEEDS_RESYNC")}this.#i(i?"snapshot.checked":"chain.checked",[t.id??t.record.id])}}#T(e,t=1/0){let i=this.#y.get(e);if(i){for(let n of i)n.age<=t&&i.delete(n);i.size||this.#y.delete(e)}}async#Y(e,t){c(!this.#a,"CLOSED");for(let i of t){let n=this.#y.get(i.id)??new Set;n.add(i),this.#y.set(i.id,n)}try{await this.#t.send(e,{volatile:!0,signal:this.#m.signal})}catch(i){if(i.code!=="UNKNOWN_OUTCOME")for(let n of t){let r=this.#y.get(n.id);r?.delete(n),r?.size||this.#y.delete(n.id)}throw i}}#K(e,t){let i=this.#c;return new Et(e,async(n,r)=>{this.#d(i);let a=await this.#F(n,t,r);return this.#d(i),a},n=>(this.#d(i),this.#Y(ae("update",[{id:n.id,sealed:n.sealed}]),[n])),n=>this.#R(async()=>{this.#d(i),await this.#te(n)}))}async#te(e,t=!1){let i=this.#r.get(e.id);i&&e.age<i.state.age||(await this.#N(i?.state,e,t),i&&(i.state=e,this.#T(e.id,e.age),this.#n.get(e.id)?.observe(e,{refresh:t}),this.#i("content.memory",[e.id]),this.#p("change",{id:e.id,kind:"updated"})))}async register(e){await this.#o,c(!this.#a,"CLOSED"),c(!this.#e&&!this.#C,"BUSY"),c(this.#s==="ready","NEEDS_RESYNC"),this.#C=!0;try{return await this.#R(async()=>{let t=this.#c;this.#d(t);let i=this.#O;this.#i("master.key.derive");let n=Ct(e);e=void 0;let r=await n;this.#d(t),this.#i("master.key.ready");let a=tt("X"),o=nt(),h=U({contents:[]});try{this.#i("master.origin.new");let d=await Re(r,o,a,h);this.#i("master.sealed"),this.#B(t,i);let[l]=await this.#t.send(ae("create",[{sealed:d}]),{volatile:!0,signal:this.#m.signal});this.#d(t);let f=X(d);return this.#c++,this.#e={id:l,origin:a,token:o,data:h,witness:f.witness,record:{id:l,...f},...V(a)},this.#h=r,this.#U=ss(this,this.#c),this.#t.connected?this.#s!=="needsResync"&&(this.#s="open"):this.#s="disconnected",this.#i("master.local.accepted",[l]),this.#i("session.memory",[l],0),l}finally{this.#e?.origin!==a&&a.fill(0)}})}finally{e=void 0,this.#C=!1}}async connect(e,t){P(e),await this.#o,c(!this.#e&&!this.#C,"BUSY"),c(!this.#a,"CLOSED"),this.#C=!0;try{return await this.#R(async()=>{let i=this.#c;this.#d(i);let n=this.#O;this.#i("master.read",[e]);let r=this.#w,[a]=await this.#t.send(ye([e]),{signal:this.#m.signal});this.#L(i,r);let o=ee(a.payload);this.#i("master.header",[e]),this.#i("master.key.derive",[e]);let h=Ct(t,o.salt);t=void 0;let d=await h;this.#L(i,r),this.#i("master.key.ready",[e]);let l={id:e,...await this.#P(d,a,void 0,"master")};c(l.mode==="X","UNSUPPORTED_PROFILE");let f=this.#x(l.data);this.#i("master.catalog",[e],f.length);let p=await this.#H(f);this.#L(i,r),this.#j(n),this.#c++,this.#e=l,this.#h=d,this.#r=p;for(let[m,u]of p)this.#n.set(m,this.#K(u.state,u.credentials));return this.#U=ss(this,this.#c),this.#s="open",this.#i("session.memory",[e],p.size),this.#U})}catch(i){throw i.code!=="NEEDS_RESYNC"&&this.#t.disconnect(),H(i)}finally{t=void 0,this.#C=!1}}async#H(e,t=!1,i=this.#m.signal){let n=new Map;if(!e.length)return n;this.#i("content.read",e.map(r=>r.id),e.length);try{for(let r=0;r<e.length;r+=_.batch){let a=e.slice(r,r+_.batch),o=new Map((await this.#W(a.map(h=>h.id),i)).map(h=>[h.id,h]));for(let h of a){B(i);let d=o.get(h.id),l=await De(h.key,ee(d.payload).salt);this.#i("content.key",[h.id]);let f={id:h.id,...await this.#P(l,d,h.token)};try{await this.#N(this.#r.get(h.id)?.state,f,t)}catch(p){throw f.origin.fill(0),p}n.set(h.id,{state:f,credentials:l}),this.#i("content.staged",[h.id])}}}catch(r){for(let a of n.values())a.state.origin.fill(0);throw r}return n}async#W(e,t=this.#m.signal){try{return await this.#t.send(ye(e),{signal:t})}catch(i){if(i.code!=="LIMIT"||e.length<2)throw i;let n=Math.ceil(e.length/2);return[...await this.#W(e.slice(0,n),t),...await this.#W(e.slice(n),t)]}}snapshot(){this.#b();let e=Object.create(null);for(let t of this.#e.data.contents){let i=this.#r.get(t.id);i&&Object.defineProperty(e,t.name,{value:U(i.state.data),enumerable:!0})}return e}value(e,t=[]){let i=this.#M(e),n=this.#r.get(i.id);return c(n,"NOT_FOUND"),U(At(n.state.data,t))}ref(e){let t=this.#M(e).id,i=this.#c;return ts(this,()=>{c(this.#c===i,"STALE_REFERENCE"),c(this.#r.has(t)&&this.#e?.data.contents.some(r=>r.id===t&&r.name===e),"STALE_REFERENCE")},e)}update(e,t){return this.set(e,[],t)}set(e,t,i){this.#b(!0);let n=this.#M(e);c(Array.isArray(t));let r=U(i),a=[...t],o=this.#n.get(n.id);return c(o,"NOT_FOUND"),this.#i("write.queued",[n.id]),o.enqueue(h=>wt(h,a,r))}remove(e,t){this.#b(!0);let i=this.#M(e);c(Array.isArray(t));let n=[...t];c(n.length>0,"UNSUPPORTED");let r=this.#n.get(i.id);return c(r,"NOT_FOUND"),r.enqueue(a=>wt(a,n,null,!0))}#se(e){this.#b(!0),c(this.#f<_.queue,"LIMIT"),this.#f++;let t=this.#c,i=this.#A.then(()=>(this.#d(t),this.#b(!0),c(this.#_<0,"NEEDS_RESYNC"),e())).finally(()=>this.#f--);return this.#A=i.catch(()=>{}),i}add(e,t,i="X"){de(e),c(i==="X"||i==="S");let n=U(t);return this.#se(async()=>{let r=this.#c,a=this.#O;c(!this.#e.data.contents.some(l=>l.name===e),"EXISTS");let o=this.#l.get(e);if(o)c(o.mode===i&&JSON.stringify(o.data)===JSON.stringify(n),"BUSY");else{this.#i("content.new");let l=Dt(),f=nt(),p=await De(l),m=tt(i),u=await Re(p,f,m,null);this.#i("content.empty.sealed"),this.#B(r,a),o={key:l,token:f,credentials:p,mode:i,data:n,state:{origin:m,token:f,data:null,...V(m)}};try{let[y]=await this.#t.send(ae("create",[{sealed:u}]),{volatile:!0,signal:this.#m.signal});o.id=y,this.#i("content.id",[y]),o.state.id=y,o.state.record={id:y,...X(u)},o.state.witness=o.state.record.witness}catch(y){throw!this.#a&&y.code==="UNKNOWN_OUTCOME"&&(this.#_=1/0),y}this.#d(r),this.#l.set(e,o)}this.#B(r,a);let h=await this.#F(o.state,o.credentials,()=>n);this.#d(r);let d=await this.#F(this.#e,this.#h,l=>(c(!l.contents.some(f=>f.name===e),"EXISTS"),l.contents.push({id:o.id,name:e,key:o.key,token:o.token}),this.#i("catalog.link",[this.#e.id,o.id]),this.#x(l),l));this.#d(r);try{this.#i("add.commit",[o.id,this.#e.id]),this.#B(r,a),await this.#Y(ae("update",[{id:o.id,sealed:h.sealed},{id:this.#e.id,sealed:d.sealed}]),[h,d])}catch(l){throw!this.#a&&l.code==="UNKNOWN_OUTCOME"&&(this.#_=d.age,this.#s="needsResync"),l}return await this.#R(async()=>{if(this.#d(r),d.age>=this.#e.age&&(await this.#N(this.#e,d),this.#e=d),!this.#r.has(o.id)&&this.#e.data.contents.some(l=>l.id===o.id&&l.token===o.token)){let l=o.received&&o.received.age>h.age?o.received:h;this.#r.set(o.id,{state:l,credentials:o.credentials}),this.#n.set(o.id,this.#K(l,o.credentials))}this.#l.delete(e),this.#T(this.#e.id,this.#e.age),this.#T(o.id,this.#r.get(o.id)?.state.age??1/0),this.#i("add.memory",[o.id,this.#e.id])}),this.#i("content.subscribed",[o.id]),{ok:!0,name:e,subscriptionReady:this.#t.connected}})}async#ie(e){if(this.#a||!this.#e)return;this.#i("changed.receive",[...e.updated.map(f=>f.id),...e.deleted]);let t=this.#c,i=this.#w,n=e.deleted.includes(this.#e.id),r=e.updated.find(f=>f.id===this.#e.id),a=this.#e;if(r){let f={id:this.#e.id,...await this.#P(this.#h,r,this.#e.token,"master")};f.age>=this.#e.age&&(await this.#N(this.#e,f),this.#x(f.data),a=f)}for(let f of a.data.contents){let p=this.#e.data.contents.find(m=>m.id===f.id);p&&c(f.key===p.key&&f.token===p.token,"UNSUPPORTED_PROFILE")}let o=new Map,h=new Map;for(let f of e.updated){let p=a.data.contents.find(g=>g.id===f.id);if(!p){let g=[...this.#l.values()].find(A=>A.id===f.id);if(g){let A={id:f.id,...await this.#P(g.credentials,f,g.token)},E=g.received??g.state;A.age>=E.age&&(await this.#N(E,A),h.set(g,A))}continue}let m=await De(p.key,ee(f.payload).salt),u={id:p.id,...await this.#P(m,f,p.token)},y=this.#r.get(p.id)?.state;y&&u.age<y.age||(await this.#N(y,u),o.set(p.id,{state:u,credentials:m}))}if(n){this.#L(t,i),await this.close();return}let d=a.data.contents.filter(f=>!this.#r.has(f.id)&&!o.has(f.id)&&!e.deleted.includes(f.id));for(let[f,p]of await this.#H(d))o.set(f,p);this.#L(t,i);for(let[f,p]of h)f.received=p;this.#e=a,this.#T(a.id,a.age);let l=new Set(a.data.contents.map(f=>f.id));for(let f of this.#r.keys())(!l.has(f)||e.deleted.includes(f))&&(this.#n.get(f)?.close(),this.#n.delete(f),this.#r.delete(f),this.#T(f));for(let[f,p]of o)this.#r.set(f,p),this.#T(f,p.state.age),this.#n.has(f)?this.#n.get(f).observe(p.state):this.#n.set(f,this.#K(p.state,p.credentials));this.#p("change",{ids:[...o.keys()],kind:"updated"}),this.#i("changed.memory",[...o.keys(),...e.deleted]),e.deleted.length&&this.#p("change",{ids:[...e.deleted],kind:"deleted"})}async refresh(){return c(!this.#D.running,"BUSY"),this.#J()}async#J(e=this.#m.signal){return this.#b(),c(!this.#f&&![...this.#n.values()].some(t=>t.active),"BUSY"),this.#R(async()=>{let t=this.#c,i=this.#w;this.#L(t,i,e);let n=this.#O;this.#i("refresh.begin",[this.#e.id]),this.#i("master.read",[this.#e.id]);let[r]=await this.#t.send(ye([this.#e.id]),{signal:e}),a={id:this.#e.id,...await this.#P(this.#h,r,this.#e.token,"master")};await this.#N(this.#e,a,!0),this.#i("master.catalog",[this.#e.id],this.#x(a.data).length);let o=await this.#H(this.#x(a.data),!0,e);this.#L(t,i,e),this.#j(n),this.#e=a,this.#T(a.id,a.age);for(let[h,d]of this.#n)o.has(h)||(d.close(),this.#n.delete(h),this.#T(h));this.#r=o;for(let[h,d]of o)this.#T(h,d.state.age),this.#n.has(h)?this.#n.get(h).observe(d.state,{refresh:!0}):this.#n.set(h,this.#K(d.state,d.credentials));a.age>=this.#_&&(this.#_=-1);for(let[h,d]of this.#l)a.data.contents.some(l=>l.name===h&&l.id===d.id&&l.token===d.token)&&this.#l.delete(h);return this.#s=!this.#I&&this.#_<0&&![...this.#n.values()].some(h=>h.blocked)?"open":"needsResync",this.#i("refresh.memory",[this.#e.id],o.size),this.#p("status",this.#s),this.#L(t,i,e),this.#U}).catch(t=>{let i=H(t);throw this.#t.connected&&!e?.aborted&&this.#V(i),i})}reconnect(){if(this.#a)return Promise.reject(new b("CLOSED"));let e=this.#D.running,t=this.#D.run();if(!e){this.#s="reconnecting";for(let i of this.#n.values())i.stop();this.#p("status",this.#s)}return this.#o=t.then(()=>{}),this.#o.catch(()=>{}),t}async recoverContent(e){this.#b(),de(e),c(this.#t.connected,"OFFLINE"),c(!this.#g&&!this.#D.running&&!this.#f&&![...this.#n.values()].some(i=>i.active),"BUSY"),c(!this.#I||this.#I.content===e,"BUSY"),c(this.#_<0&&!this.#l.size&&(this.#I||!this.#y.size),"NEEDS_RESYNC"),this.#g=!0;let t;this.#z=new Promise(i=>{t=i});try{return await this.#R(async()=>{let i=this.#c,n=this.#w,r=this.#O,a=()=>this.#L(i,n,this.#m.signal);a();let o=this.#I;if(!o){let u=this.#M(e),y=this.#r.get(u.id)?.state;c(y,"NOT_FOUND"),o={content:e,entry:U(u),source:U(y.data),sourceAge:y.age,mode:y.mode,phase:"prepared"},this.#I=o}this.#s="needsResync";for(let u of this.#n.values())u.stop();this.#i("repair.begin",[o.entry.id]),a(),c(o.phase!=="createUnknown","UNKNOWN_OUTCOME");let[h]=await this.#t.send(ye([this.#e.id]),{signal:this.#m.signal});a();let d={id:this.#e.id,...await this.#P(this.#h,h,this.#e.token,"master")};await this.#N(this.#e,d,!0);let l=this.#x(d.data),f=l.find(u=>u.name===e),p=(u,y)=>u?.id===y.id&&u.key===y.key&&u.token===y.token;if(a(),o.id&&p(f,{id:o.id,key:o.key,token:o.token})){c(o.candidate&&["commitUnknown","committed"].includes(o.phase),"CONFLICT"),await this.#N(o.master,d,!0);let u=await this.#H(l,!0);await this.#N(o.candidate,u.get(o.id).state,!0),a();let y=this.#Z(o,d,u,r,!0);return this.#i("repair.resolved",[y.previousId,y.id]),y}c(!["commitUnknown","committed"].includes(o.phase),"UNKNOWN_OUTCOME"),c(p(f,o.entry),"CONFLICT");let m=await this.#H(l.filter(u=>u.id!==o.entry.id),!0);if(a(),this.#i("repair.checked",[d.id,o.entry.id]),a(),o.id){let[u]=await this.#t.send(ye([o.id]),{signal:this.#m.signal});a(),c(D(u.witness,o.base.record.witness)&&D(u.payload,o.base.record.payload),"CONFLICT")}else{if(!o.base){o.key=Dt(),o.token=nt(),o.credentials=await De(o.key),a();let u=tt(o.mode);o.base={origin:u,token:o.token,data:null,...V(u)}}o.empty||(o.empty=await Re(o.credentials,o.token,o.base.origin,null),a()),this.#i("repair.reserve"),a(),this.#B(i,r);try{let[u]=await this.#t.send(ae("create",[{sealed:o.empty}]),{volatile:!0,signal:this.#m.signal});this.#d(i),o.phase="createUnknown",c(u!==d.id&&!l.some(g=>g.id===u),"UNKNOWN_OUTCOME"),o.id=u;let y=X(o.empty);Object.assign(o.base,{id:u,witness:y.witness,record:{id:u,...y}}),o.phase="reserved"}catch(u){throw u.code==="UNKNOWN_OUTCOME"&&!this.#a&&(o.phase="createUnknown"),u}a()}o.candidate=await this.#F(o.base,o.credentials,()=>o.source),a(),o.master=await this.#F(d,this.#h,u=>{let y=u.contents.find(g=>g.name===e);return c(p(y,o.entry),"CONFLICT"),Object.assign(y,{id:o.id,key:o.key,token:o.token}),this.#x(u),u}),a(),this.#i("repair.commit",[o.id,d.id]),a(),this.#B(i,r);try{await this.#Y(ae("update",[{id:o.id,sealed:o.candidate.sealed},{id:d.id,sealed:o.master.sealed}]),[o.candidate,o.master]),o.phase="committed"}catch(u){throw this.#a||(o.phase=u.code==="UNKNOWN_OUTCOME"?"commitUnknown":"reserved"),u}return this.#d(i),m.set(o.id,{state:o.candidate,credentials:o.credentials}),this.#Z(o,o.master,m,r,!1)})}catch(i){throw!this.#a&&this.#I&&this.#t.connected&&this.#V(i),H(i)}finally{this.#g=!1,t()}}#Z(e,t,i,n,r){let a=Object.freeze({ok:!0,previousId:e.entry.id,id:e.id,sourceAge:e.sourceAge,reconciled:r});for(let o of this.#n.values())o.close();this.#n.clear(),this.#e=t,this.#r=i,this.#y.clear();for(let[o,h]of i)this.#n.set(o,this.#K(h.state,h.credentials));return this.#Q(),this.#s=this.#t.connected?this.#O===n?"open":"needsResync":"disconnected",this.#i("repair.memory",[a.previousId,a.id,t.id]),this.#a||this.#p("change",{ids:[a.previousId,a.id],kind:"recovered"}),this.#a||this.#p("status",this.#s),a}#Q(){let e=this.#I;if(!e)return;let t=new Set([this.#e?.origin,...[...this.#r.values()].map(i=>i.state.origin)]);for(let i of[e.base,e.candidate,e.master])i&&!t.has(i.origin)&&i.origin.fill(0);this.#I=void 0}async delete(e){this.#b(!0),de(e),c(!this.#f&&![...this.#n.values()].some(i=>i.active),"BUSY"),this.#g=!0;let t;this.#z=new Promise(i=>{t=i});try{let i=this.#O;this.#i("delete.begin"),await this.refresh();let n=this.#M(e),r=this.#r.get(n.id)?.state;c(r,"NOT_FOUND");let a=this.#c,o=await Ut(n.id,r.origin);this.#i("delete.proof",[n.id]);let h=await this.#F(this.#e,this.#h,d=>(d.contents=d.contents.filter(l=>l.id!==n.id),this.#i("catalog.unlink",[this.#e.id,n.id]),d));this.#d(a),this.#i("delete.commit",[n.id,this.#e.id]);try{this.#B(a,i),await this.#Y(Pt([o],[{id:this.#e.id,sealed:h.sealed}]),[h])}catch(d){throw this.#a||(d.code==="UNKNOWN_OUTCOME"&&(this.#_=h.age),this.#s="needsResync",this.#i("resync.required")),d}return await this.#R(async()=>{this.#d(a),h.age>=this.#e.age&&(await this.#N(this.#e,h),this.#e=h),this.#n.get(n.id)?.close(),this.#n.delete(n.id),this.#r.delete(n.id),this.#T(n.id),this.#T(this.#e.id,this.#e.age),this.#i("delete.memory",[n.id,this.#e.id]),this.#p("change",{ids:[n.id],kind:"deleted"})}),{ok:!0}}finally{this.#g=!1,t()}}async superDelete(){this.#b(!0),c(!this.#f&&![...this.#n.values()].some(t=>t.active),"BUSY"),this.#g=!0;let e;this.#z=new Promise(t=>{e=t});try{let t=this.#O;this.#i("superdelete.begin",[this.#e.id]),await this.refresh();let i=[...this.#r.values()].map(a=>a.state);i.push(this.#e);let n=this.#c,r=[];for(let a of i)r.push(await Ut(a.id,a.origin));this.#d(n);try{this.#i("superdelete.commit",i.map(a=>a.id),i.length),this.#B(n,t),await this.#t.send(Pt(r),{volatile:!0,signal:this.#m.signal})}catch(a){throw!this.#a&&a.code==="UNKNOWN_OUTCOME"&&(this.#_=1/0,this.#s="needsResync"),a}return await this.close(),{ok:!0}}finally{this.#g=!1,e()}}close(){if(this.#v)return this.#v;let e,t;return this.#v=new Promise((i,n)=>{e=i,t=n}),this.#ne().then(e,t),this.#v}async#ne(){if(this.#a)return;this.#a=!0,this.#D.cancel("CLOSED"),this.#s="closed",this.#c++,this.#m.abort(new b("CLOSED"));for(let t of this.#q.splice(0))try{t?.()}catch{}let e=t=>t?.origin?.fill(0);e(this.#e);for(let{state:t}of this.#r.values())e(t);for(let t of this.#y.values())for(let i of t)e(i);for(let t of this.#l.values())e(t.state),e(t.received);this.#Q();for(let t of this.#n.values())t.close();this.#e=void 0,this.#h=void 0,this.#r.clear(),this.#n.clear(),this.#y.clear(),this.#l.clear(),this.#U=void 0,this.#i("session.clear");try{this.#t.connected&&await this.#t.send(vt("session.close"))}catch{}finally{this.#t.close(),this.#i("session.closed"),this.#p("status","closed");for(let t of this.#u.values())t.clear();this.#u.clear()}}};export{We as SocketIoTransport,is as Ulda,b as UldaError};